SQL: Structured Query LanguageSQL FundamentalsRelational Database Model

What is a relational database?

Question 4 of 4 · Updated

On this page

A relational database is a database that organizes information according to the relational model: data is represented logically as relations, commonly implemented as tables with rows and columns. Each table describes a particular kind of information, and values such as identifiers allow related records to be combined. Keys and constraints help keep the data consistent, while SQL provides a practical way to query and modify it.

For example, an e-commerce database can store customers in one table and orders in another. Rather than repeating the customer's name and contact details on every order, the order stores a customer identifier that refers to the customer's record.

1. What does relational actually mean?#

The relational model represents data using relations. A relation in the mathematical model is a set of tuples defined over named attributes and their domains. In a typical SQL database, a table is the practical representation of that idea.

Relational model termTypical SQL representationExample
RelationTablecustomers
TupleRow(1, 'Asha')
AttributeColumnname
DomainPermitted values for an attributeInteger identifiers or names
KeyColumn or combination of columns that identifies a rowcustomer_id

Strict mathematical relations are sets, so they have no duplicate tuples or inherent row ordering. SQL tables and query results can contain duplicates unless prevented by constraints or removed by an operation such as DISTINCT. SQL also supports NULL, which introduces behavior beyond the simplest mathematical relational model. The logical model does not prescribe the physical disk layout: a database engine can use pages, indexes, memory caches and other structures to implement it.

The term relational comes from the concept of a relation, not merely from the fact that two tables can be linked. A database with a single table can still follow the relational model.

2. A practical relational database design#

Imagine an online store. The database needs to represent customers and orders. Each customer can place zero, one or many orders, but in this design each order must belong to exactly one customer.

customers

customer_id (PK)name
1Asha
2Ravi
3Meera

orders

order_id (PK)customer_id (FK)amount_cents
10112500
10214000
10321800

Order 101 and order 102 refer to customer 1 (Asha). Order 103 refers to customer 2 (Ravi). Meera has no orders yet, which is valid.

The relationship is one-to-many: one customer can have many orders. The primary key (PK) identifies each row, while the foreign key (FK) in orders refers to the corresponding primary key in customers.

3. Implement the tables and relationship using SQL#

Run the following examples in a fresh disposable database. The SQL uses common syntax intended for PostgreSQL and tested in SQLite. For SQLite, enable foreign-key enforcement on the connection before creating the tables with PRAGMA foreign_keys = ON; (this command is SQLite-specific and is not needed in PostgreSQL).

SQL
CREATE TABLE customers ( customer_id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL ); CREATE TABLE orders ( order_id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers(customer_id), amount_cents INTEGER NOT NULL CHECK (amount_cents >= 0) ); INSERT INTO customers (customer_id, name) VALUES (1, 'Asha'), (2, 'Ravi'), (3, 'Meera'); INSERT INTO orders (order_id, customer_id, amount_cents) VALUES (101, 1, 2500), (102, 1, 4000), (103, 2, 1800);

Here, customer_id in customers uniquely identifies the customer. In orders, order_id identifies an individual order; customer_id can repeat because multiple orders can belong to the same customer. The foreign key requires each order's customer ID to refer to an existing customer, and NOT NULL prevents an order from having no customer ID. The CHECK constraint rejects negative order amounts. Amounts use integer cents for this small teaching example.

Note that SQLite does not enforce VARCHAR length in the same way as PostgreSQL; the test demonstrates the relationship, not identical type enforcement across engines.

Suppose the store wants to display each order together with the customer's name. The name is not stored in orders, so the query combines the two tables using their shared customer identifier.

SQL
SELECT o.order_id, c.name, o.amount_cents FROM orders AS o JOIN customers AS c ON o.customer_id = c.customer_id ORDER BY o.order_id;

Result:

order_idnameamount_cents
101Asha2500
102Asha4000
103Ravi1800

Logically, the join pairs each order with the customer whose ID matches its foreign-key value, selects the requested columns and sorts by order ID. The database optimizer determines how to execute that operation physically. Meera does not appear because this inner join returns matching pairs only.

To show every customer, including those who have not placed an order, use a left join:

