C.W.K.
Stream
Lesson 01 of 16 · published

SELECT: Asking the Database a Question

~12 min · queries, select

Level 0Schema Seedling
0 XP0/86 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

SELECT is the question

SELECT is the only SQL statement that asks rather than changes. It returns rows; it never modifies the database. "Show me all users," "what was last month's revenue," "which orders shipped today" — every read query starts with SELECT.

The shape of every SELECT

Memorise this clause order — it shows up in every query, in this order, until you retire:

SELECT <columns or expressions>
FROM   <table or join>
WHERE  <row filter>
GROUP  BY <grouping>
HAVING <group filter>
ORDER  BY <sort>
LIMIT  <cap> OFFSET <skip>

The execution order is a different list (FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT). We'll come back to that — it explains why HAVING can reference aggregates but WHERE cannot.

Specific columns beat SELECT *

In production code, list the columns you want. SELECT * ships extra bytes over the wire, breaks subtly when columns are added or reordered, and obscures the query's intent. Use SELECT * in the psql terminal for exploration; almost never in committed code.

Code

Basic shapes·sql
-- All columns, all rows (exploratory only)
SELECT * FROM users LIMIT 10;

-- Specific columns (production-ready)
SELECT id, name, email FROM users;

-- Computed columns + aliases
SELECT id,
       UPPER(name)                AS shouting_name,
       price * quantity           AS line_total,
       AGE(now(), created_at)     AS account_age
FROM   order_items;
DISTINCT and basic functions·sql
SELECT DISTINCT category FROM products ORDER BY category;

SELECT COUNT(*) AS total,
       COUNT(DISTINCT customer_id) AS unique_customers
FROM   orders;

External links

Exercise

In a sample database (use the pagila sample DB or any of your own), write five SELECTs of increasing complexity: (1) all rows, (2) specific columns, (3) computed column with alias, (4) DISTINCT on one column, (5) COUNT with a filter.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.