CrackKit
0% complete
SQL & PostgreSQL Mastery

SELECT, FROM & clause order

SELECT is the statement you'll write more than any other. This lesson covers its skeleton — choosing columns, naming the table, and the clause order that trips everyone up at first.

The simplest query

sql
SELECT name, city        -- which columns you want
FROM customers;          -- which table they come from
  • `SELECT` lists the columns to return, comma-separated.
  • `FROM` names the table.
  • The semicolon ; ends the statement.

SQL keywords are case-insensitive (select = SELECT), but the convention is UPPERCASE keywords, lowercase identifiers — it makes queries scannable.

Every column, and computed columns

sql
SELECT * FROM customers;              -- * = all columns (handy for exploring)

SELECT name, price, price * 0.9 AS sale_price   -- compute a new column
FROM products;

* is great for quick exploration but avoid it in real application code — it fetches columns you don't need and breaks when the schema changes. Name the columns you actually use.

Aliases with AS

AS renames a column (or table) in the output — essential for computed columns and readability:

sql
SELECT
    name        AS product_name,
    price / 100 AS price_in_rupees
FROM products;

The AS keyword is optional (price/100 price_in_rupees works) but include it — it's clearer. Alias names with spaces or capitals need double quotes: AS "Sale Price".

The clause order you must memorize

SQL clauses must appear in a fixed order. Here's the full skeleton (you'll learn each clause across the course):

SELECT columns FROM table WHERE row filter GROUP BY grouping HAVING group filter ORDER BY sorting LIMIT row cap

Write them out of order and you get a syntax error. But there's a twist worth knowing now...

Written order ≠ execution order

The database executes clauses in a different order than you write them: FROM first (get the table), then WHERE (filter rows), then GROUP BY, then SELECT, and ORDER BY/LIMIT last.

This explains a classic beginner error: you can't use a SELECT alias in WHERE, because WHERE runs before SELECT computes it. WHERE sale_price > 100 fails; WHERE price * 0.9 > 100 works. Keep this execution order in mind and half of SQL's "gotchas" evaporate.