🌱 BasicsbeginnerCommonly used

How to write a SELECT query in SQL

Retrieve data from one or more columns in a table.

Table schema used in examplesβ€” A users table with basic columns
CREATE TABLE users (
  id       INTEGER PRIMARY KEY,
  name     TEXT,
  email    TEXT,
  age      INTEGER,
  country  TEXT
);
Select all columnsAll databases
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 specific columnsAll databases
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 with a column aliasAll databases
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 with expressionAll databases
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 valuesAll databases
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)
← Back to SQL Reference