SELECT — Asking for Data
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.
The shortcut
You write SELECT first, but the database runs the clauses in a different order: FROM → WHERE → SELECT → ORDER BY. It finds the table, filters rows, then computes the output columns, then sorts.
This one fact explains the most common beginner error. A column alias made in SELECT does not exist yet when WHERE runs, so WHERE total > 1000 fails. It does exist by the time ORDER BY runs, so ORDER BY total works.
Which columns?
She wants customers, so show
name(addemailif useful).
Drills
Our customers table has four rows: Asha (Pune), Ravi (Delhi), Meera (Pune), Kabir (Mumbai). Answer fast — trust the rule.
How many rows does SELECT DISTINCT city FROM customers; return?
Which query lists products from most to least expensive?
SELECT name, price * 1.18 AS total FROM products WHERE total > 1000; fails. Why?
What does SELECT name FROM customers WHERE city = 'Pune' ORDER BY name; return?
Remember
- Which columns, from which table, which rows, in what order.
- Written SELECT-first, run FROM → WHERE → SELECT → ORDER BY.
- Aliases work in ORDER BY but not in WHERE;
SELECT *is for exploring, not for app code.