SQL
SELECT c.customer_id, c.name, COUNT(o.order_id) AS order_count FROM customers AS c LEFT JOIN orders AS o ON c.customer_id = o.customer_id GROUP BY c.customer_id, c.name ORDER BY c.customer_id;
customer_idnameorder_count
1Asha2
2Ravi1
3Meera0

The left join preserves Meera's row even without matching orders. COUNT(o.order_id) counts only non-NULL order identifiers, so the count is zero for Meera. COUNT(*) would count the unmatched left-join result row and incorrectly report one order in this particular query.

5. How relational databases protect data integrity#

Relationships are useful for querying, but declared constraints also provide rules that the database engine enforces.

Try these statements separately in the disposable database; each should fail:

SQL
-- Missing customer: foreign-key violation INSERT INTO orders (order_id, customer_id, amount_cents) VALUES (104, 99, 1000); -- Repeated customer ID: primary-key violation INSERT INTO customers (customer_id, name) VALUES (1, 'Other'); -- Negative amount: CHECK violation INSERT INTO orders (order_id, customer_id, amount_cents) VALUES (104, 1, -1);

The first statement would create an order for a nonexistent customer. The second would violate row identity. The third would violate the permitted amount rule. An engine enforcing these constraints rejects the writes. Error messages and transaction failure behavior depend on the DBMS; in PostgreSQL, if an error occurs inside an explicit transaction, roll back or recover using an appropriate savepoint before continuing.

Example verification: Table creation, inserts, both query results and all three constraint rejections passed in an isolated SQLite 3.46.1 in-memory database with foreign keys enabled. PostgreSQL execution was not available. No examples were executed against the production database.

6. Common relationship patterns#

  • One-to-one: one record in A matches at most one record in B, such as an employee and an optional employee profile. A UNIQUE foreign key can enforce the at-most-one side.
  • One-to-many: one customer can place many orders, as above. A foreign key in the many-side table models the association.
  • Many-to-many: students can enroll in multiple courses, and each course can have multiple students. An intermediate enrollment table can contain student_id and course_id as foreign keys and use their combination as a primary key when duplicate enrollments are forbidden.

A foreign key does not automatically create a join result. The query specifies the join condition. Conversely, SQL can join columns without a declared foreign key, but that alone does not enforce referential integrity.

7. Why choose the relational model?#

Separating customers from orders avoids storing the customer's current name on every order. If Asha changes her name, it can be updated in one place rather than in every order row. This reduces update anomalies and illustrates the motivation for normalization: organize facts according to their dependencies, not simply split every large table into smaller tables.

Relational databases are especially useful when applications have well-defined entities, integrity requirements, transactions involving related records and queries across multiple data sets. Examples include order processing, payments, inventory and university enrollment.

The model also has trade-offs. Complex joins can be expensive on large or poorly indexed tables. Schema changes need careful migration planning, and a highly normalized design may be less convenient for some reporting workloads. Indexes, denormalization or pre-aggregation may help when chosen for measured workload needs, but they introduce storage, write or consistency costs. A relational database is not automatically faster or slower than a document database; the right choice depends on data relationships, access patterns and consistency requirements.

8. Common interview mistakes#

  • Assuming a table must have a foreign key to be relational. Foreign keys enforce declared associations; a relation can exist independently.
  • Treating customer names as join keys when names may be shared or changed. Use stable identifiers when the schema provides them.
  • Assuming rows are stored or returned in insertion order. Specify ORDER BY when presentation order matters.
  • Confusing a primary key with a foreign key. A primary key identifies rows in its own table; a foreign key references a qualifying key in a referenced table.
  • Assuming normalization always eliminates all repeated values. Repeated foreign keys, such as customer_id in orders, are expected.

9. Interview-ready answer#

A relational database is a database based on the relational model, where data is represented in tables consisting of rows and columns. Primary keys identify records, and foreign keys can enforce relationships between tables. SQL lets us retrieve related information through joins and maintain consistency using constraints and transactions. For example, an e-commerce application can store customers and orders separately and connect them through customer_id. This reduces unnecessary duplication and allows the database to enforce that every order belongs to an existing customer. PostgreSQL, MySQL and SQL Server are examples of relational database management systems.

Related questions

Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning