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 orderOnly 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.ASrenames a column in the output:SELECT price * quantity AS total.DISTINCTremoves duplicate result rows:SELECT DISTINCT city FROM customers.ORDER BY price DESCsorts largest first;ASC(the default) sorts smallest first.- To return only the first few rows, PostgreSQL, MySQL and SQLite use
LIMIT 5; SQL Server usesSELECT TOP 5; the SQL standard spells itFETCH FIRST 5 ROWS ONLY.