Database
A database is an organized collection of data, usually stored on a computer and controlled by software called a database management system (DBMS).[1] The DBMS lets people and programs store, find, change, and protect data without knowing how the data is laid out on disk. Most databases in use today hold data in tables of rows and columns, and most use the language SQL to read and write it.[1]
The study of databases is a part of computer science. It covers how to describe data, answer questions about it quickly, keep it correct when many users change it at once, and spread it across many machines.[2]
Why databases exist
Databases solve problems that appear when each program keeps its own files. Early database applications were built directly on file systems, and this caused several problems:[2]
- Duplicate and conflicting data. The same facts are copied into different files and formats, and the copies stop matching.
- Hard-to-reach data. Each new question needs a new program.
- Hidden rules. Rules such as "an account balance must stay above zero" are buried in program code, so they are hard to add or change.
- Half-done updates. A crash in the middle of a money transfer can leave one account changed and the other not.
- Clashing users. Two people withdrawing money from the same account at the same time can leave the wrong balance.
- Weak security. It is hard to let a user see some of the data but not all of it.
A DBMS handles all of these problems in one place, so each program does not have to solve them again.[2] Banks, airlines, phone companies, universities, and online shops all keep their records in databases.[2]
Tables, rows, and keys
In a relational database, all data is stored in tables.[2] Each table is made of rows and columns:[3]
| Part | Also called | What it holds | Example |
|---|---|---|---|
| Row | Tuple | One thing being described | One instructor |
| Column | Attribute | One kind of fact about each thing | A name or a salary |
Each column has a domain, the set of values it may hold. A special value, null, marks a value that is unknown.[3]
Keys tie the data together:
- A primary key is a column, or set of columns, whose value picks out exactly one row. For example, an instructor ID identifies one instructor.[2]
- A foreign key is a column whose values must appear in another table. For example, the department name stored with each instructor must match a row in the department table.[3]
Asking questions with SQL
A database separates the design of the data from the data itself. The schema is the overall logical structure of the database, while an instance is the actual content at one point in time.[2] A schema works like a variable's type in a program, and an instance works like the variable's current value.
Defining data
A data definition language (DDL) states the schema. This SQL statement creates a table of instructors:[2]
create table instructor (
ID char(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
The DBMS stores such definitions in a data dictionary, which holds data about the data.[2] This includes the schema, integrity rules (rules that keep stored data valid, such as "a balance must stay above zero"), and who may access what.[2]
Querying data
A data manipulation language (DML) reads and updates data, and the part that reads data is called a query language.[2] SQL is declarative: the user states what data is wanted, not how to find it. Declarative languages are usually easier to learn and use than procedural ones, which make the user spell out the steps.[2]
This query finds all instructors in the computer science department:[2]
select name
from instructor
where dept_name = 'Comp. Sci.'
An SQL query takes one or more tables as input and always returns a single table.[2]
SQL is not as powerful as a general programming language, so applications are written in languages such as C, Java, or Python and send SQL queries to the database.[2] They do this in one of two ways:[2]
- Embedded SQL, meaning SQL statements written inside the program's own code.
- A programming interface, such as Open Database Connectivity (ODBC) or JDBC, which are standard interfaces that let a program pass SQL queries to a database.
Inside a database management system
A DBMS is split into parts, each with its own job. Its main functional parts are the storage manager, the query processor, and the transaction management part.[2]
- The query processor turns a query into low-level steps and runs them. It includes the DDL interpreter, the DML compiler, and the query evaluation engine.[2]
- The storage manager links the stored data to the programs and queries that use it. Its parts include the file manager, the buffer manager (which moves data between disk and memory), the authorization and integrity manager, and the transaction manager.[2]
- Transaction management keeps the database correct despite crashes and many users working at once.[2]
On disk, the storage manager keeps data files, the data dictionary, and indexes. An index points to the rows that hold a given value, so the system can find them without reading everything.[2]
Schemas and data independence
A database has two kinds of schema. The logical schema describes what data exists and how it relates, while the physical schema describes how it is stored.[2]
Physical data independence is the ability to change the physical schema without changing the logical schema.[2] Applications depend only on the logical schema, so the storage can be reorganized without rewriting them.[2]
Edgar F. Codd made this a main goal in 1970. He wrote that users "must be protected from having to know how the data is organized in the machine."[4]
Design and administration
Database design has two stages:[2]
- Logical design chooses the schema, meaning which tables to have and which attributes go in each.
- Physical design decides how the data is laid out in storage.
A database administrator (DBA) has central control over the system. A DBA's duties include:[2]
- defining the schema and storage structures;
- granting access rights;
- backing up the database;
- keeping enough free disk space;
- watching for jobs that slow the system down.
Transactions
A transaction is a group of operations that together do one logical job.[2] Jim Gray defined it as a unit of work, such as moving money between bank accounts, that must leave the database consistent whether it succeeds or not: either the money moves, or it stays where it was.[5]
A transaction commits when it finishes successfully and its changes are recorded as permanent.[6] The classic example moves 50 dollars from account A to account B. If the system fails after A is reduced but before B is increased, money is lost, so the system must make sure a partly done transaction leaves no trace.[7]
The ACID properties
Theo Härder and Andreas Reuter created the acronym ACID in their 1983 survey for four properties a transaction must have:[8]
- Atomicity. The transaction happens completely or not at all.[8]
- Consistency. A transaction run on its own keeps the database consistent, so each successful transaction commits only legal results.[7][8]
- Isolation. Transactions may run at the same time, but each one acts as if the others ran wholly before it or wholly after it.[7]
- Durability. Once a transaction completes, its changes survive later system failures.[7]
Concurrency control
Concurrency control is the set of methods a DBMS uses to provide isolation.[7] Running transactions at the same time makes better use of the processor and disk, and short transactions need not wait behind long ones.[7]
Two-phase locking is a common method. Each transaction locks the data it uses and works in two phases:[9]
- In the growing phase, it may take locks but not release any.
- In the shrinking phase, it may release locks but not take any.
This rule guarantees that the result matches some one-at-a-time order of the transactions, a property called conflict serializability.[9]
Two stricter forms hold some locks until the transaction ends, either by committing or by aborting (being canceled, with its changes undone). An exclusive lock is the kind a transaction takes in order to write data, and no other transaction can hold a lock on that data at the same time.[9]
| Form | Locks held until the transaction ends |
|---|---|
| Strict two-phase locking | All exclusive locks |
| Rigorous two-phase locking | All locks |
Many databases use rigorous two-phase locking.[9]
Multiversion schemes keep old versions of data. Each write creates a new version, so a read can return a suitable version at once and never has to wait.[9]
Under snapshot isolation, each transaction reads from a snapshot of the committed data taken when it started. Snapshot isolation does not always give serializable results. Serializable snapshot isolation adds checks that fix this.[9]
Recovery after a crash
A DBMS keeps a log on stable storage, meaning storage that keeps its contents through crashes.[6] Before a transaction changes a data item, the system writes a log record holding the item's old value and its new value.[6]
Data moves between memory and disk in blocks, units of data that the system reads or writes together. The write-ahead logging rule says that before a block in memory is written to the database on disk, all log records for that block must already be on stable storage.[6] After a crash, the system uses the log to undo transactions that had not committed and to redo those that had.[6]
The result is that committed work survives and unfinished work disappears as if it never started, the subject of database recovery.[8]
Finding data fast
Indexes
A database index lets the system find rows without scanning the whole table.[2] The most common kind is the B-tree, proposed by Rudolf Bayer and Edward McCreight while at Boeing Scientific Research Labs. By 1979 Douglas Comer wrote that it had become, in practice, the standard way to organize indexes in a database system.[10]
A B-tree is a search tree whose nodes each hold many keys. The root is the top node of the tree, and leaves are nodes with no children. The order is the smallest number of keys a node other than the root may hold, so each such node holds between and keys.[10]
Insertions and deletions always keep the tree balanced, so all leaves sit at the same depth.[10]
Balance limits the cost of a search. For a file of records, a search in a B-tree of order (with ) never visits more than
nodes, where each visit usually means one read from secondary storage, such as a disk that keeps data long-term.[10] Here , the Logarithm of to base , is the power to which must be raised to get .
The cost therefore grows only with the logarithm of the file size. A B-tree of order 50 that indexes one million records can be searched with at most 4 disk reads.[10]
Query processing and optimization
The DBMS answers a query in three steps:[2]
- Parsing and translation turn the SQL text into an expression in relational algebra.
- Optimization picks the cheapest plan among the many ways to compute that expression.
- Evaluation runs the chosen plan and returns the result.
Query optimization is what lets SQL stay declarative. The user states only what data is wanted, and the optimizer chooses how to get it.[2]
Pat Selinger led the team in IBM's System R project that built the first cost-based query optimizer.[11] Michael Stonebraker and Andrew Pavlo wrote in 2024 that the optimizer "remains the hardest part of building a DBMS."[12]
Data models
A data model is a set of tools for describing data, the relationships between data, what the data means, and the rules it must follow.[2] The data model decides what a database looks like to its users.
| Model | How data is organized | Example systems |
|---|---|---|
| Hierarchical | Records in trees; programs follow set paths | IBM IMS[13] |
| Network | Records joined by links; programs move along the links | IDS and CODASYL systems[14] |
| Relational | Tables; rows connected by matching values | Oracle, Db2, SQL Server[14] |
| Object-oriented | Objects, as in object-oriented programming[1] | |
| Key-value | Values stored and fetched by a key | Amazon Dynamo[15] |
| Document | Semi-structured documents, typically in JSON format | MongoDB, CouchDB[15] |
| Wide-column | Rows by key, each with any number of named attributes | Bigtable, Cassandra, HBase[15] |
| Graph | Entities and the relationships between them | Amazon Neptune[1][16] |
Object-oriented programming organizes code around objects, each of which combines data with the operations on that data.
Key-value stores offer three basic operations:[15]
- put stores a value under a key.
- get fetches the value stored under a key.
- delete removes a key and its value.
Many key-value stores give limited or no support for transactions, which makes them easier to scale across many machines.[15]
Vector databases are another specialized kind. They are single-purpose systems with indexes that speed up nearest-neighbor search.[12]
The relational model
Codd introduced the relational model in a paper in Communications of the ACM in June 1970.[11] The paper set out a model with three parts:[4]
- n-ary relations, meaning relations whose tuples each have attributes;
- a normal form for relations;
- a general language for working with data.
A normal form is a standard shape that relations should take; database normalization covers the idea. Codd argued that his model describes data in its natural structure only, without extra structure added for the machine's sake.[4]
In the model, a relation is a set of tuples, and each tuple has one value for each attribute. Because a relation is a set, it holds no duplicate rows.[3]
Relational algebra is a set of operations that take one or two relations and return a new relation. It has six basic operations:[3]
- Select, , keeps the tuples of relation that satisfy the condition .
- Project, , keeps only the attributes to of .
- Union combines the tuples of two relations.
- Set difference keeps the tuples of one relation that are not in another.
- Cartesian product, , pairs every tuple of with every tuple of .
- Rename gives a relation or its attributes a new name.
A join combines a Cartesian product with a selection:[3]
Here and are relations and is a condition on the attributes of both. Relational algebra is a pure language used to study what queries can express and to optimize them, while SQL is the language used in practice.[2]
Codd used operations on relations to address the problems of duplicate and inconsistent data.[4] Database normalization grew from this work into a design method for removing duplicate data.
The entity-relationship model
Peter Chen proposed the entity-relationship model in 1976.[17]
The model describes the world as entities and the relationships among them. Chen offered it as a common view from which network and relational views of data could be derived.[17]
Today it is used mainly for database design.[2]
Transactions versus analytics
Databases serve two broad kinds of work:
- Online transaction processing (OLTP) handles many short transactions that read and update a few rows, such as orders and payments.[9][16]
- Analytics reads large amounts of data to summarize trends.[18]
A data warehouse is a store of data gathered from many sources under one schema at a single site.[18]
A warehouse keeps history that the source systems often discard, and it moves heavy reporting work away from the transaction systems. New data is usually copied in from OLTP systems from time to time.[18]
Online analytical processing (OLAP) tools let users summarize and view this data in different ways with little delay.[18]
Row stores and column stores
The two kinds of work favor different layouts on disk, a choice called data orientation. A row store keeps all the values of a row together. A column store keeps each column in its own file or region.[19]
On a magnetic disk, each jump to a new location costs a seek, the time to move the disk head there. The table compares the two layouts on common tasks.[19]
| Task | Row store | Column store |
|---|---|---|
| Read one whole record | One seek | One seek per column |
| Scan a few columns of many rows | Must read every column | Reads only the needed columns |
| Compression | Mixed values in each block | Similar values together, so better compression |
| Loading and updating | Simple | Slower, since each column is written separately |
For these reasons, column stores are typically used for analytics, and data warehouses often use column storage.[19][18]
Distributed databases
A single machine has limits on storage, speed, and reliability, so large databases spread data across many machines, called nodes.[20] A distributed data store uses two main tools, partitioning and replication.
Partitioning and replication
Partitioning splits a table's rows among nodes so that each node holds a subset.[20] There are two common ways to decide which node gets a row:
- Hash partitioning applies a hash function, a function that maps a value to a node number, to a chosen attribute. It spreads rows evenly and is good for finding single values, but a range query (a search for all values that fall within a given range) must visit every node.
- Range partitioning gives each node a range of values. A range query may touch only one or a few nodes.
Replication keeps copies of each partition on at least 2 nodes, often 3, so that requests can go to a copy when a node fails.[20] Copies in other data centers can survive the loss of a whole site.[20]
Sharding is a form of partitioning in which the application itself routes each request to one of many separate databases.[20]
The CAP theorem
Replicated data raises a trade-off between correctness and staying online. At a 2000 symposium, Eric Brewer proposed that a web service cannot guarantee all three of these at once:[21]
- Consistency: every read sees the latest write.
- Availability: every request gets a response.
- Partition tolerance: the system keeps working when the network loses messages between nodes.
Seth Gilbert and Nancy Lynch proved this in 2002 for asynchronous networks, which have no clocks and no limit on how long a message may take.[21] They also showed that any two of the three can be achieved. This result is known as the CAP theorem, and systems that choose availability can still offer weaker forms of consistency, such as eventual consistency.[21]
NoSQL and NewSQL
NoSQL is a loose name for a group of databases that do not use the relational model.[22]
The term in its current sense came from a meetup in San Francisco on June 11, 2009, organized by Johan Oskarsson.[22]
No single trait defines the group, but common traits include:[22]
- not using SQL;
- running on large clusters of machines;
- having no fixed schema.
Most NoSQL systems relax some ACID properties in exchange for flexible data models and the ability to scale across many machines.[16] Stonebraker and Pavlo note that by the end of the 2010s almost every NoSQL system had added an SQL interface, and many had added ACID transactions.[12]
NewSQL systems appeared in the early 2010s. They aimed to match the scalability of NoSQL systems for OLTP work while keeping SQL, the relational model, and ACID transactions.[12]
History
Tape and disk
In the 1950s and early 1960s, data was stored on magnetic tape, which can only be read in order, and fed in on punched cards.[2] Hard disks later allowed direct access to any record.[2]
IDS and the network model
Charles Bachman's Integrated Data Store (IDS), working at General Electric by 1963, kept one set of shared files on disk. Programs for tasks such as billing read and updated these files by sending requests to IDS, and IDS gave programmers a set of commands for working with data.[14]
Bachman's design shaped the network data model standardized by the CODASYL Database Task Group. This work won him the 1973 Turing Award.[14]
IMS and the hierarchical model
IBM's Information Management System (IMS) began as a system to track the parts of the Apollo spacecraft. Its first version shipped in 1967, and it printed its first "READY" message at Rockwell's Space Division in California on August 14, 1968.[13]
IMS combined a hierarchical database with software for high-volume transactions. It was fast when the path to the data was known in advance, but changes to the data often forced queries to be rewritten.[13]
Relational research prototypes
Codd's 1970 paper started the relational era. IBM, which earned revenue from IMS, at first opposed his ideas.[23]
Two research prototypes showed the model could work:[11]
- IBM's System R.
- INGRES at the University of California, Berkeley, active from 1973 to 1979 under Michael Stonebraker and Eugene Wong.
SQL and the first products
The first relational products followed within a decade:
- 1974: within System R, Donald Chamberlin and Raymond Boyce published the SEQUEL language, whose name was later shortened to SQL.[11]
- 1979: Software Development Laboratories released Oracle, the first commercial version of SQL. The company renamed itself Oracle in 1983.[11]
- 1981: IBM announced SQL/DS.[23]
- 1983: IBM announced DB2.[23]
Standards and adoption
SQL became an American national standard in 1986 and an international standard early in 1987.[11] This standard is now ISO/IEC 9075, and its latest version, SQL:2023, was published in June 2023.[11]
Relational databases became the most widely used kind in the 1980s, and by the end of the 1990s they had replaced CODASYL systems.[1][14] Free systems such as MySQL, PostgreSQL, and SQLite later made relational databases available to everyone.[11]
Big data and after
Later decades widened what databases do:[2]
- 1980s: parallel and distributed database systems, and object-oriented databases.
- 1990s: large data warehouses, data mining (finding patterns in very large data sets), and web commerce.[18]
- 2000s: big data storage systems such as Google's Bigtable, and NoSQL systems.
- 2010s: SQL front ends for big data systems, massively parallel databases, and main-memory databases on multi-core machines.
Massively parallel databases use many processors at once. Main-memory databases keep data in memory rather than on disk. Multi-core machines have processors with several cores that work at the same time.
Old systems also last a long time. Stonebraker and Pavlo note that many IMS databases still run today, because moving them is costly and risky.[12]
The same authors argue that the relational model and SQL remain dominant and have absorbed the best ideas of their rivals.[12]
The research field
Database research has its own conferences and awards. The ACM group on data management took the name SIGMOD after its 1974 meeting, and its annual meetings are among the most respected in the field.[11] The International Conference on Very Large Data Bases (VLDB) began in 1975 and is held each year.[24]
The ACM lists five winners of the Turing Award, computing's highest honor, under the research subject of databases.[25] Ullman's 2020 award, shared with Alfred Aho, was given for algorithms and theory underlying programming language implementation, and for their textbooks.[26]
| Year | Winner | Main database work |
|---|---|---|
| 1973 | Charles Bachman | Integrated Data Store and the network model[14] |
| 1981 | Edgar F. Codd | The relational model[23] |
| 1998 | Jim Gray | Transactions, concurrency control, and crash recovery[5] |
| 2014 | Michael Stonebraker | INGRES and Postgres[27] |
| 2020 | Jeffrey Ullman | Theory of lossless joins and normal forms, and the textbook Principles of Database Systems (1980)[26] |
References
- What Is a Database?, Oracle, 2024.
- Database System Concepts, 7th ed., Chapter 1: Introduction (slides), Silberschatz, Korth and Sudarshan, 2020.
- Database System Concepts, 7th ed., Chapter 2: Introduction to the Relational Model (slides), Silberschatz, Korth and Sudarshan, 2020.
- A Relational Model of Data for Large Shared Data Banks, E. F. Codd, Communications of the ACM, 1970.
- Jim Gray, A.M. Turing Award Laureate, ACM, 2024.
- Database System Concepts, 7th ed., Chapter 19: Recovery System (slides), Silberschatz, Korth and Sudarshan, 2020.
- Database System Concepts, 7th ed., Chapter 17: Transactions (slides), Silberschatz, Korth and Sudarshan, 2020.
- Principles of Transaction-Oriented Database Recovery, Theo Härder and Andreas Reuter, ACM Computing Surveys, 1983.
- Database System Concepts, 7th ed., Chapter 18: Concurrency Control (slides), Silberschatz, Korth and Sudarshan, 2020.
- The Ubiquitous B-Tree, Douglas Comer, ACM Computing Surveys, 1979.
- 50 Years of Queries, Donald Chamberlin, Communications of the ACM, 2024.
- What Goes Around Comes Around... And Around..., Michael Stonebraker and Andrew Pavlo, SIGMOD Record, 2024.
- Information Management Systems, IBM, 2024.
- Charles W. Bachman, A.M. Turing Award Laureate, ACM, 2024.
- Database System Concepts, 7th ed., Chapter 10: Big Data (slides), Silberschatz, Korth and Sudarshan, 2020.
- What Is a NoSQL Database?, Amazon Web Services, 2024.
- The Entity-Relationship Model: Toward a Unified View of Data, Peter Chen, ACM Transactions on Database Systems, 1976.
- Database System Concepts, 7th ed., Chapter 11: Data Analytics (slides), Silberschatz, Korth and Sudarshan, 2020.
- The Design and Implementation of Modern Column-Oriented Database Systems, Daniel Abadi and coauthors, Foundations and Trends in Databases, 2013.
- Database System Concepts, 7th ed., Chapter 21: Parallel and Distributed Storage (slides), Silberschatz, Korth and Sudarshan, 2020.
- Brewer's Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services, Seth Gilbert and Nancy Lynch, ACM SIGACT News, 2002.
- NoSQL Definition, Martin Fowler, 2012.
- Edgar F. Codd, A.M. Turing Award Laureate, ACM, 2024.
- VLDB 2024, VLDB Endowment, 2024.
- A.M. Turing Award Winners by Research Subject: Databases, ACM, 2024.
- Jeffrey D Ullman, A.M. Turing Award Laureate, ACM, 2021.
- Michael Stonebraker, A.M. Turing Award Laureate, ACM, 2024.
