SELECT Statement Basics
Retrieving columns from a table — the query you'll write more than any other, plus aliases and DISTINCT.
2 min read
SELECT reads data out of a table. It's the query you'll write far more than any other, and every other SQL topic in this course builds on top of it.
SELECT name, email FROM users;This reads as "give me the name and email columns, from the users table, for every row." Column names are listed after SELECT, separated by commas; the table comes after FROM.
Selecting all columns
* is shorthand for every column in the table:
SELECT * FROM users;Handy for quickly inspecting a table while exploring, but it's generally worth avoiding in real application code: it pulls columns you may not need (wasting bandwidth and, at scale, query performance), and if someone adds a column to the table later, every place using SELECT * silently starts returning it too, whether or not that was intended.
Column aliases
AS renames a column in the result, without changing anything in the underlying table:
SELECT name AS full_name, email AS contact_email FROM users;This is useful for giving computed columns a readable name (you'll see this constantly once you get to aggregate functions and CASE expressions later in this course), and for giving results field names that match what your application code expects. AS is optional in most dialects — SELECT name full_name FROM users works the same way — but including it makes the intent clear to anyone reading the query.
DISTINCT: removing duplicate rows
DISTINCT collapses duplicate rows in the result down to one:
SELECT DISTINCT country FROM users;If ten users are all in "Canada", this returns "Canada" once, not ten times. DISTINCT applies to the whole row of selected columns, not each column independently — SELECT DISTINCT country, city FROM users returns each unique (country, city) pair, not distinct countries and distinct cities separately.
Query capitalization convention
SQL keywords (SELECT, FROM, WHERE) are case-insensitive, but the near-universal convention is to write them in uppercase and table/column names in lowercase, purely for readability — select name from users runs exactly the same as SELECT name FROM users, but the uppercase version is far easier to scan in a longer query.
Right now, every query here returns every row in the table. The next lesson covers WHERE, for narrowing that down to only the rows you actually want.