← All lessons
SQL from zero · Lesson 2 of 10

Choosing columns

* is handy for a first look, but usually you want only some of the columns. List them after SELECT, with a comma between each one:

SELECT name, price FROM products;
Returns
name        | price
------------+------
Duck feeder | 24
Bird bath   | 45.5
Rain boots  | 40
Raincoat    | 59
Pond net    | 12.5
Field guide | 18
Sketchbook  | 9.75
Binoculars  | 120
(8 rows)

The columns come back in the order you list them. Ask for price, name and you get the price first.

Spaces and line breaks don't matter to the database, so longer queries are written over several lines to make them easier to read. Each line starts with a keyword. These parts are called clauses: the SELECT clause says which columns, and the FROM clause says which table.

SELECT name, city
FROM customers;
Returns
name | city
-----+-------
Ana  | Austin
Ben  | Denver
Cleo | Austin
Dev  | Boston
Eve  | Denver
Finn | NULL
Gus  | Boston
Hana | Austin
(8 rows)

Finn's city shows as NULL. That's how a database shows a value nobody filled in. You'll meet it properly in lesson 6.

The names of tables and columns were chosen by whoever built the database, so you need to know them. In the practice, The tables lists every table and its columns. If you spell a name wrong, the database doesn't guess what you meant. It stops with an error such as no such column: prise. Errors are normal and useful: read the message, because it usually names the exact problem.

Two dashes start a comment. The database ignores everything after -- on that line, so you can leave notes for people who read the query later:

-- each customer and the day they joined
SELECT name, joined
FROM customers;
Returns
name | joined
-----+-----------
Ana  | 2024-01-15
Ben  | 2024-02-03
Cleo | 2024-03-22
Dev  | 2024-05-10
Eve  | 2024-06-01
Finn | 2024-07-19
Gus  | 2024-08-30
Hana | 2024-09-12
(8 rows)

Practice

Show just the name of every product.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

SELECT a, b FROM t;Only columns a and b, in that order.
clauseOne part of a query, starting with a keyword (SELECT, FROM).
-- noteA comment: ignored by the database.
no such columnThe error for a column name that doesn't exist (often a typo).

The other AI and data engineering courses