Relational Databases Explained: Tables, Rows, Columns, Primary Keys and Foreign Keys
What a relational database is and why almost every application uses one: tables, rows and columns, primary and foreign keys, the three kinds of relationship, NULL, and where the database server sits in a real system. With a runnable example of the database enforcing the rules.
kvi5hnuCode Sprout team member14 min readOn this page
Almost every application you'll work on stores its important data in a relational database. That includes online shops, banking systems, hospital records and the back end of most mobile apps. SQL is the language you use to talk to it. Before you write any SQL, it's worth understanding what the database actually holds and which rules it enforces for you. Everything else in this course builds on these ideas.
Throughout the course, the examples use a small fictional outdoor-gear shop called Trailhead. It has customers, products, orders, employees and stores. Each example creates just the few rows it needs.
Database, DBMS and server
Three words get mixed up all the time:
- A database is an organized collection of data: the customers, the orders, the products.
- A database management system (DBMS) is the software that stores that data on disk, answers queries, enforces rules, and lets many users work at once without corrupting anything. Oracle Database, Microsoft SQL Server, PostgreSQL, MySQL, IBM Db2 and SQLite are all DBMSs. A DBMS built on the relational model is an RDBMS.
- A database server is the machine (or container, or cloud service) that runs the DBMS.
Applications almost never read the database's files directly. They send SQL statements to the DBMS and get results back. This is the client/server model:
- The client is the program that needs the data: a desktop app, a web application, a reporting tool, or you typing into a SQL editor.
- The server runs the DBMS and does the actual work of finding, sorting and changing data. This is often called back-end processing.
- The two talk over a network. The client uses a data access API, a library such as JDBC for Java, ADO.NET for C#, or a driver for Python or Node.js. The API sends the SQL text and receives the rows.
In most modern systems, there's another layer in the middle. A browser or mobile app talks to an application server or web API, and only that server talks to the database. The end user never connects to the database at all. That's a good thing for security, as article 58 explains.

The relational model
In 1970, Edgar F. Codd, a researcher at IBM, proposed storing data as relations: sets of rows that all have the same columns. Before that, programs navigated data through pointers and fixed file layouts. Every program had to know exactly how the data was laid out. Codd's idea separated what data you want from how it's stored, and that separation is why SQL lets you describe a result instead of writing a loop to find it.
In everyday terms, a relation is a table:
| Formal term | Everyday term | Example |
|---|---|---|
| relation | table | customers |
| tuple | row (record) | the row for customer 2, Ben Okafor |
| attribute | column (field) | city |
| domain | data type plus allowed values | text, at most 60 characters |
A few properties of the model are worth knowing from the start, because they explain behaviour that surprises beginners:
- Rows have no built-in order. A table is a set, not a list. If you don't ask for an order with
ORDER BY, the database may return rows in any order, and that order can change between runs (article 9). - Every row in a table has the same columns. You can't give one customer an extra column. If some customers have two phone numbers and others have five, that's a sign you need another table.
- Each cell holds one value. A cell like
'Pune, Leeds, Oslo'that packs a list into one value breaks the model, and it makes queries painful. Normalization (article 51) is the process of fixing that. - Every row should be identifiable. That's what keys are for.
Primary keys
A primary key is a column, or a set of columns, whose value identifies exactly one row. For customers, that's customer_id. The DBMS enforces two rules on a primary key:
- Unique. No two rows can have the same key.
- Not NULL. Every row must have a key value.
A key made of one column is a simple key. A key made of several columns is a composite key. For example, a line on an order might be identified by (order_id, line_no). Neither column is unique on its own, but the pair is.
There are two styles of primary key, and you'll see both in real systems:
- A natural key uses data that already exists and is unique, such as an ISBN, a country code like
IN, or an email address. - A surrogate key is a meaningless number or identifier the database generates, such as
customer_id = 2.
Most designs use a surrogate key for each table, because natural values change (people change email addresses) or turn out not to be unique after all. They then add a separate unique constraint on the natural value to keep it from being duplicated. Article 54 covers how databases generate surrogate keys.
Foreign keys and relationships
Tables become useful when they refer to each other. An order belongs to a customer, so the orders table stores the customer's key in its own customer_id column. That column is a foreign key: a column whose values must match a key in another table, called the parent or referenced table.

