Skip to content
Codescope

SELECT, WHERE & ORDER BY

The logical order a query runs in, which is not the written order.

intro8 min5 steps

Before you start

**SQL** is the language for asking questions of a database. Every query you'll ever write starts with the same four words: SELECT (columns), FROM (table), WHERE (filter), ORDER BY (sort).

The tricky bit: SQL runs those clauses in a different order than you write them. You write SELECT first, but the database does WHERE first — because it needs to filter rows before it knows which values to select. That's why you can't refer to a column alias inside WHERE.

This lesson runs a query step by step in the order the database actually executes it, so the rules stop feeling arbitrary and start making sense.

SELECT * FROM employees

Rownamedeptsalaryint
1Anaeng75000
2Bensales55000
3Caleng90000
4Deeeng65000
5Elisales48000

5 rows × 3 columns

All rows, all columns. The starting point for any query.

Step 1 of 5. SELECT * returns everything. `SELECT * FROM employees` returns every row and every column. The `*` means "all columns" — it is a shorthand for listing them all. This is useful for exploration, but in production queries you should name the columns you need. `*` makes queries brittle when columns are added later.

01 / 05

Step 01 / 05

SELECT * returns everything

SELECT * FROM employees returns every row and every column. The * means "all columns" — it is a shorthand for listing them all.

This is useful for exploration, but in production queries you should name the columns you need. * makes queries brittle when columns are added later.

query.sqlSQL
-- The logical order a query executes in:-- 1. FROM   — pick the table-- 2. WHERE  — filter rows-- 3. SELECT — pick columns-- 4. ORDER BY — sort the result-- All rows, all columnsSELECT * FROM employees;-- Pick columnsSELECT name, salary FROM employees;-- Filter rowsSELECT name, salaryFROM employeesWHERE salary > 60000;-- SortSELECT name, salaryFROM employeesWHERE salary > 60000ORDER BY salary DESC;-- Combine: alias, comparison, LIMITSELECT name, salary, salary * 12 AS annualFROM employeesWHERE dept = 'eng'ORDER BY salary DESCLIMIT 3;