Tables, Rows and a First Session in psql
Meet the relational model — tables, rows, columns and keys — and run your first queries against PostgreSQL 17 in psql.
Contentsand lesson path
On this page
- Why it matters
- Tables, rows and columns
- A first session in psql
- Your first queries
- Check your understanding
- Apply it
- Review prompt
Lessons of SQL Fundamentals
- Tables, Rows and a First Session in psql Concept · 20 min
- Filtering, Sorting and the NULL Trap Worked example · 25 min
- Joins and Subqueries Without Multiplying Rows Lab · 30 min
- Turning Rows into Business Metrics Lab · 25 min
- Tables, Views and Changing Data Safely Lab · 25 min
- Check: Answer Questions About an Unseen Schema Knowledge check · 10 questions
What you will learn
- Write SELECT queries that filter, sort and limit rows, handling NULL with three-valued logic correctly.
01. Why it matters
Every application you have built so far forgot everything when it stopped. The JSON endpoints from the HTTP API lessons read a request, answered, and kept nothing. Real services remember: accounts, orders, messages, reviews. That memory usually lives in a relational database, and you talk to it in SQL, a language that outlives most frameworks you will ever learn.
You have already worked with tabular data as files — CSV and Parquet in the data handling skill. A relational database keeps the same idea, one table of rows and columns, but adds three things files cannot give you:
- Types and rules live with the data. A column declared
numeric(10,2)rejects text; a rule declared once blocks bad rows from every program that touches the table. - Many readers and writers at once. Two requests can insert orders at the same moment without corrupting either.
- Ask, do not scan. You state the result you want; the database decides how to find it, often far faster than any loop you would write.
This skill uses PostgreSQL as the reference engine: it is free, standards-leaning, and the database you are most likely to meet behind an API. Nearly everything you learn here also works in MySQL, SQLite or SQL Server with small dialect differences. The examples follow one small online store — products, customers, orders — that grows across the lessons.
02. Tables, rows and columns
A table holds one kind of thing, named in the singular or plural by convention: products, customers, orders. Each row is one record — one product, one customer. Each column is one attribute of that thing, and every row has the same columns.
Three properties make a table more than a grid:
- Every column has a type.
integerfor whole numbers,textfor strings,datefor days,numeric(10,2)for exact amounts of money — up to ten digits with two after the decimal point. Do not store money in a binary floating-point type:realcannot represent 0.10 exactly, so sums of prices drift by fractions of a cent and invoices stop adding up. - Every cell holds one value. Not a list, not a nested record. An order that contains three products is not one row with three products squeezed into a cell; it is three rows in a separate
order_itemstable that point back at the order. You will build exactly that shape in the joins lesson. - Rows are identified by a key. A
PRIMARY KEYis a column (or columns) whose value is unique and never missing, soid 4points at exactly one row of the table. Other tables refer to it, which is what makes the model relational.
A column can also hold NULL — "no value here". A customer with no country yet is not in country "" or "unknown"; the value is absent, and SQL treats absent values differently from any real value. The next lesson gives NULL the attention it deserves.
03. A first session in psql
psql is the command-line client that ships with PostgreSQL, and every engineer who works with Postgres ends up in it. The quickest lab is a throwaway container — the containerization skill covers what is happening here; you only need the command. It publishes the container on port 55433 so it cannot collide with anything else on your machine:
docker run --name sql-lab \
-e POSTGRES_PASSWORD=learnsql \
-e POSTGRES_DB=store \
-p 55433:5432 \
-d postgres:17-alpinedocker exec -it sql-lab psql -U postgres -d storepsql (17.12)
Type "help" for help.
store=#You are now talking to the store database. Create the products table and put the store catalogue in it:
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
category text NOT NULL,
price numeric(10,2) NOT NULL
);
INSERT INTO products (id, name, category, price) VALUES
(1, 'USB-C cable', 'accessories', 9.90),
(2, 'Mechanical keyboard', 'peripherals', 89.00),
(3, 'Mouse pad', 'accessories', 12.50),
(4, '27-inch monitor', 'displays', 249.00),
(5, 'Webcam 1080p', 'peripherals', 45.00),
(6, 'Laptop stand', 'accessories', 29.00),
(7, 'HDMI cable 2m', 'accessories', 12.50),
(8, 'USB-C dock', 'peripherals', 129.00);CREATE TABLE
INSERT 0 8Before querying, learn the two meta-commands you will use daily. They start with a backslash and are handled by psql itself, not by SQL. \dt lists tables; \d <table> describes one table — its columns, types, which may be NULL, and its keys:
List of relations
Schema | Name | Type | Owner
--------+----------+-------+----------
public | products | table | postgres
(1 row) Table "public.products"
Column | Type | Collation | Nullable | Default
----------+---------------+-----------+----------+---------
id | integer | | not null |
name | text | | not null |
category | text | | not null |
price | numeric(10,2) | | not null |
Indexes:
"products_pkey" PRIMARY KEY, btree (id)Read that output like a contract: every column has a type, Nullable not null marks columns a row cannot omit, and the primary key is backed by an index, which is how a lookup by id stays fast as the table grows.
04. Your first queries
SQL is declarative: you describe the result you want, and the engine works out how to produce it. There is no loop to write, no variable to update. Start with everything:
SELECT * FROM products; id | name | category | price
----+---------------------+-------------+--------
1 | USB-C cable | accessories | 9.90
2 | Mechanical keyboard | peripherals | 89.00
3 | Mouse pad | accessories | 12.50
4 | 27-inch monitor | displays | 249.00
5 | Webcam 1080p | peripherals | 45.00
6 | Laptop stand | accessories | 29.00
7 | HDMI cable 2m | accessories | 12.50
8 | USB-C dock | peripherals | 129.00
(8 rows)A full query reads almost like English, with clauses arriving in a fixed order. This one narrows the rows, keeps two columns, and sorts:
SELECT name, price FROM products
WHERE category = 'accessories'
ORDER BY price, name; name | price
---------------+-------
USB-C cable | 9.90
HDMI cable 2m | 12.50
Mouse pad | 12.50
Laptop stand | 29.00
(4 rows)Mouse pad and HDMI cable 2m both cost 12.50, so price alone cannot decide which comes first. The second sort column, name, breaks the tie: rows that tie on every listed column are returned in any order unless you add a tie-breaker.
The engine evaluates the clauses in a logical order that differs from how you write them: FROM picks the table, WHERE filters rows, SELECT keeps the columns you asked for, ORDER BY sorts last. Keeping that order in mind will make later lessons easier, because it explains why, for instance, you cannot use a column alias inside WHERE.
Two habits are worth forming on day one. First, prefer naming columns over SELECT * in real code — an explicit list keeps results stable when the table changes. Second, treat row order as a promise only when ORDER BY makes it one: without it, PostgreSQL may return rows in any order, and usually will the moment the table grows. Aggregates preview the reporting side of SQL:
SELECT count(*) FROM products; count
-------
8
(1 row)05. Check your understanding
06. Apply it
Start the practice project for this skill: your own sample store in PostgreSQL.
- Run the container and connect with psql as shown above, then create
productsand load the eight rows. - Write three queries by hand and predict each result before running it: all products in
displays; every product with price over 100 ordered cheapest first; only thenameandpricecolumns of peripherals. - Describe each table you create with
\dand read the contract out loud: types, not-null columns, keys.
Keep this database — the next lessons build the rest of the store on top of it.
07. Review prompt
Without looking back:
- Explain table, row, column and key in your own words, and why an order with three products becomes rows in a second table rather than three values in one cell.
- Why is money stored as
numeric(10,2)and not asreal? - In which logical order does the engine evaluate
FROM,WHERE,SELECTandORDER BY? - What do
\dtand\d productseach show, and what does a primary key promise?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.