Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 3

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

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. integer for whole numbers, text for strings, date for 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: real cannot 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_items table that point back at the order. You will build exactly that shape in the joins lesson.
  • Rows are identified by a key. A PRIMARY KEY is a column (or columns) whose value is unique and never missing, so id 4 points 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:

Terminal
docker run --name sql-lab \
  -e POSTGRES_PASSWORD=learnsql \
  -e POSTGRES_DB=store \
  -p 55433:5432 \
  -d postgres:17-alpine
Terminal
docker exec -it sql-lab psql -U postgres -d store
Expected output (the version line shows the 17.x release your image contains)
psql (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:

SQL · store=#
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);
Expected output
CREATE TABLE
INSERT 0 8

Before 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:

psql · \dt
          List of relations
 Schema |   Name   | Type  |  Owner   
--------+----------+-------+----------
 public | products | table | postgres
(1 row)
psql · \d products
                  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:

SQL · store=#
SELECT * FROM products;
Expected output
 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:

SQL · store=#
SELECT name, price FROM products
WHERE category = 'accessories'
ORDER BY price, name;
Expected output
     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:

SQL · store=#
SELECT count(*) FROM products;
Expected output
 count 
-------
     8
(1 row)

05. Check your understanding

Practice check · 3 questions

Tables and psql

Three quick checks on the model and the tool.

Q1. Inside psql, you want to see every table in the database you are connected to. Which command does that?
Q2. A query with no ORDER BY clause returns rows in a different order on two runs. What is going on?
Q3. What does declaring id integer PRIMARY KEY guarantee about the products table?
Practice only: not graded, not saved, not evidence.

06. Apply it

Start the practice project for this skill: your own sample store in PostgreSQL.

  1. Run the container and connect with psql as shown above, then create products and load the eight rows.
  2. 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 the name and price columns of peripherals.
  3. Describe each table you create with \d and 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:

  1. 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.
  2. Why is money stored as numeric(10,2) and not as real?
  3. In which logical order does the engine evaluate FROM, WHERE, SELECT and ORDER BY?
  4. What do \dt and \d products each show, and what does a primary key promise?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check