Skip to the workspace
Pebellslearn by building
Basic SQL Syntax  ›  Capstone Project

SELECT — Asking for Data

SELECT 15 minA SELECT query names the columns, the table, the rows to keep and their order, and the database runs FROM and WHERE before it builds the output columns.

sql / SELECT — Asking for Data

Explore each scene at your own pace.

01 · The rule

The rule

SELECT — Asking for Data

A SELECT query names the columns, the table, the rows to keep and their order, and the database runs FROM and WHERE before it builds the output columns.

Trace source rows through filtering, projection and explicit ordering.

Your manager asks: "Which customers do we have in Pune? Alphabetical, please." That sentence already contains a complete query. SELECT is the statement you will write more than any other, and it maps almost word for word onto how people ask questions.

The rule

Which columns, from which table, which rows, in what order.

Each part of that line is one clause:

SELECT name, email          -- which columns
FROM customers              -- from which table
WHERE city = 'Pune'         -- which rows
ORDER BY name;              -- in what order

Only SELECT and FROM are required. Some useful extras:

  • SELECT * returns every column. Handy for exploring; in application code, list the columns you need so the query does not change when the table does.
  • AS renames a column in the output: SELECT price * quantity AS total.
  • DISTINCT removes duplicate result rows: SELECT DISTINCT city FROM customers.
  • ORDER BY price DESC sorts largest first; ASC (the default) sorts smallest first.
  • To return only the first few rows, PostgreSQL, MySQL and SQLite use LIMIT 5; SQL Server uses SELECT TOP 5; the SQL standard spells it FETCH FIRST 5 ROWS ONLY.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.