SELECT Statement
SELECT Statement
Section titled βSELECT StatementβWhat it means
Section titled βWhat it meansβSELECT retrieves data from one or more tables β the most fundamental SQL statement. You specify which columns to return (or * for all), which table(s) to read from, and optionally filter, sort, and limit the results with other clauses (WHERE, ORDER BY, TOP, etc.).
Examples
Section titled βExamplesβSELECT * FROM Customers; -- every column, every row
SELECT Name, Email FROM Customers; -- specific columns only
SELECT Name AS CustomerName, Email FROM Customers; -- column alias for output
SELECT DISTINCT Country FROM Customers; -- unique values only, duplicates removed
SELECT TOP 10 * FROM Customers ORDER BY CreatedAt DESC; -- first 10 rows, most recent first
SELECT Name, Price, Price * 1.08 AS PriceWithTax FROM Products; -- computed columnCommon mistake
Section titled βCommon mistakeβUsing SELECT * in production application code instead of naming the specific columns you need β it pulls unnecessary data over the network, breaks if the tableβs columns change order or new ones are added, and can silently return more data than the application expects.
-- Fragile: pulls every column, including ones the app doesn't use,-- and breaks assumptions if the schema changes laterSELECT * FROM Customers WHERE Id = 42;
-- Explicit, resilient to schema changes, and only transfers needed dataSELECT Id, Name, Email FROM Customers WHERE Id = 42;Quick practice
Section titled βQuick practiceβ-
What does
SELECT DISTINCT Country FROM Customers;return?Answer
Each unique value found in theCountrycolumn, with duplicates removed. -
Why is
SELECT *generally discouraged in application code, even though itβs convenient while exploring data?Answer
It transfers unnecessary data, is fragile to schema changes (column additions/reordering), and makes it unclear exactly which columns the calling code actually depends on. -
What does
SELECT TOP 10 * FROM Customers ORDER BY CreatedAt DESC;return?Answer
The 10 most recently created customers, since it sorts byCreatedAtdescending before limiting to the first 10 rows.