Before continuing: This entry is part of the constraints and keys guide. If you are new to the topic, start with CREATE TABLE.
Table example in SQL
SELECT id, name, price
FROM products
ORDER BY id
LIMIT 3;The display order is not part of the table. Here it is requested with ORDER BY id. Without that clause, the engine does not guarantee that rows always come back in the same sequence.
What changes from case to case
Structure and data are not the same thing
Schema
Defines column names, types, defaults, keys and constraints. It is changed with definition statements such as CREATE TABLE or ALTER TABLE.
Stored rows
They hold the values themselves. They change with INSERT, UPDATE and DELETE.
A table can exist without rows. Its structure is still defined even when a query SELECT * returns no results.
Why a table needs identity and rules
A primary key identifies each row uniquely. A foreign key links a row to another table. Constraints such as NOT NULL, UNIQUE or CHECK block states the model treats as invalid.
These rules are no substitute for a good understanding of the domain, but they let the database reject some errors before they spread.
How to really get to know a table
Do not work out the structure from a screenshot or a query showing a few columns. Review the schema with your engine's metadata tools. The exact commands vary: PostgreSQL offers catalogues and client commands; SQLite has pragmas; MySQL and SQL Server have their own catalogues.
To find out what it contains, use explicit queries. For example, this query confirms that products contains nine rows spread across five categories:
SELECT COUNT(*) AS rows,
COUNT(DISTINCT category) AS categories
FROM products;| rows | categories |
|---|---|
| 9 | 5 |