How to write a SELECT query in SQL
Retrieve data from one or more columns in a table.
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
email TEXT,
age INTEGER,
country TEXT
);SELECT * FROM users;Returns every column and every row from the users table. The * means "all columns".
When to use: Quick exploration. Avoid in production β always specify columns you need.
Avoid SELECT * in production queries. Fetching unused columns wastes bandwidth and breaks if columns are added/removed.
SELECT name, email, country
FROM users;Returns only the specified columns. More efficient and explicit than SELECT *.
When to use: Always prefer this in production code.
SELECT
name AS full_name,
email AS email_address,
age AS years_old
FROM users;Renames columns in the result set using AS. The original column names are unchanged.
When to use: When column names are unclear or you need friendlier names in the output.
SELECT
name,
age,
age * 12 AS age_in_months
FROM users;You can compute values in the SELECT list. Here we multiply age by 12.
SELECT DISTINCT country
FROM users;Returns each unique country only once, removing duplicates.
When to use: Finding all unique values in a column.
Common Mistakes
- βUsing SELECT * in production β always specify the columns you need
- βForgetting the FROM clause
- βConfusing single quotes (for strings) with double quotes (for identifiers)