This chapter, and the next chapters, will provide a high-level overview of topics related to database development. These topics will cover the theoretical aspect of relational databases. The first two chapters try to summarize theoretical topics that are seen on a daily basis. Understanding these theoretical concepts will enable the developers to not only come up with clean designs, but also to master relational databases.
This chapter is not restricted to learning PostgreSQL, but covers all relational databases. The topics covered in this chapter include the following:
Different database management systems support diverse application scenarios, use cases, and requirements. Database management systems have a long history. First, we will quickly take a look at the recent history, and then explore the market-dominant database management system categories.
Broadly, the term database can be used to present a collection of things. Moreover, this term brings to mind many other terms including data, information, data structure, and management. A database can be defined as a collection or repository of data, which has a certain structure, managed by a database management system (DBMS). Data can be structured as tabular data, semi-structured as XML documents, or unstructured data that does not fit a predefined data model.
In the early days, databases were mainly aimed at supporting business applications; this led us to the well-defined relational algebra and relational database systems. With the introduction of object-oriented languages, new paradigms of database management systems appeared such as object-relational databases and object-oriented databases. Also, many businesses as well as scientific applications use arrays, images, and spatial data; thus, new models such as raster, map, and array algebra are supported. Graph databases are used to support graph queries such as the shortest path from one node to another, along with supporting traversal queries easily.
With the advent of web applications such as social portals, it is now necessary to support a huge number of requests in a distributed manner. This has led to another new paradigm of databases called NoSQL (Not Only SQL), which has different requirements such as performance over fault tolerance and horizontal scaling capabilities. In general, the timeline of database evolution was greatly affected by many factors such as the following:
Many database models have appeared and vanished such as the network model and hierarchical model. The predominant categories now in the market are relational, object-relational databases, and NoSQL databases. One should not think of NoSQL and SQL databases as rivals--they are complementary to each other. By utilizing different database systems, one can overcome many limitations and get the best of different technologies.
The NoSQL databases are affected by the CAP theorem, also known as Brewer's theorem. In 2002, S. Gilbert and N. Lynch published a formal proof of the CAP theorem in their article, Brewer's conjecture and the feasibility of consistent, available, partition-tolerant web services. In 2009, the NoSQL movement began. Currently, there are over 150 NoSQL databases (nosql-database.org).
The CAP theorem states that it is impossible for a distributed computing system to simultaneously provide all three of the following guarantees:
The choice of which feature to discard determines the nature of the system. For example, one could sacrifice consistency to get a scalable, simple, and high performance database management system. Often, the main difference between a relational database and a NoSQL database is consistency. A relational database enforces ACID (atomicity, consistency, isolation, durability) properties. In contrast, many NoSQL databases adopt the basically available soft-state, eventual consistency (base) model.
A NoSQL database provides a means for data storage, manipulation, and retrieval for non-relational data. The NoSQL databases are distributed, open source, and horizontally scalable. NoSQL often adopts the base model, which prizes availability over consistency, and informally guarantees that if no new updates are made on a data item, eventually all access to that data item will return the latest version of that data item. The advantages of this approach include the following:
We will now explore a few types of NoSQL databases.
The key-value store is the simplest database store. In this database model, the storage, as its name suggests, is based on maps or hash tables. Some key-value databases allow complex values to be stored as lists and hash tables. Key-value pairs are extremely fast for certain scenarios, but lack the support for complex queries and aggregation. Some of the existing open source key-value databases are Riak, Redis, Memebase, and MemcacheDB.
Columnar or column-oriented databases are based on columns. Data in a certain column in a two-dimensional relation is stored together.
Unlike relational databases, adding columns is inexpensive and is done on a row-by-row basis. Rows can have a different set of columns. Tables can benefit from this structure by eliminating the storage cost of the null values. This model is best suited for distributed databases.
HBase is one of the most famous columnar databases. It is based on the Google Bigtable storage system. Column-oriented databases are designed for huge data scenarios, so they scale up easily. For small datasets, HBase is not a suitable architecture. First, the recommended hardware topology for HBase is a five-node or server deployment. Also, it needs a lot of administration and is difficult to master and learn.
A document-oriented database is suitable for documents and semi-structured data. The central concept of a document-oriented database is the notion of a document. Documents encapsulate and encode data (or information) in some standard formats or encodings such as XML, JSON, and BSON. Documents do not adhere to a standard schema or have the same structure, so they provide a high degree of flexibility. Unlike relational databases, changing the structure of the document is simple and does not lock the clients from accessing the data.
Document databases merge the power of relational databases and column-oriented databases. They provide support for ad hoc queries and can be scaled up easily. Depending on the design of the document database, MongoDB is designed to handle a huge amount of data efficiently. On the other hand, CouchDB provides high availability even in the case of hardware failure.
Graph databases are based on the graph theory, where a database consists of nodes and edges. The nodes as well as the edges can be assigned data. Graph databases allow traversing between the nodes using edges. As a graph is a generic data structure, graph databases are capable of representing different data. A famous implementation of an open source commercially supported graph database is Neo4j.
Relational database management systems are one of the most widely-used DBMSs in the world. It is highly unlikely that any organization, institution, or personal computer today does not have or use a piece of software that rely on RBDMS. Software applications can use relational databases via dedicated database servers or via lightweight RDBMS engines, embedded in the software applications as shared libraries. The capabilities of a relational database management system vary from one vendor to another, but most of them adhere to the ANSI SQL standards. A relational database is formally described by relational algebra, and is based on the relational model. Object-relational database (ORD) are similar to relational databases. They support the following object-oriented model concepts:
In a relational database, a single logical operation is called a transaction. The technical translation of a transaction is a set of database operations, which are create, read, update, and delete (CRUD). An example of explaining a transaction is budget assignment to several projects in the company assuming we have a fixed amount of money. If we increase a certain project budget, we need to deduct this amount of increase from another project. The ACID properties in this context could be described as follows:
Relational databases are often linked to the structured query language (SQL). SQL is a declarative programming language and is the standard relational database language. The American National Standard Institute (ANSI) and the International Standard Organization (ISO) published the SQL standard for the first time in 1986, followed by many versions such as SQL:1999, SQL:2003, SQL:2006, SQL:2008, SQL:2011, and SQL:2016. The SQL language has several parts:
A relational model is a first-order predicate logic, which was first introduced by Edgar F. Codd in 1970 in his paper A relational model of data for large shared data banks. A database is represented as a collection of relations. The state of the whole database is defined by the state of all the relations in the database. Different information can be extracted from the relations by joining and aggregating data from different relations and by applying filters on the data. In this section, the basic concepts of the relational model are introduced using the top-down approach by first describing the relation, tuple, attribute, and domain.
The terms relation, tuple, attribute, and unknown, which are used in the formal relational model, are equivalent to table, row, column, and null in the SQL language.
Think of a relation as a table with a header, columns, and rows. The table name and the header help in interpreting the data in the rows. Each row represents a group of related data, which points to a certain object.
A relation is represented by a set of tuples. Tuples should have the same set of ordered attributes. Attributes have a domain, that is, a type and a name:
customer_id | first_name | last_name | ||
---|---|---|---|---|
Tuple → | 1 | thomas | sieh | thomas@example.com |
Tuple → | 2 | wang | kim | kim@example.com |
Attribute ↑ | Attribute ↑ | Attribute ↑ | Attribute ↑ |
The relation schema is denoted by the relation name and the relation attributes. For example, customer (customer_id, first_name, last_name, and email)
is the relation schema for the customer relation. Relation state is defined by the set of relation tuples; thus, adding, deleting, and amending a tuple will change the relation to another state.
Tuple order or position in the relation is not important, and the relation is not sensitive to tuple order. The tuples in the relation could be ordered by a single attribute or a set of attributes. Also, a relation cannot have duplicate tuples.
A relation can represent entities in the real world, such as a customer, or can be used to represent an association between relations. For example, the customer could have several services and a service can be offered to several customers. This could be modeled by three relations: customer
, service
, and customer_service
. The customer_service
relation associates the customer and the service relations. Separating the data in different relations is a key concept in relational database modeling, which is called normalization. Normalization is the process of organizing relation columns and relations to reduce data redundancy. For example, assume that a collection of services is stored in the customer relation. If a service is assigned to multiple customers, this would result in data redundancy. Also, updating a certain service would require updating all its copies in the customer table.
A tuple is a set of ordered attributes. They are written by listing the elements within parentheses () and separated by commas, such as (john, smith, 1971). Tuple elements are identified via the attribute name. Tuples have the following properties:
In the formal relational model, multi-valued attributes as well as composite attributes are not allowed. This is important to reduce data redundancy and increase data consistency. This isn't strictly true in modern relational database systems because of the utilization of complex data types such as JSON and key-value stores.
Predicates in relational databases use three-valued logic (3VL), where there are three truth values: true, false, and unknown aka NULL. In a relational database, the third value, NULL, can be interpreted in many ways, such as unknown data, missing data, not applicable, or will be loaded later. The three-valued logic is used to remove ambiguity. For example, no two NULL values are equal.
The following table shows logical OR / AND truth operator; note that these operators are commutative, that is, A AND B = B AND A:
A | B | A AND B | A OR B |
---|---|---|---|
TRUE | TRUE | TRUE | TRUE |
FALSE | TRUE | FALSE | TRUE |
NULL | TRUE | NULL | TRUE |
FALSE | FALSE | FALSE | FALSE |
NULL | FALSE | FALSE | NULL |
NULL | NULL | NULL | NULL |
The following table shows the NOT truth operator:
A | NOT A |
---|---|
TRUE | FALSE |
FALSE | TRUE |
NULL | NULL |
Each attribute has a name and a domain, and the name should be distinct within the relation. The domain defines the possible set of values that the attribute can have. One way to define the domain is to define the data type and a constraint on this data type. For example, hourly wage should be a positive real number and bigger than five if we assume that the minimum hourly wage is five dollars. The domain could be continuous, such as salary, which is any positive real number, or discrete, such as gender.
The formal relational model puts a constraint on the domain: the value should be atomic. Atomic means that each value in the domain is indivisible. For instance, the name attribute domain is not atomic because it can be divided into first name and last name. Some examples of domains are as follows:
The relational model defines many constraints in order to control data integrity, redundancy, and validity:
We could classify the constraints in a relational database roughly into two categories:
The domain integrity constraint ensures data validity. The first step in defining the domain integrity constraint is to determine the appropriate data type. The domain data types could be integer, real, boolean, character, text, inet, and so on. For example, the data type of first name and email address is text. After specifying the data type, check constraints, such as the mail address pattern, need to be defined.
customer_service
schema is defined as customer_id
, service_id
, start_date
, end_date
, order_date
. For this relation, we can have a check constraint to make sure that start_date
and end_date
are entered correctly by applying the following check start_date
<end_date
.
customer_service
relation, order_date
can have a default value, which is the current date.player_id
, player_nickname
). The player uses his ID to play with others; he can also pick up a nickname which is also unique to identify himself.In the relational model, a relation is defined as a set of tuples. This means that all the tuples in a relation must be distinct. The entity integrity constraint is enforced by having a primary key which is an attribute/set of attributes having the following characteristics:
Each relation must have only one primary key, but can have many unique keys. A candidate key is a minimal set of attributes that can identify a tuple. All unique, not null attributes can be candidate keys. The set of all attributes form a super key. In practice, we often pick up a single attribute to be a primary key instead of a compound key ( a key that consists of two or more attributes that uniquely identify a tuple) to ease the joining of the relations with each other.
If the primary key is generated by the DBMS, then it is called a surrogate key or synthetic key . Otherwise, it is called a natural key. The surrogate key candidates can be sequences and universal unique identifiers (UUID). A surrogate key has many advantages such as performance, requirement change tolerance, agility, and compatibility with object relational mappers. The chief disadvantage of surrogate keys is that , it makes redundant tuples possible.
Relations are associated with each other via common attributes. Referential integrity constraints govern the association between two relations and ensure data consistency between tuples. If a tuple in one relation references a tuple in another relation, then the referenced tuple must exist. In the customer service example, if a service is assigned to a customer, then the service and the customer must exist, as shown in the following example. For instance, in the customer_service
relation, we cannot have a tuple with values (5, 1,01-01-2014, NULL)
, because we do not have a customer with customer_id
equal to 5
.
The lack of referential integrity constraints can lead to many problems:
Foreign keys can increase performance in reading data from multiple tables. The query execution planner will have a better estimation of the number of rows that need to be processed. Disabling foreign keys when doing a bulk insert will lead to a performance boost.
Referential integrity constraints are achieved via foreign keys. A foreign key is an attribute or a set of attributes that can identify a tuple in the referenced relation. As the purpose of a foreign key is to identify a tuple in the referenced relation, foreign keys are generally primary keys in the referenced relation. Unlike a primary key, a foreign key can have a null value. It can also reference a unique attribute in the referenced relation. Allowing a foreign key to have a null value enables us to model different cardinality constraints. Cardinality constraints define the participation between two different relations. For example, a parent can have more than one child; this relation is called one-to-many relationship, because one tuple in the referenced relation is associated with many tuples in the referencing relation. Also, a relation could reference itself. This foreign key is called a self-referencing or recursive foreign key.
For example, a company acquired by another company:
To ensure data integrity, foreign keys can be used to define several behaviors when a tuple in the referenced relation is updated or deleted. The following behaviors are called referential actions:
Integrity constraints or business logic constraints describe the database application constraints in general. These constraints are either enforced by the business logic tier of the application program or by SQL procedural languages. Trigger and rule systems can also be used for this purpose. For example, the customer should have at most one active service at a time. Based on the nature of the application, one could favor using an SQL procedural language or a high-level programming language to meet the semantic constraints, or mix the two approaches.
The advantages of using the SQL programming language are as follows:
Relational algebra is the formal language of the relational model. It defines a set of closed operations over relations, that is, the result of each operation is a new relation. Relational algebra inherits many operators from set algebra. Relational algebra operations can be categorized into two groups:
The first one is a group of operations that are inherited from a set theory such as union
, intersection
, set difference
, and cartesian product
, also known as cross product
.
The second is a group of operations that are specific to the relational model such as select
and project
. Relational algebra operations could also be classified as binary and unary operations.
The primitive operators are as follows:
select
(σ): A unary operation written as σϕR where ϕ is a predicate. The selection retrieves the tuples in R, where ϕ holds.project
(π): A unary operation used to slice the relation in a vertical dimension, that is, attributes. This operation is written as πa1,a2,…,an R(), where a1, a2, ..., an are a set of attribute names.cartesian product
(×): A binary operation used to generate a more complex relation by joining each tuple of its operands together. Let's assume that R and S are two relations, then R×S = (r1, r2, ..., rn, s1, s2, ..., sn) where (r1, r2,...,rn) ∈ R and (s1, s2, ..., sn) ∈ S.union
(∪): Appends two relations together; note that the relations should be union compatible, that is, they should have the same set of ordered attributes. Formally, R∪S = (r1,r2,...rn) ∪ (s1,s2,...,sn) where (r1, r2,...,rn) ∈ R and (s1, s2, ..., sn) ∈ S.difference
(-): A binary operation in which the operands should be union compatible. Difference creates a new relation from the tuples, which exist in one relation but not in the other. The set difference for the relation R and S can be given as R-S = (r1,r2,...rn) where (r1,r2,...rn) ∈ R and (r1,r2,...rn) ∉ S.rename
(ρ): A unary operation that works on attributes. This operator is mainly used to distinguish the attributes with the same names but in different relation when joined together, or it is used to give more user friendly name for the attribute for presentation purposes. Rename is expressed as ρa/bR, where a and b are attribute names and b is an attribute of R.In addition to the primitive operators, there are aggregation functions such as sum
, count
, min
, max
, and avg
aggregates. Primitive operators can be used to define other relation operators such as left-join, right-join, equi-join, and intersection. Relational algebra is very important due to its expressive power in optimizing and rewriting queries. For example, the selection is commutative, so σaσbR = σbσaR. A cascaded selection may also be replaced by a single selection with a conjunction of all the predicates, that is, σaσbR = σa AND b R.
SELECT
is used to restrict tuples from the relation. SELECT
always returns a unique set of tuples this is inherited form entity integrity constraint. For example, the query give me the customer information where the customer_id equals to 2 is written as follows:
σcustomer_id =2 customer
The selection, as mentioned earlier, is commutative; the query give me all customers where the customer mail is known, and the customer first name is kim is written in three different ways, as follows:
σemail is not null(σfirst_name =kim customer)
σfirst_name =kim(σemail is not null customer)
σfirst_name =kim and email is not null (customer)
The selection predicates are certainly determined by the data types. For numeric data types, the comparison operator might be ≠, =, <, >, ≥, or ≤. The predicate expression can also contain complex expressions and functions. The equivalent SQL statement for the SELECT
operator is the SELECT *
statement, and the predicate is defined in the WHERE
clause.
The symbol *
means all the relation attributes; note that in the production environment, it is not recommended to use *
. Instead, one should list all the relation attributes explicitly.
The following SELECT
statement is equivalent for the relational algebra expression σ</span>customer_id =2 customer:
SELECT * FROM customer WHERE customer_id = 2;
The project operation could be visualized as vertical slicing of the table. The query, give me the customer names, is written in relational algebra as follows:
π first_name, last_name customer
The following is the result of projection expression:
first_name | last_name |
---|---|
thomas | sieh |
wang | kim |
Duplicate tuples are not allowed in the formal relational model; the number of returned tuples from the PROJECT
operator is always equal to or less than the number of total tuples in the relation. If a PROJECT
operator's attribute list contains a primary key, then the resulting relation has the same number of tuples as the projected relation.
The projection operator also can be optimized, for example, cascading projections could be optimized as the following expression:
πa(πa,πb(R)) = πa(R)
The SQL equivalent for the PROJECT
operator is SELECT DISTINCT
. The DISTINCT
keyword is used to eliminate duplicates. To get the result shown in the preceding expression, one could execute the following SQL statement:
SELECT DISTINCT first_name, last_name FROM customers;
The sequence of the execution of the PROJECT
and SELECT
operations can be interchangeable in some cases. The query give me the name of the customer with customer_id equal to 2 could be written as follows:
σcustomer_id =2 (π first_name, last_name customer)
π first_name, last_name(σcustomer_id =2 customer)
In other cases, the PROJECT
and SELECT
operators must have an explicit order as shown in the following example; otherwise, it will lead to an incorrect expression. The query, give me the last name of the customers where the first name is kim, could be written in the following way:
π last_name(σfirst_name=kim customer)
The rename
operation is used to alter the attribute name of the resultant relation or to give a specific name to the resultant relation. The rename
operation is used to perform the following:
The AS
keyword in SQL is the equivalent of the rename
operator in relational algebra. The following SQL example creates a relation with one tuple and one attribute, which is renamed PI:
SELECT 3.14::real AS PI;
The set theory operations are union
, intersection
, and minus
(difference). Intersection
is not a primitive relational algebra operator, because it can be written using the union and difference operators:
A∩B = ((A∪B)-(A-B))-(B-A)
The intersection and union are commutative:
A∩B=B∩A
A∪B=B∪A
For example, the query, give me all the customer IDs where the customer does not have a service assigned to him, could be written as follows:
πcustomer_id customer-πcustomer_id customer_service
The cartesian product
operation is used to combine tuples from two relations into a single one. The number of attributes in single relation equals the sum of the number of attributes of the two relations. The number of tuples in the single relation equals the product of the number of tuples in the two relations. Let's assume that A and B are two relations, and C = A × B:
The number of attribute of C = the number of attribute in A + the number of attribute of B
The number of tuples of C = the number of tuples of A * The number of tuples of B
The following image shows the cross join of customer and customer service:
The equivalent SQL join for Cartesian product
is CROSS JOIN
, the query for the customer with customer_id equal to 1, retrieve the customer id, name and the customer service IDs can be written in SQL as follows:
SELECT DISTINCT customer_id, first_name, last_name, service_id FROM customer AS c CROSS JOIN customer_service AS cs WHERE c.customer_id=cs.customer_id AND c.customer_id = 1;
In the preceding example, one can see the relationship between relational algebra and the SQL language. For example, we have used select
, rename
, project
, and Cartesian product
. The preceding example shows how relational algebra could be used to optimize query execution. This example could be executed in several ways:
Execution plan 1:
customer_id = 1
.customer_id = 1
.Cross JOIN
the relations resulting from steps 1 and 2.customer_id
, first_name
, last_name
, and service_id
from the relation resulting from step 3.Execution plan 2:
Cross JOIN
customer and customer_service
.Customer_service.customer_id=customer.customer_id
and customer.customer_id = 1
.customer_id
, first_name
, last_name
, and service_id
from the relation resulting from step 2.
The SELECT
query is written in this way to show how to translate relational algebra to SQL. In modern SQL code, we can project attributes without using DISTINCT
. In addition to that, one should use a proper join instead of cross join.
Each execution plan has a cost in terms of CPU, random access memory (RAM), and hard disk operations. The RDBMS picks the one with the lowest cost. In the preceding execution plans, the rename
as well as distinct
operator were ignored for simplicity.
Data models describe real-world entities such as customer, service, products, and the relation between these entities. Data models provide an abstraction for the relations in the database. Data models aid the developers in modeling business requirements, and translating business requirements to relations. They are also used for the exchange of information between the developers and business owners.
In the enterprise, data models play a very important role in achieving data consistency across interacting systems. For example, if an entity is not defined, or is poorly defined, then this will lead to inconsistent and misinterpreted data across the enterprise. For instance, if the semantics of the customer entity not defined clearly, and different business departments use different names for the same entity such as customer and client, this may lead to confusion in the operational departments.
Data model perspectives are defined by ANSI as follows:
According to ANSI, this abstraction allows changing one part of the three perspectives without amending the other parts. One could change both the logical and the physical data models without changing the conceptual model. To explain, sorting data using bubble or quick sort is not of interest for the conceptual data model. Also, changing the structure of the relations could be transparent to the conceptual model. One could split one relation into many relations after applying normalization rules, or by using enum
data types in order to model the lookup tables.
The entity-relation (ER) model falls in the conceptual data model category. It captures and represents the data model for both business users and developers. The ER model can be transformed into the relational model by following certain techniques.
Conceptual modeling is a part of the software development life cycle (SDLC). It is normally done after the functional and data requirements-gathering stage. At this point, the developer is able to make the first draft of the ER diagram as well as describe functional requirements using data flow diagrams, sequence diagrams, user stories, and many other techniques.
During the design phase, the database developer should give great attention to the design, run a benchmark stack to ensure performance, and validate user requirements. Developers modeling simple systems could start coding directly. However, care should be taken when making the design, since data modeling involves not only algorithms in modeling the application but also data. The change in design might lead to a lot of complexities in the future such as data migration from one data structure to another.
While designing a database schema, avoiding design pitfalls is not enough. There are alternative designs, where one could be chosen. The following pitfalls should be avoided:
In order to explain the basics of the ER model, an online web portal to buy and sell cars will be modeled. The requirements of this sample application are listed as follows, and an ER model will be developed step by step:
The ER diagram represents entities, attributes, and relationships. An entity is a representation of a real-world object such as car or a user. An attribute is a property of an object and describes it. A relationship represents an association between two or more entities.
The attributes might be composite or simple (atomic). Composite attributes can be divided into smaller subparts. A subpart of a composite attribute provides incomplete information that is semantically not useful by itself. For example, the address is composed of street name, building number, and postal code. Any one of them isn't useful alone without its counterparts.
Attributes could also be single-valued or multi-valued. The color of a bird is an example of a multi-valued attribute. It can be red and black, or a combination of any other colors. A multi-valued attribute can have a lower and upper bound to constrain the number of values allowed. In addition, some attributes can be derived from other attributes. Age can be derived from the birth date. In our example, the final rank of a seller is derived from the number of advertisements and the user ratings.
Finally, key attributes can identify an entity in the real world. A key attribute should be marked as a unique attribute, but not necessarily as a primary key, when physically modeling the relation. Finally, several attribute types could be grouped together to form a complex attribute.
Entities should have a name and a set of attributes. They are classified into the following:
A weak entity is usually related to another strong entity. This strong entity is called the identifying entity. Weak entities have a partial key, aka discriminator, which is an attribute that can uniquely identify the weak entity, and it is related to the identifying entity. In our example, if we assume that the search key is distinct each time the user searches for cars, then the search key is the partial key. The weak entity symbol is distinguished by surrounding the entity box with a double line.
The next image shows the preliminary design of car portal application. The user entity has several attributes. The name attribute is a composite attribute, and email is a key attribute. The seller entity is a specialization of the user entity. The total rank is a derived attribute calculated by aggregating the user ratings and the number of advertisements. The color attribute of the car is multi-valued. The seller can be rated by the users for certain advertisements; this relation is a ternary relation, because the rating involves three entities which are car, seller, and user. The car picture is a subpart attribute of the advertisement. The following diagram shows that the car can be advertised more than once by different sellers. In the real world, this makes sense, because one could ask more than one seller to sell his car.
When an attribute of one entity refers to another entity, some relationships exist. In the ER model, these references should not be modeled as attributes but as relationships or weak entities. Similar to entities, there are two classes of relationships: weak and strong. Weak relationships associate the weak entities with other entities. Relationships can have attributes as entities. In our example, the car is advertised by the seller; the advertisement date is a property of the relationship.
Relationships have cardinality constraints to limit the possible combinations of entities that participate in a relationship. The cardinality constraint of car and seller is 1:N; the car is advertised by one seller, and the seller can advertise many cars. The participation between seller and user is called total participation, and is denoted by a double line. This means that a seller cannot exist alone, and he must be a user.
The many-to-many relationship cardinality constraint is denoted by N:M to emphasize different participation from the entities.
Up until now, only the basic concepts of ER diagrams have been covered. Some concepts such as (min, max) cardinality notation, ternary/n-ary relationships, generalization, specialization, and enhanced entity relation diagrams (EER) have not been discussed.
The rules to map an ER diagram to a set of relations (that is, the database schema) are almost straightforward but not rigid. One could model an entity as an attribute, and then refine it to a relationship. An attribute which belongs to several entities can be promoted to be an independent entity. The most common rules are listed as follows (note that only basic rules have been covered, and the list is not exhaustive):
Unified modeling language (UML) is a standard developed by the Object Management Group (OMG). UML diagrams are widely used in modeling software solutions, and there are several types of UML diagrams for different modeling purposes including class, use case, activity, and implementation diagrams.
A class diagram can represent several types of associations, that is, the relationship between classes. They can depict attributes as well as methods. An ER diagram can be easily translated into a UML class diagram. UML class diagrams also have the following advantages:
The design of a database management system is affected by the CAP theorem. Relational databases and NoSQL databases are not rivals but complementary. One can utilize different database categories in a single software application. In certain scenarios, one can use the key-value store as a cache engine on top of the relational database to gain performance.
Relational and object-relational databases are the market-dominant databases. Relational databases are based on the concept of relation and have a very robust mathematical model. Object-relational databases such as PostgreSQL overcome the limitations of relational databases by introducing complex data types, inheritance, and rich extensions.
Relational databases are based on the relation, tuple, and attribute concepts. They ensure data validity and consistency by employing several techniques such as entity integrity, constraints, referential integrity, and data normalization.
The next chapter, provides first-hand experience in installing the PostgreSQL server and client tools on different platforms. The next chapter also introduces PostgreSQL capabilities, such as out-of-the-box replication support and its very rich data types.
Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.
If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.
Please Note: Packt eBooks are non-returnable and non-refundable.
Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:
If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:
Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.
You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.
Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.
When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.
For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.