Concept · Basic queries

SELECT

SELECT states which columns or values you want a query to return.

SELECT example

Picking two columns
SELECT name, price
FROM products;

It returns one row per product and shows only name and price. It does not change the data.

What to look for: Picture a product with id = 7, name = «Notebook» and price = 4.50. The query will show «Notebook» and «4.50», but not the id. Changing the columns in the SELECT only changes the output.

Check the result with small data

Two products have an id, a name and a price. We ask for only two columns.

Self-contained query · SQLite
WITH products(id, name, price) AS (
  VALUES (7, 'Notebook', 4.50), (8, 'Pencil', 0.80)
)
SELECT name, price FROM products ORDER BY id;
Query result
nameprice
Notebook4.5
Pencil0.8

Two rows appear with name and price; the id exists in the data but is not included in the result. SELECT decides the columns, not the number of rows.

Check your understanding: Which column would appear if you added id to the SELECT?

Show answer

The id column, with 7 and 8. The number of rows would still be two.

How SELECT is used

Separate columns with commas. FROM names the table the rows come from. You can include a calculation and name it with AS.

To filter or sort the result, see WHERE and ORDER BY.

Common mix-ups with SELECT

Forgetting a comma

Ambiguous
SELECT name price
FROM products;

Some engines interpret price as an alias for name. To ask for two columns, write SELECT name, price.

Mistaking an alias for stored data

An alias only labels the result of that query. It does not create a new column or change the table.

Choosing columns also defines what the result promises

The projection decides what information the reader or an application receives. Asking for name and price does not save a new table or remove the id from the original data: it simply leaves it out of that output. A calculated expression, such as a price including tax, does not change the stored amount either, as long as the statement only reads.

For results consumed by code, use explicit columns and unique names. SELECT * may include tomorrow a column added to the schema, or two identical names after a join. Column order also matters in exports and in operations that compare sets. A query that still runs is not necessarily still delivering the shape its consumer expected.

Row order needs a separate rule. Without ORDER BY, do not rely on insertion order or on the id. If you apply a limit to pick the first results, also define how ties are broken. Finally, telling rows apart from values avoids another mix-up: showing only one column does not necessarily reduce the number of rows; removing repeats needs an explicit intent and can change what the report means.

Technical questions: PostgreSQL: SELECT, columns and aliases (opens in a new tab).