Relational model: Difference between revisions

Content deleted Content added
m Added related page numbers to citation
m Disambiguating links to Object-orientation (link changed to Object-oriented programming) using DisamAssist.
 
(165 intermediate revisions by 99 users not shown)
Line 1:
{{short description|Database model}}
The '''relational model''' ('''RM''') for [[database]] management is an approach to managing data using a structure and language consistent with [[first-order logic|first-order predicate logic]], first described in 1969 by [[Edgar F. Codd]].<ref>{{Citation | title = Derivability, Redundancy, and Consistency of Relations Stored in Large Data Banks | first = E.F | last = Codd | publisher = IBM | series = Research Report | year = 1969}}.</ref><ref name= "codd1970">{{cite journal|last= Codd |first= E.F |year=1970|title=A Relational Model of Data for Large Shared Data Banks | series = Classics | url= http://www.acm.org/classics/nov95/toc.html |journal=[[Communications of the ACM]] |volume= 13 |issue= 6 |pages= 377–87 |doi= 10.1145/362384.362685}}</ref> In the relational model of a database, all data is represented in terms of [[tuple]]s, grouped into [[relation (database) |relation]]s. A database organized in terms of the relational model is a [[relational database]].
The '''relational model''' ('''RM''') is an approach to managing [[data]] using a [[Structure (mathematical logic)|structure]] and language consistent with [[first-order logic|first-order predicate logic]], first described in 1969 by English computer scientist [[Edgar F. Codd]],<ref>{{Citation | title = Derivability, Redundancy, and Consistency of Relations Stored in Large Data Banks | first = E.F | last = Codd | publisher = IBM | series = Research Report | year = 1969}}.</ref><ref name="codd1970">{{cite journal |last= Codd |first= E.F |year= 1970 |title= A Relational Model of Data for Large Shared Data Banks |series= Classics |journal= [[Communications of the ACM]] |volume= 13 |issue= 6 |pages= 377–87 |doi= 10.1145/362384.362685 |s2cid= 207549016 |doi-access= free }}</ref> where all data are represented in terms of [[tuple]]s, grouped into [[relation (database)|relation]]s. A database organized in terms of the relational model is a [[relational database]].
 
The purpose of the relational model is to provide a [[Declarative programming|declarative]] method for specifying data and queries: users directly state what information the database contains and what information they want from it, and let the [[database management system|database management system software]] take care of describing data structures for storing the data and retrieval procedures for answering queries.
[[File:Relational Model.svg|thumb|280px|Diagram of an example database according to the relational model<ref name="USDT01">{{Citation | format = [[Portable document format |PDF]] | url = http://knowledge.fhwa.dot.gov/tam/aashto.nsf/All+Documents/4825476B2B5C687285256B1F00544258/$FILE/DIGloss.pdf | title = Data Integration Glossary | place = [[United States of America |US]] | publisher = Department of Transportation | date = August 2001}}.</ref>]]
[[File:Relational key.png|thumb|280px|In the relational model, related records are linked together with a "key".]]
The purpose of the relational model is to provide a [[Declarative programming |declarative]] method for specifying data and queries: users directly state what information the database contains and what information they want from it, and let the database management system software take care of describing data structures for storing the data and retrieval procedures for answering queries.
 
Most relational databases use the [[SQL]] data definition and query language; these systems implement what can be regarded as an engineering approximation to the relational model. A ''[[Table (database)|table]]'' in ana SQL [[database schema]] corresponds to a predicate variable; the contents of a table to a relation; key constraints, other constraints, and SQL queries correspond to predicates. However, SQL databases [[#SQL and the relational model|deviate from the relational model in many details]], and Codd fiercely argued against deviations that compromise the original principles.<ref>{{Citation | first = E. F | last = Codd | title = The Relational Model for Database Management | publisher = Addison-Wesley | year = 1990 | ISBNisbn = 978-0-201-14192-24 | pages=371-388371–388}}.</ref>
 
== Overview ==
The relational model's central idea is to describe a database as a collection of [[Predicate (mathematical logic)|predicate]]s over a finite set of predicate variables, describing [[constraint (database) |constraints]] on the possible values and combinations of values. The content of the database at any given time is a finite (logical) [[model (logic) |model]] of the database, i.e. a set of [[Relation (database)|relation]]s, one per predicate variable, such that all predicates are satisfied. A request for information from the database (a [[database query]]) is also a predicate.
[[File:Relational model concepts.png|thumb|360px|Relational model concepts.]]
 
=== Alternatives ===
Other [[model (abstract)|models]] are the [[Hierarchical database model|hierarchical model]] and [[network model]]. Some [[system]]s using these older architectures are still in use today in [[data center]]s with high data volume needs, or where existing systems are so complex and abstract it would be cost-prohibitive to migrate to systems employing the relational model; also of note are newer [[object database|object-oriented databases]].
 
=== Implementation ===
There have been several attempts to produce a true implementation of the relational database model as originally defined by [[Edgar F. Codd|Codd]] and explained by [[Christopher J. Date |Date]], [[Hugh Darwen |Darwen]] and others, but none have been popular successes so far. {{As of |2015|10}} [[Rel (DBMS) |Rel]] is one of the more recent attempts to do this.
 
The relational model was the first database model to be described in formal mathematical terms. Hierarchical and network databases existed before relational databases, but their specifications were relatively informal. After the relational model was defined, there were many attempts to compare and contrast the different models, and this led to the emergence of more rigorous descriptions of the earlier models; though the procedural nature of the data manipulation interfaces for hierarchical and network databases limited the scope for formalization.<ref>{{Citation | title = Database Administration: High-impact Strategies – What You Need to Know: Definitions, Adoptions, Impact, Benefits, Maturity, Vendors | first = Kevin | last = Roebuck | publisher = Emereo | year = 2012 | ISBN = 978-1-74304877-1 | url = https://books.google.com/books?id=piUPBwAAQBAJ}}.</ref>{{Page needed |date=October 2015}}
 
== History ==
The relational model was inventeddeveloped by [[Edgar F. Codd|E.F. (Ted) Codd]] as a general model of data, and subsequently maintained and developedpromoted by [[Christopher J. Date|Chris Date]] and [[Hugh Darwen]] among others. In [[their 1995 ''The Third Manifesto]] (first published in 1995)'', Date and Darwen showtry to demonstrate how the relational model can accommodate certain "desired" [[Object-oriented programming|object-oriented]] features.<ref>{{Cite web |title=Did Date and Darwen's "Third Manifesto" have a lasting impact? |url=https://cs.stackexchange.com/questions/99350/did-date-and-darwens-third-manifesto-have-a-lasting-impact |access-date=2024-08-03 |website=Computer Science Stack Exchange |language=en}}</ref>
 
=== ControversiesExtensions ===
Codd himself, someSome years after publication of his 1970 model, Codd proposed a [[three-valued logic]] (True, False, Missing or /[[Null (SQL) |NULL]]) version of it to deal with missing information, and in his ''The Relational Model for Database Management Version 2'' (1990) he went a step further with a four-valued logic (True, False, Missing but Applicable, Missing but Inapplicable) version.<ref>{{cite book| first =C.Christopher J. | last = Date|title=Date on Database: Writings 2000–2006|date= 2006 |publisher= Apress|isbn= 978-1-59059-746-0|pages=329–41|chapter= 18. Why Three- and Four-Valued Logic Don't Work}}</ref> But these have never been implemented, presumably because of attending complexity. SQL's NULL construct was intended to be part of a three-valued logic system, but fell short of that due to logical errors in the standard and in its implementations.<ref>{{cite book | first =C.J | last = Date|title=An Introduction to Database Systems|date=2004|publisher= Addison Wesley |isbn=0-321-19784-4|pages=592–97|edition= 8}}</ref>
 
== TopicsConceptualization ==
The fundamental assumption of the relational model is that all [[data]] is represented as mathematical ''n''-[[arity|ary]] '''[[Relation (database)|relation]]s''', an ''n''-ary relation being a [[subset]] of the [[Cartesian product]] of ''n'' domains. In the mathematical model, [[reasoning]] about such data is done in two-valued [[predicate logic]], meaning there are two possible [[evaluation]]s for each [[proposition]]: either ''true'' or ''false'' (and in particular no third value such as ''unknown'', or ''not applicable'', either of which are often associated with the concept of [[Null (SQL)|NULL]]). Data are operated upon by means of a [[relational calculus]] or [[relational algebra]], these being equivalent in [[expressive power (computer science)|expressive power]].
 
=== Basic concepts ===
The relational model of data permits the database designer to create a consistent, logical representation of [[information]]. Consistency is achieved by including declared '''''[[constraint (database)|constraint]]s''''' in the database design, which is usually referred to as the logical schema. The theory includes a process of [[database normalization]] whereby a design with certain desirable properties can be selected from a set of [[Logical equivalence |logically equivalent]] alternatives. The [[access plan]]s and other implementation and operation details are handled by the [[DBMS]] engine, and are not reflected in the logical model. This contrasts with common practice for SQL DBMSs in which [[performance tuning]] often requires changes to the logical model.
[[File:Relational database terms.svg|thumb|A relation with 5 attributes (its degree) and 4 tuples (its cardinality) can be visualized as a table with 5 columns and 4 rows. However, unlike rows and columns in a table, a relation's attributes and tuples are unordered.]]
 
A ''relation'' consists of a ''heading'' and a ''body''. The heading defines a [[Set (mathematics)|set]] of ''attributes'', each with a ''name'' and ''data type'' (sometimes called a ''___domain''). The number of attributes in this set is the relation's ''degree'' or ''[[arity]]''. The body is a set of ''tuples''. A tuple is a collection of ''n'' ''values'', where ''n'' is the relation's degree, and each value in the tuple corresponds to a unique attribute.<ref>{{Cite web |date=2023-02-12 |title=Tuple in DBMS |url=https://www.geeksforgeeks.org/tuple-in-dbms/ |access-date=2024-08-03 |website=GeeksforGeeks |language=en-US}}</ref> The number of tuples in this set is the relation's ''[[cardinality]]''.<ref name="professionals"/>{{rp|17–22}}
The basic relational building block is the [[Data ___domain|___domain]] or [[data type]], usually abbreviated nowadays to '''''type'''''. A ''[[tuple]]'' is an ordered [[set (mathematics) |set]] of '''''attribute values'''''. An [[Attribute (computing)|attribute]] is an ordered pair of '''''attribute name''''' and '''''type name'''''. An attribute value is a specific valid value for the type of the attribute. This can be either a scalar value or a more complex type.
 
Relations are represented by ''relational [[Variable (computer science)|variables]]'' or ''relvars'', which can be reassigned.<ref name="professionals"/>{{rp|22–24}} A ''[[database]]'' is a collection of relvars.<ref name="professionals"/>{{rp|112–113}}
A relation consists of a '''''heading''''' and a '''''body'''''. A heading is a set of attributes. A body (of an ''n''-ary relation) is a set of ''n''-tuples. The heading of the relation is also the heading of each of its tuples.
 
In this model, databases follow the ''Information Principle'': At any given time, all [[Information theory|information]] in the database is represented solely by values within tuples, corresponding to attributes, in relations identified by relvars.<ref name="professionals"/>{{rp|111}}
A relation is defined as a [[set (mathematics) |set]] of ''n''-tuples. In both mathematics and the relational database model, a set is an ''unordered'' collection of unique, non-duplicated items, although some DBMSs impose an order to their data. In mathematics, a [[tuple]] has an order, and allows for duplication. [[Edgar F. Codd|E.{{nbsp}}F. Codd]] originally defined tuples using this mathematical definition.<ref name= "codd1970"/> Later, it was one of [[Edgar F. Codd |E.{{nbsp}}F. Codd]]'s great insights that using attribute names instead of an ordering would be so much more convenient (in general) in a computer language based on relations {{Citation needed |date= February 2007}}. This insight is still being used today. Though the concept has changed, the name "tuple" has not. An immediate and important consequence of this distinguishing feature is that in the relational model the [[Cartesian product]] becomes [[Commutative operation |commutative]].
 
=== Constraints ===
A [[table (database)|table]] is an accepted visual representation of a relation; a tuple is similar to the concept of a ''[[row (database) |row]]''.
 
A database may define arbitrary [[boolean expressions]] as [[constraint (database)|constraints]]. If all constraints evaluate as ''true'', the database is ''consistent''; otherwise, it is ''inconsistent''. If a change to a database's relvars would leave the database in an inconsistent state, that change is illegal and must not succeed.<ref name="professionals"/>{{rp|91}}
A ''[[relvar]]'' is a named variable of some specific relation type, to which at all times some relation of that type is assigned, though the relation may contain zero tuples.
 
In general, constraints are expressed using relational comparison operators, of which just one, "is subset of" (⊆), is theoretically sufficient.{{Citation needed|reason=This should be explained, because it is interesting enough to read more about it|date=August 2010}}
The basic principle of the relational model is the [[Information Principle]]: all [[information]] is represented by data values in relations. In accordance with this Principle, a [[relational database]] is a set of relvars and the result of every query is presented as a relation.
 
Two special cases of constraints are expressed as ''keys'' and ''foreign keys'':
The consistency of a relational database is enforced, not by rules built into the applications that use it, but rather by ''[[constraint (database)|constraint]]s'', declared as part of the logical schema and enforced by the [[DBMS]] for all applications. In general, constraints are expressed using relational comparison operators, of which just one, "is subset of" (⊆), is theoretically sufficient{{Citation needed|reason=This should be explained, because it is interesting enough to read more about it|date=August 2010}}. In practice, several useful shorthands are expected to be available, of which the most important are [[candidate key]] (really, [[superkey]]) and [[foreign key]] constraints.
 
==== InterpretationKeys ====
To fully appreciate the relational model of data it is essential to understand the intended ''interpretation'' of a [[relation (database)|relation]].
 
A ''candidate key'', or simply a ''key'', is the smallest [[subset]] of attributes guaranteed to uniquely differentiate each tuple in a relation. Since each tuple in a relation must be unique, every relation necessarily has a key, which may be its complete set of attributes. A relation may have multiple keys, as there may be multiple ways to uniquely differentiate each tuple.<ref name="professionals"/>{{rp|31–33}}
The body of a relation is sometimes called its extension. This is because it is to be interpreted as a representation of the [[extension (predicate logic)|extension]] of some [[Predicate (logic)|predicate]], this being the set of true [[proposition]]s that can be formed by replacing each [[free variable]] in that predicate by a name (a term that designates something).
 
An attribute may be unique across tuples without being a key. For example, a relation describing a company's employees may have two attributes: ID and Name. Even if no employees currently share a name, if it is possible to eventually hire a new employee with the same name as a current employee, the attribute subset {Name} is not a key. Conversely, if the subset {ID} is a key, this means not only that no employees ''currently'' share an ID, but that no employees ''will ever'' share an ID.<ref name="professionals"/>{{rp|31–33}}
There is a [[bijection|one-to-one correspondence]] between the free variables of the predicate and the attribute names of the relation heading. Each tuple of the relation body provides attribute values to instantiate the predicate by substituting each of its free variables. The result is a proposition that is deemed, on account of the appearance of the tuple in the relation body, to be true. Contrariwise, every tuple whose heading conforms to that of the relation, but which does not appear in the body is deemed to be false. This assumption is known as the [[closed world assumption]]: it is often violated in practical databases, where the absence of a tuple might mean that the truth of the corresponding proposition is unknown. For example, the absence of the tuple ('John', 'Spanish') from a table of language skills cannot necessarily be taken as evidence that John does not speak Spanish.
 
==== Foreign keys ====
For a formal exposition of these ideas, see the section [[Relational model#Set-theoretic formulation|Set-theoretic Formulation]], below.
{{main|Foreign key}}
 
A ''foreign key'' is a subset of attributes ''A'' in a relation ''R<sub>1</sub>'' that corresponds with a key of another relation ''R<sub>2</sub>'', with the property that the [[Projection (relational algebra)|projection]] of ''R<sub>1</sub>'' on ''A'' is a subset of the projection of ''R<sub>2</sub>'' on ''A''. In other words, if a tuple in ''R<sub>1</sub>'' contains values for a foreign key, there must be a corresponding tuple in ''R<sub>2</sub>'' containing the same values for the corresponding key.<ref name="professionals"/>{{rp|34}}
=== Application to databases ===
A '''[[data ___domain|data type]]''' as used in a typical relational database might be the set of integers, the set of character strings, the set of dates, or the two boolean values ''true'' and ''false'', and so on. The corresponding '''type names''' for these types might be the strings "int", "char", "date", "boolean", etc. It is important to understand, though, that relational theory does not dictate what types are to be supported; indeed, nowadays provisions are expected to be available for ''user-defined'' types in addition to the ''built-in'' ones provided by the system.
 
=== Relational operations ===
'''[[Column (database)|Attribute]]''' is the term used in the theory for what is commonly referred to as a '''column'''. Similarly, '''table''' is commonly used in place of the theoretical term '''relation''' (though in SQL the term is by no means synonymous with relation). A table data structure is specified as a list of column definitions, each of which specifies a unique column name and the type of the values that are permitted for that column. An '''attribute ''value''''' is the entry in a specific column and row, such as "John Doe" or "35".
Users (or programs) request data from a relational database by sending it a [[database query|query]]. In response to a query, the database returns a result set.
 
Often, data from multiple tables are combined into one, by doing a [[Join (SQL)|join]]. Conceptually, this is done by taking all possible combinations of rows (the [[Cartesian product]]), and then filtering out everything except the answer.
A '''[[tuple]]''' is basically the same thing as a '''[[row (database)|row]]''', except in an SQL DBMS, where the column values in a row are ordered. (Tuples are not ordered; instead, each attribute value is identified solely by the '''attribute name''' and never by its ordinal position within the tuple.) An attribute name might be "name" or "age".
 
There are a number of relational operations in addition to join. These include project (the process of eliminating some of the columns), restrict (the process of eliminating some of the rows), union (a way of combining two tables with similar structures), difference (that lists the rows in one table that are not found in the other), intersect (that lists the rows found in both tables), and product (mentioned above, which combines each row of one table with each row of the other). Depending on which other sources you consult, there are a number of other operators&nbsp;– many of which can be defined in terms of those listed above. These include semi-join, outer operators such as outer join and outer union, and various forms of division. Then there are operators to rename columns, and summarizing or aggregating operators, and if you permit [[relation (database)|relation]] values as attributes (relation-valued attribute), then operators such as group and ungroup.
A '''[[relation (database)|relation]]''' is a '''[[table (database)|table]]''' structure definition (a set of column definitions) along with the data appearing in that structure. The structure definition is the '''heading''' and the data appearing in it is the '''body''', a set of rows. A database '''[[relvar]]''' (relation variable) is commonly known as a '''base table'''. The heading of its assigned value at any time is as specified in the table declaration and its body is that most recently assigned to it by invoking some '''update operator''' (typically, INSERT, UPDATE, or DELETE). The heading and body of the table resulting from evaluation of some query are determined by the definitions of the operators used in the expression of that query. (Note that in SQL the heading is not always a set of column definitions as described above, because it is possible for a column to have no name and also for two or more columns to have the same name. Also, the body is not always a set of rows because in SQL it is possible for the same row to appear more than once in the same body.)
 
The flexibility of relational databases allows programmers to write queries that were not anticipated by the database designers. As a result, relational databases can be used by multiple applications in ways the original designers did not foresee, which is especially important for databases that might be used for a long time (perhaps several decades). This has made the idea and implementation of relational databases very popular with businesses.
=== SQL and the relational model ===
{{unreferenced section|date=February 2013}}
SQL, initially pushed as the [[standardization|standard]] language for [[relational database]]s, deviates from the relational model in several places. The current [[International Organization for Standardization|ISO]] SQL standard doesn't mention the relational model or use relational terms or concepts. However, it is possible to create a database conforming to the relational model using SQL if one does not use certain SQL features.
 
=== Database normalization ===
The following deviations from the relational model have been noted{{who|date=September 2011}} in SQL. Note that few database servers implement the entire SQL standard and in particular do not allow some of these deviations. Whereas NULL is ubiquitous, for example, allowing duplicate column names within a table or anonymous columns is uncommon.
{{Main|Database normalization}}
[[Relation (database)|Relation]]s are classified based upon the types of anomalies to which they're vulnerable. A database that is in the [[first normal form]] is vulnerable to all types of anomalies, while a database that is in the ___domain/key normal form has no modification anomalies. Normal forms are hierarchical in nature. That is, the lowest level is the first normal form, and the database cannot meet the requirements for higher level normal forms without first having met all the requirements of the lesser normal forms.<ref name="Normalization">David M. Kroenke, ''Database Processing: Fundamentals, Design, and Implementation'' (1997), Prentice-Hall, Inc., pages 130–144</ref>
 
== Logical interpretation ==
;Duplicate rows
:The same row can appear more than once in an SQL table. The same tuple cannot appear more than once in a [[relation (database)|relation]].
;Anonymous columns
:A column in an SQL table can be unnamed and thus unable to be referenced in expressions. The relational model requires every attribute to be named and referenceable.
;Duplicate column names
:Two or more columns of the same SQL table can have the same name and therefore cannot be referenced, on account of the obvious ambiguity. The relational model requires every attribute to be referenceable.
;Column order significance
:The order of columns in an SQL table is defined and significant, one consequence being that SQL's implementations of Cartesian product and union are both noncommutative. The relational model requires there to be no significance to any ordering of the attributes of a relation.
;Views without CHECK OPTION
:Updates to a view defined without CHECK OPTION can be accepted but the resulting update to the database does not necessarily have the expressed effect on its target. For example, an invocation of INSERT can be accepted but the inserted rows might not all appear in the view, or an invocation of UPDATE can result in rows disappearing from the view. The relational model requires updates to a view to have the same effect as if the view were a base relvar.
;Columnless tables unrecognized
:SQL requires every table to have at least one column, but there are two relations of degree zero (of [[Cardinality (SQL statements)|cardinality]] one and zero) and they are needed to represent extensions of predicates that contain no free variables.
;NULL
:This special mark can appear instead of a value wherever a value can appear in SQL, in particular in place of a column value in some row. The deviation from the relational model arises from the fact that the implementation of this ''ad hoc'' concept in SQL involves the use of [[three-valued logic]], under which the comparison of NULL with itself does not yield ''true'' but instead yields the third [[truth value]], ''unknown''; similarly the comparison NULL with something other than itself does not yield ''false'' but instead yields ''unknown''. It is because of this behaviour in comparisons that NULL is described as a mark rather than a value. The relational model depends on the [[law of excluded middle]] under which anything that is not true is false and anything that is not false is true; it also requires every tuple in a relation body to have a value for every attribute of that relation. This particular deviation is disputed by some if only because E.{{nbsp}}F. Codd himself eventually advocated the use of special marks and a 4-valued logic, but this was based on his observation that there are two distinct reasons why one might want to use a special mark in place of a value, which led opponents of the use of such logics to discover more distinct reasons and at least as many as 19 have been noted, which would require a 21-valued logic. {{Citation needed|date=July 2009}} SQL itself uses NULL for several purposes other than to represent "value unknown". For example, the sum of the empty set is NULL, meaning zero, the average of the empty set is NULL, meaning undefined, and NULL appearing in the result of a LEFT JOIN can mean "no value because there is no matching row in the right-hand operand".
 
The relational model is a [[formal system]]. A relation's attributes define a set of [[logic]]al [[propositions]]. Each proposition can be expressed as a tuple. The body of a relation is a subset of these tuples, representing which propositions are true. Constraints represent additional propositions which must also be true. [[Relational algebra]] is a set of logical rules that can [[Validity (logic)|validly]] [[inference|infer]] conclusions from these propositions.<ref name="professionals"/>{{rp|95–101}}
=== Relational operations ===
Users (or programs) request data from a relational database by sending it a [[database query|query]] that is written in a special language, usually a dialect of SQL. Although SQL was originally intended for end-users, it is much more common for SQL queries to be embedded into software that provides an easier user interface. Many Web sites, such as Wikipedia, perform SQL queries when generating pages.
 
The definition of a ''tuple'' allows for a unique empty tuple with no values, corresponding to the [[empty set]] of attributes. If a relation has a degree of 0 (i.e. its heading contains no attributes), it may have either a cardinality of 0 (a body containing no tuples) or a cardinality of 1 (a body containing the single empty tuple). These relations represent [[Boolean ___domain|Boolean]] [[truth values]]. The relation with degree 0 and cardinality 0 is ''False'', while the relation with degree 0 and cardinality 1 is ''True''.<ref name="professionals"/>{{rp|221–223}}
In response to a query, the database returns a result set, which is just a list of rows containing the answers. The simplest query is just to return all the rows from a table, but more often, the rows are filtered in some way to return just the answer wanted.
 
=== Example ===
Often, data from multiple tables are combined into one, by doing a [[Join (SQL)|join]]. Conceptually, this is done by taking all possible combinations of rows (the [[Cartesian product]]), and then filtering out everything except the answer. In practice, relational database management systems rewrite ("[[Query optimizer|optimize]]") queries to perform faster, using a variety of techniques.
 
If a relation of Employees contains the attributes ''{Name, ID}'', then the tuple ''{Alice, 1}'' represents the proposition: "There exists an employee named ''Alice'' with ID ''1''". This proposition may be true or false. If this tuple exists in the relation's body, the proposition is true (there is such an employee). If this tuple is not in the relation's body, the proposition is false (there is no such employee).<ref name="professionals"/>{{rp|96–97}}
There are a number of relational operations in addition to join. These include project (the process of eliminating some of the columns), restrict (the process of eliminating some of the rows), union (a way of combining two tables with similar structures), difference (that lists the rows in one table that are not found in the other), intersect (that lists the rows found in both tables), and product (mentioned above, which combines each row of one table with each row of the other). Depending on which other sources you consult, there are a number of other operators&nbsp;– many of which can be defined in terms of those listed above. These include semi-join, outer operators such as outer join and outer union, and various forms of division. Then there are operators to rename columns, and summarizing or aggregating operators, and if you permit [[relation (database)|relation]] values as attributes (RVA&nbsp;– [[relation-valued attribute]]), then operators such as group and ungroup. The SELECT statement in SQL serves to handle all of these except for the group and ungroup operators.
 
Furthermore, if ''{ID}'' is a key, then a relation containing the tuples ''{Alice, 1}'' and ''{Bob, 1}'' would represent the following [[contradiction]]:
The flexibility of relational databases allows programmers to write queries that were not anticipated by the database designers. As a result, relational databases can be used by multiple applications in ways the original designers did not foresee, which is especially important for databases that might be used for a long time (perhaps several decades). This has made the idea and implementation of relational databases very popular with businesses.
# There exists an employee with the name ''Alice'' and the ID ''1''.
# There exists an employee with the name ''Bob'' and the ID ''1''.
# There do not exist multiple employees with the same ID.
 
Under the [[principle of explosion]], this contradiction would allow the system to prove that any arbitrary proposition is true. The database must enforce the key constraint to prevent this.<ref name="professionals"/>{{rp|104}}
=== Database normalization ===
{{Main|Database normalization}}
[[Relation (database)|Relation]]s are classified based upon the types of anomalies to which they're vulnerable. A database that's in the first normal form is vulnerable to all types of anomalies, while a database that's in the ___domain/key normal form has no modification anomalies. Normal forms are hierarchical in nature. That is, the lowest level is the first normal form, and the database cannot meet the requirements for higher level normal forms without first having met all the requirements of the lesser normal forms.<ref name="Normalization">David M. Kroenke, ''Database Processing: Fundamentals, Design, and Implementation'' (1997), Prentice-Hall, Inc., pages 130–144</ref>
 
== Examples ==
 
=== Database ===
An idealized, very simple example of a description of some [[relvar]]s ([[relation (database) |relation]] variables) and their attributes:
* Customer ('''<u>Customer ID</u>''', Tax ID, Name, Address, City, State, Zip, Phone, Email,Sex)
* Order ('''<u>Order NoID</u>''', <u>Customer ID</u>, <u>Invoice NoID</u>, Date Placed, Date Promised, Terms, Status)
* Order LineInvoice ('''<u>OrderInvoice NoID</u>''', '''<u>Order LineCustomer NoID</u>''', <u>ProductOrder CodeID</u>, QtyStatus)
* Invoice ('''<u>Invoice No</u>''', <u>Customer ID</u>, <u>Order No</u>, Date, Status)
* Invoice Line ('''<u>Invoice No</u>''', '''<u>Invoice Line No</u>''', <u>Product Code</u>, Qty Shipped)
* Product ('''<u>Product Code</u>''', Product Description)
 
In this [[design]] we have sixthree relvars: Customer, Order, Order Line,and Invoice, Invoice Line and Product. The bold, underlined attributes are ''[[candidate key]]s''. The non-bold, underlined attributes are ''[[foreign key]]s''.
 
Usually one [[candidate key]] is chosen to be called the [[primary key]] and used in [[preference]] over the other candidate keys, which are then called [[alternate key]]s.
 
A ''candidate key'' is a unique [[identifier]] enforcing that no [[tuple]] will be duplicated; this would make the [[Relation (database)|relation]] into something else, namely a [[bag (mathematics) |bag]], by violating the basic definition of a [[set (mathematics)|set]].{{Citation needed |date=October 2015}} Both foreign keys and superkeys (that includes candidate keys) can be composite, that is, can be composed of several attributes. Below is a tabular depiction of a relation of our example Customer relvar; a relation can be thought of as a value that can be attributed to a relvar.
 
=== Customer relation ===
{| class="wikitable"
|-
! Customer ID !! Tax ID !! Name !! Address !! [More fields&hellip;]
|-
| 123 || Alice
| 1234567890 || 555-5512222 || Munmun || 323 Broadway || &hellip;
|-
| 456 || Bob
| 2223344556 || 555-5523232 || Wile E. || 1200 Main Street || &hellip;
|-
| 789 || Carol
| 3334445563 || 555-5533323 || Ekta || 871 1st Street || &hellip;
|-
| 4232342432 || 555-5325523 || E. F. Codd || 123 It Way || &hellip;
|}
 
If we attempted to ''insert'' a new customer with the ID ''1234567890123'', this would violate the design of the relvar since '''<u>Customer ID</u>''' is a ''primary key'' and we already have a customer ''1234567890123''. The [[DBMS]] must reject a [[database transaction|transaction]] such as this that would render the [[database]] inconsistent by a violation of an [[Database integrity |integrity constraint]]. However, it is possible to insert another customer named ''Alice'', as long as this new customer has a unique ID, since the Name field is not part of the primary key.
 
''[[Foreign key]]s'' are [[integrity constraint]]s enforcing that the [[Value (computer science) |value]] of the [[attribute set]] is drawn from a ''[[candidate key]]'' in another [[relation (database) |relation]]. For example, in the Order relation the attribute '''<u>Customer ID</u>''' is a foreign key. A ''[[Join (SQL)|join]]'' is the [[Operation (mathematics)|operation]] that draws on [[information]] from several relations at once. By joining relvars from the example above we could ''query'' the database for all of the Customers, Orders, and Invoices. If we only wanted the tuples for a specific customer, we would specify this using a [[restriction condition]]. If we wanted to retrieve all of the Orders for Customer ''123'', we could [[Information retrieval|query]] the database to return every row in the Order table with '''<u>Customer ID</u>''' ''123'' .
 
There is a flaw in our [[database design]] above. The Invoice relvar contains an Order ID attribute. So, each tuple in the Invoice relvar will have one Order ID, which implies that there is precisely one Order for each Invoice. But in reality an invoice can be created against many orders, or indeed for no particular order. Additionally the Order relvar contains an Invoice ID attribute, implying that each Order has a corresponding Invoice. But again this is not always true in the real world. An order is sometimes paid through several invoices, and sometimes paid without an invoice. In other words, there can be many Invoices per Order and many Orders per Invoice. This is a '''[[many-to-many (data model)|many-to-many]]''' relationship between Order and Invoice (also called a ''non-specific relationship''). To represent this relationship in the database a new relvar should be introduced whose [[role]] is to specify the correspondence between Orders and Invoices:
If we wanted to retrieve all of the Orders for Customer ''1234567890'', we could [[Information retrieval|query]] the database to return every row in the Order table with '''<u>Customer ID</u>''' ''1234567890'' and join the Order table to the Order Line table based on '''<u>Order No</u>'''.
 
OrderInvoice ('''<u>Order ID</u>''', '''<u>Invoice ID</u>''')
There is a flaw in our [[database design]] above. The Invoice relvar contains an Order No attribute. So, each tuple in the Invoice relvar will have one Order No, which implies that there is precisely one Order for each Invoice. But in reality an invoice can be created against many orders, or indeed for no particular order. Additionally the Order relvar contains an Invoice No attribute, implying that each Order has a corresponding Invoice. But again this is not always true in the real world. An order is sometimes paid through several invoices, and sometimes paid without an invoice. In other words there can be many Invoices per Order and many Orders per Invoice. This is a '''[[many-to-many (data model) |many-to-many]]''' relationship between Order and Invoice (also called a ''non-specific relationship''). To represent this relationship in the database a new relvar should be introduced whose [[role]] is to specify the correspondence between Orders and Invoices:
 
Now, the Order relvar has a ''[[One-to-many (data model)|one-to-many relationship]]'' to the OrderInvoice table, as does the Invoice relvar. If we want to retrieve every Invoice for a particular Order, we can query for all orders where '''<u>Order ID</u>''' in the Order relation equals the '''<u>Order ID</u>''' in OrderInvoice, and where '''<u>Invoice ID</u>''' in OrderInvoice equals the '''<u>Invoice ID</u>''' in Invoice.
OrderInvoice ('''<u>Order No</u>''', '''<u>Invoice No</u>''')
 
== Application to relational databases ==
A '''[[data ___domain|data type]]''' in a relational database might be the set of integers, the set of character strings, the set of dates, etc. The relational model does not dictate what types are to be supported.
 
'''Attributes''' are commonly represented as '''[[Column (database)|columns]]''', '''tuples''' as '''[[row (database)|rows]]''', and '''relations''' as '''tables'''. A table is specified as a list of column definitions, each of which specifies a unique column name and the type of the values that are permitted for that column. An '''attribute ''value''''' is the entry in a specific column and row.
 
A database '''[[relvar]]''' (relation variable) is commonly known as a '''base table'''. The heading of its assigned value at any time is as specified in the table declaration and its body is that most recently assigned to it by an '''update operator''' (typically, INSERT, UPDATE, or DELETE). The heading and body of the table resulting from evaluating a query are determined by the definitions of the operators used in that query.
 
=== SQL and the relational model ===
SQL, initially pushed as the [[standardization|standard]] language for [[relational database]]s, deviates from the relational model in several places. The current [[International Organization for Standardization|ISO]] SQL standard doesn't mention the relational model or use relational terms or concepts.{{citation needed|date=December 2023}}
 
According to the relational model, a Relation's attributes and tuples are [[Set (mathematics)|mathematical sets]], meaning they are unordered and unique. In a SQL table, neither rows nor columns are proper sets. A table may contain both duplicate rows and duplicate columns, and a table's columns are explicitly ordered. SQL uses a [[Null (SQL)|Null]] value to indicate missing data, which has no analog in the relational model. Because a row can represent unknown information, SQL does not adhere to the relational model's ''Information Principle''.<ref name="professionals">{{cite book |last1=Date |first1=Chris J. |title=Relational Theory for Computer Professionals: What Relational Databases are Really All About |date=2013 |publisher=O'Reilly Media |___location=Sebastopol, Calif |isbn=978-1-449-36943-9 |edition=1.}}</ref>{{rp|153–155,162}}
Now, the Order relvar has a ''[[one-to-many relationship]]'' to the OrderInvoice table, as does the Invoice relvar. If we want to retrieve every Invoice for a particular Order, we can query for all orders where '''<u>Order No</u>''' in the Order relation equals the '''<u>Order No</u>''' in OrderInvoice, and where '''<u>Invoice No</u>''' in OrderInvoice equals the '''<u>Invoice No</u>''' in Invoice.
 
== Set-theoretic formulation ==
{{unreferenced section|date=December 2023}}
Basic notions in the relational model are ''[[relation (database)|relation]] names'' and ''attribute names''. We will represent these as strings such as "Person" and "name" and we will usually use the variables <math>r, s, t, \ldots</math> and <math>a, b, c</math> to range over them. Another basic notion is the set of ''atomic values'' that contains values such as numbers and strings.
 
Line 157 ⟶ 138:
: A relation is a tuple <math>(H, B)</math> with <math>H</math>, the header, and <math>B</math>, the body, a set of tuples that all have the ___domain <math>H</math>.
 
Such a relation closely corresponds to what is usually called the extension of a predicate in [[first-order logic]] except that here we identify the places in the predicate with attribute names. Usually in the relational model a [[logical schema|database schema]] is said to consist of a set of relation names, the headers that are associated with these names and the [[constraint (database) |constraints]] that should hold for every instance of the database schema.
 
; Relation universe
Line 168 ⟶ 149:
 
; [[Superkey]]
A superkey is a set of column headers for which the values of those columns concatenated are unique across all rows. Formally:
: A superkey is written as a finite set of attribute names.
: A superkey <math>K</math> holds in a relation <math>(H, B)</math> if:
Line 175 ⟶ 157:
: '''Theorem:''' A superkey <math>K</math> holds in a relation universe <math>U</math> over <math>H</math> if and only if <math>K \subseteq H</math> and <math>K \rightarrow H</math> holds in <math>U</math>.
; [[Candidate key]]
A candidate key is a superkey that cannot be further subdivided to form another superkey.
: A superkey <math>K</math> holds as a candidate key for a relation universe <math>U</math> if it holds as a superkey for <math>U</math> and there is no [[proper subset]] of <math>K</math> that also holds as a superkey for <math>U</math>.
; [[Functional dependency]]
Functional dependency is the property that a value in a tuple may be derived from another value in that tuple.
: A functional dependency (FD for short) is written as <math>X \rightarrow Y</math> for <math>X, Y</math> finite sets of attribute names.
: A functional dependency <math>X \rightarrow Y</math> holds in a relation <math>(H, B)</math> if:
Line 204 ⟶ 188:
 
=== Algorithm to derive candidate keys from functional dependencies ===
'''algorithm''' derive candidate keys from functional dependencies '''is'''
'''INPUT:''' a set ''S'' of FDs that contain only subsets of a header ''H''
'''OUTPUTinput:''' thea set ''CS'' of superkeysFDs that holdcontain asonly candidatesubsets keysof ina header ''H''
'''output:''' the set ''C'' of superkeys that hold as candidate keys in
all relation universes over ''H'' in which all FDs in ''S'' hold
all relation universes over ''H'' in which all FDs in ''S'' hold
'''begin'''
''C'' := ∅; // found candidate keys
''C'' := ∅ // found candidate keys
''Q'' := { ''H'' }; // superkeys that contain candidate keys
'''while''' ''Q'' <> ∅ '''do'''
let ''K'' be some element from ''Q'';
''Q'' := ''Q''&nbsp;– { ''K'' };
''minimal'' := '''true''';
'''for each''' ''X->Y'' '''in''' ''S'' '''do'''
''K' '':= (''K''&nbsp;– ''Y'') ∪ ''X''; // derive new superkey
'''if''' ''K' ''⊂ ''K'' '''then'''
''minimal'' := '''false''';
''Q'' := ''Q'' ∪ { ''K' ''};
'''end if'''
'''end for'''
'''if''' ''minimal'' '''and''' there is not a subset of ''K'' in ''C'' '''then'''
remove all supersets of ''K'' from ''C'';
''C'' := ''C'' ∪ { ''K'' };
'''end if'''
'''end while'''
 
'''end'''
== Alternatives ==
Other [[Database model|models]] include the [[Hierarchical database model|hierarchical model]] and [[network model]]. Some [[system]]s using these older architectures are still in use today in [[data center]]s with high data volume needs, or where existing systems are so complex and abstract that it would be cost-prohibitive to migrate to systems employing the relational model. Also of note are newer [[object database|object-oriented databases]].<ref>Atkinson, M., Dewitt, D., Maier, D., Bancilhon, F., Dittrich, K. and Zdonik, S., 1990. The object-oriented database system manifesto. In Deductive and object-oriented databases (pp. 223-240). North-Holland.</ref> and [[Datalog]].<ref>Maier, D., Tekle, K.T., Kifer, M. and Warren, D.S., 2018. Datalog: concepts, history, and outlook. In Declarative Logic Programming: Theory, Systems, and Applications (pp. 3-100).</ref>
 
''Datalog'' is a database definition language, which combines a relational view of data, as in the relational model, with a logical view, as in [[logic programming]]. Whereas relational databases use a relational calculus or relational algebra, with [[Relational database#Relational operations|relational operations]], such as ''union'', ''intersection'', ''set difference'' and ''cartesian product'' to specify queries, Datalog uses logical connectives, such as ''if'', ''or'', ''and'' and ''not'' to define relations as part of the database itself.
 
In contrast with the relational model, which cannot express recursive queries without introducing a least-fixed-point operator,<ref>Aho, A.V. and Ullman, J.D., 1979, January. Universality of data retrieval languages. In Proceedings of the 6th ACM SIGACT-SIGPLAN symposium on Principles of programming languages (pp. 110-119).</ref> recursive relations can be defined in Datalog, without introducing any new logical connectives or operators.
 
== See also ==
{{div col-begin|colwidth=28em}}
{{col-break}}
* [[Domain relational calculus]]
* [[Life cycle of a relational database]]
* [[List of relational database management systems]]
* [[Query language]]
** [[Database query language]]
** [[Information retrieval query language]]
{{col-break}}
* [[Relation (mathematics)|Relation]]
* [[Relational database]]
* [[Relational database management system]]
* [[The Third Manifesto]] ([[The Third Manifesto|TTM]])
* [[Tuple-versioning]]
{{div col- end}}
 
== Notes ==
{{reflist|group=nb}}
 
== References ==
Line 249 ⟶ 239:
 
== Further reading ==
* {{cite book|lastlast1=Date|firstfirst1=C.Christopher J.|author2-link=Hugh Darwen|title=Foundation for future database systems: the third manifesto; a detailed study of the impact of type theory on the relational model of data, including a comprehensive model of type inheritance|year= 2000|publisher= Addison-Wesley |___location= Reading, [[Massachusetts | MA]] |isbn=978-0-201-70928-75|edition= 2 | last2= Darwen | first2 = Hugh|author1-link=Christopher J Date}}
* {{cite book|last=Date|first=C. J.|title= An Introduction to Database Systems|year= 2007 | author-mask = 3 | publisher= Pearson Education|___location=Boston |isbn=978-0-321-19784-49|edition= 8|url-access=registration|url=https://archive.org/details/introductiontoda0000date}}
 
== External links ==
{{Commons category|Relational models}}
* {{Citation | publisher = Handle | url = http://hdl.handle.net/2027.42/4164 | title = Feasibility of a set-theoretic data structure: a general structure based on a reconstituted definition of relation | last = Childs | year = 1968 | type = research| hdl = 2027.42/4164 }} cited in Codd's 1970 paper.
* {{Citation | last = Darwen | first = Hugh | url = http://www.thethirdmanifesto.com/ | title = The Third Manifesto (TTM)}}.
* {{dmoz|Computers/Software/Databases/Relational|Relational Databases}}
* {{Citation | contribution-url = http://c2.com/cgi/wiki?RelationalModel | contribution = Relational Model | title = C2}}.
* {{Citation | url = http://blogs.sun.com/bblfish/entry/why_binary_relations_beat_tuples | title = Binary relations and tuples compared with respect to the semantic web | publisher = Sun | type = [[World Wide Web]] log}}.
 
{{Database models}}
{{Databases }}
 
{{DEFAULTSORT:Relational Model}}
[[Category:Relational model| ]]
[[Category:1969 in computer sciencecomputing]]
[[Category:Articles with example pseudocode]]
[[Category:Programming paradigms]]
[[Category:Database management systems]]