The DBMS uses the foreign key to enforce referential integrity: an order can't point at a customer that doesn't exist. It enforces this in both directions:
- Inserting or updating the child row. You can't add an order for customer 9 if there's no customer 9.
- Deleting or changing the parent row. By default, you can't delete customer 1 while orders still refer to them. You can tell the database to do something else instead, such as delete the orders too (
ON DELETE CASCADE) or set their foreign key to NULL. Article 53 covers these options.
A foreign key column can be NULL unless you declare it NOT NULL. A NULL foreign key means "not linked to anything", for example an employee with no manager yet.
There are three kinds of relationship between tables:
| Relationship | Meaning | How it's stored | Example |
|---|---|---|---|
| one-to-many | one parent row, any number of child rows | a foreign key in the child table | one customer, many orders |
| one-to-one | at most one row on each side | a foreign key that's also unique | one employee, one locker |
| many-to-many | many on both sides | a third junction table with two foreign keys | orders and products, joined by order_items |
One-to-many is by far the most common. Many-to-many relationships can't be stored directly, because each cell holds one value, so you add a junction table. Each row of order_items links one order to one product, with the quantity and price for that line. Article 50 covers how to decide which relationships you need.
Columns: data type, NULL and default
When you define a column, you give it properties that the DBMS enforces:
- A data type, such as an integer, a fixed-point number like
DECIMAL(10,2)for money, text likeVARCHAR(60), or a date. The type decides what values are allowed and how they compare and sort. Article 35 covers types in detail. - NULL or NOT NULL. NULL is a special marker meaning "no value here": unknown, missing or not applicable. It isn't zero and it isn't an empty string. Chen Wei's city is NULL because we don't know it. NULL behaves in unusual ways in comparisons, and article 8 is devoted to it.
- A default value, used when an insert doesn't supply one, such as today's date for
order_date. - Optionally, an identity (auto-generated) setting for surrogate keys, and check constraints such as
price > 0.
Seeing the rules enforced
The example below creates the two tables from the diagram in PostgreSQL. It runs a query that joins them, then tries three statements that break the rules. Click Run to execute it on a real database. Article 3 explains how these runnable examples work.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(60) NOT NULL,
city VARCHAR(40)
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
order_date DATE NOT NULL,
total DECIMAL(10, 2) NOT NULL
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune'),
(2, 'Ben Okafor', 'Leeds'),
(3, 'Chen Wei', NULL);
INSERT INTO orders VALUES
(101, 1, '2026-03-02', 129.50),
(102, 1, '2026-03-09', 42.75),
(103, 2, '2026-03-10', 310.25);
-- Which customer placed each order?
SELECT c.name, o.order_id, o.total
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY o.order_id;
-- Three statements that break the rules
INSERT INTO orders VALUES (104, 9, '2026-03-11', 15.00); -- there is no customer 9
INSERT INTO customers VALUES (2, 'Dina Haddad', 'Oslo'); -- key 2 is already taken
DELETE FROM customers WHERE customer_id = 1; -- orders still refer to customer 1
name | order_id | total
------------+----------+--------
Asha Rao | 101 | 129.50
Asha Rao | 102 | 42.75
Ben Okafor | 103 | 310.25
(3 rows)
psql:/workspace/solution.sql:31: ERROR: insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL: Key (customer_id)=(9) is not present in table "customers".
psql:/workspace/solution.sql:32: ERROR: duplicate key value violates unique constraint "customers_pkey"
DETAIL: Key (customer_id)=(2) already exists.
psql:/workspace/solution.sql:33: ERROR: update or delete on table "customers" violates foreign key constraint "orders_customer_id_fkey" on table "orders"
DETAIL: Key (customer_id)=(1) is still referenced from table "orders".
The join used the foreign key to match each order with its customer. Chen Wei didn't appear, because no order refers to customer 3: an inner join only keeps rows that match (article 12). The three bad statements were all refused by the database itself, not by application code. That's the real value of declaring keys: every program that touches the data gets the same protection, including the ones written years from now.
Read the three error messages closely, because each one names the rule that was broken:
violates foreign key constraint "orders_customer_id_fkey": the new order pointed at customer 9, which doesn't exist. TheDETAILline shows the offending key.duplicate key value violates unique constraint "customers_pkey": a primary key is implemented as a unique constraint (plusNOT NULL), and key 2 was taken.update or delete on table "customers" violates foreign key constraint: deleting customer 1 would leave orders 101 and 102 pointing at nothing.
PostgreSQL invented the names orders_customer_id_fkey and customers_pkey because the CREATE TABLE statements didn't name the constraints. Article 52 shows how to give constraints your own names, which makes messages like these easier to act on. The psql:/workspace/solution.sql:31: prefix is the client reporting which line of the script failed. Because the runner carries on after an error, each bad statement was tried and reported separately.
Relational and NoSQL databases
You'll also hear about NoSQL databases, such as document stores like MongoDB, key-value stores like Redis, and wide-column stores like Cassandra. They give up some relational features, usually joins, a fixed schema or multi-row transactions, in exchange for easy horizontal scaling or a flexible data shape. Relational databases have absorbed many of these ideas: PostgreSQL, MySQL, Oracle and SQL Server all store and query JSON documents (article 43), and some scale out across many machines. For data with real relationships and strong correctness requirements, the relational model is still the default choice.
What's current
- Popular RDBMSs today are PostgreSQL (version 19, released in November 2026, is the newest), MySQL (8.4 and 9.7 are the long-term support lines, and new feature releases now use calendar version numbers such as 26.10), Microsoft SQL Server 2025, Oracle AI Database 26ai (the successor to 23ai), IBM Db2, and SQLite (3.53 is current).
- Cloud databases such as Amazon RDS and Aurora, Azure SQL, Google Cloud SQL and AlloyDB, and serverless PostgreSQL services run the same engines and speak the same SQL. The concepts in this course apply unchanged.
- The SQL standard's latest edition is SQL. It added a native JSON type and property-graph queries over relational tables (SQL/PGQ). Article 2 covers the standard and the dialects.
Common questions
Is a table the same thing as a spreadsheet? They look alike, but a table is stricter. Every column has one data type that the database enforces, rows have no fixed order, there are no formulas or merged cells, and the database checks keys and relationships. A spreadsheet will happily accept a date in a price column; a table won't.
Should every table have a primary key? Yes, in practice. Without one, you can't reliably update or delete a single row, duplicates creep in, and many tools (replication, ORMs, admin tools) either need one or work badly without it. Some databases let you create a table without a key, but that's almost never a good idea.
Can a primary key change? It can, but it shouldn't. Every foreign key that points at it would have to change too. That's one of the main reasons to use surrogate keys: a generated number has no business meaning, so there's never a reason to change it.
Can a table have more than one unique column?
Yes. A table has one primary key, but it can have any number of unique constraints. The candidates that could have been the primary key are called candidate keys, and the ones you didn't choose are alternate keys. For example, customers might use customer_id as the primary key and keep email unique as well.
Does a foreign key have to point at the primary key? It must point at a column, or set of columns, declared as the primary key or as unique in the parent table. Pointing at the primary key is by far the most common choice.
Why is NULL allowed in a foreign key?
Because "not linked yet" or "not applicable" is a real situation, such as the company's chief executive having no manager. If a link is required, declare the column NOT NULL, as orders.customer_id is in the example.
Is SQL a programming language? It's a declarative language. You describe the result you want, and the DBMS decides how to get it. It isn't a general-purpose language like Java or Python, but every major DBMS adds a procedural extension, such as PL/SQL in Oracle, T-SQL in SQL Server and PL/pgSQL in PostgreSQL, with variables, loops and error handling (Part 13).
Summary
- A DBMS stores the data, answers SQL queries and enforces rules. Applications send SQL to it through a data access API, usually from an application server.
- The relational model stores data in tables: unordered sets of rows that all share the same columns, with one value per cell.
- A primary key uniquely identifies each row and can't be NULL. A composite key uses several columns. Surrogate keys are generated values with no meaning.
- A foreign key refers to a key in a parent table. The database uses it to enforce referential integrity on inserts, updates and deletes.
- Relationships are one-to-many (a foreign key), one-to-one (a unique foreign key) or many-to-many (a junction table).
- Each column has a data type, may or may not allow NULL, and can have a default value.
Practice questions
A products table has columns product_id, sku and name. product_id is the primary key and every sku is unique. What are the candidate keys, and what's sku called?
Answer
Both product_id and sku are candidate keys, because each one uniquely identifies a row. product_id was chosen as the primary key, so sku is an alternate key. It should be declared UNIQUE (and probably NOT NULL) so the database enforces it.
Students can enrol in many courses, and each course has many students. How do you store that relationship, and what's the primary key of the extra table?
Answer
It's a many-to-many relationship, so you add a junction table, for example enrolments (student_id, course_id, enrolled_on). Both IDs are foreign keys: one to students and one to courses. The natural primary key is the composite (student_id, course_id), which also stops a student enrolling in the same course twice.
In the runnable example, what would happen if you deleted customer 3 instead of customer 1? Why?
Answer
The delete would succeed. No order refers to customer 3, so removing that row can't leave an order pointing at a missing customer. Referential integrity only blocks the delete when child rows still refer to the parent.
A designer puts a column phone_numbers in customers and stores values like '0712 555, 0781 222'. Which rule of the relational model does this break, and what's the usual fix?
Answer
It breaks the "one value per cell" rule. The cell holds a list. Searching for one number, counting numbers or updating one of them all become string manipulation. The fix is a separate table such as customer_phones (customer_id, phone, kind) with a foreign key to customers, so each number is its own row.
Previous: SQL Course Outline: From First Query to Advanced SQL
Next: The SQL Language: Statement Types, Standards and Dialects

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.