Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 14/ 160
01. SQL Foundations & Relational Concepts

Basic Retrieval (SELECT, Column Aliases AS, DISTINCT)

Project columns, alias results, and remove duplicates with DISTINCT thoughtfully.

BeginnerSELECT · AS Aliases3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

SELECT says which columns you want, FROM says which table, AS renames a column, and DISTINCT removes repeated rows.

Think of it like…

Asking a librarian for specific information: "just the titles and authors of the books in this section" (SELECT columns), with your own labels on the list (AS), and each title listed once even if the library has several copies (DISTINCT).

Where you’ve seen it

A quick look at where customers are: SELECT DISTINCT city, state FROM customers ORDER BY state, city; lists each city-and-state combination once, while SELECT name, email AS contact FROM customers LIMIT 20 previews rows with a friendlier column name.

Words you’ll hear

Projection
Choosing which columns or expressions to return.
Alias (AS)
A name for a column or expression in the result.
DISTINCT
Removes duplicate rows, comparing all selected columns together.
SELECT *
All columns; fine for exploring, risky in application code.

Visual diagram

Loading interactive diagram

Theory & example queries

Choosing and naming columns

List the columns you need, separated by commas. You can also select expressions: price * qty, UPPER(name), created_at::date. Give expressions an alias with AS so the result has a meaningful column name; use double quotes for names with spaces or capitals (AS "Total Revenue"), though plain snake_case names are easier to work with.

SELECT * is convenient for exploring, but in application code it transfers columns you don't use, can stop the database using covering indexes, and changes shape whenever someone adds a column. Name the columns instead.

Expressions with aliasesQuery example
1Input dataStart from the source rows or state that the statement sees.
order_items
2 rows
order_items sample rows
idpriceqtycreated_at
101772026-11-20 09:15:00
1022532026-11-20 14:30:00
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  id,3  price * qty AS line_total,4  created_at::date AS order_date5FROM6  order_items7LIMIT8  10;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output2 sample rows
Expected output
idline_totalorder_date
101492026-11-20
102752026-11-20

Note: Sample rows assume the first item was 7 × 7 and the second was 25 × 3. LIMIT only caps how many rows are shown.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Name the columns you need and alias your expressions.

DISTINCT and its pitfalls

DISTINCT keeps one copy of each unique combination of the selected columns. SELECT DISTINCT city, state deduplicates pairs, not cities: Pune in two different states would appear twice. To count unique values, use COUNT(DISTINCT col) rather than SELECT DISTINCT followed by a count.

Removing duplicates costs a sort or hash over the whole result. If duplicates appear only because a join multiplied rows, DISTINCT hides the real problem (and can give wrong totals later); fix the join or use EXISTS instead. PostgreSQL's DISTINCT ON (col) keeps the first row per value according to ORDER BY, which is handy for "latest row per customer".

Latest order per customer (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
orders
4 rows
orders sample rows
customer_ididcreated_at
79012026-11-18 10:00
79082026-11-20 14:32
89122026-11-19 08:00
89142026-11-21 09:08
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT DISTINCT2  ON (customer_id) customer_id,3  id,4  created_at5FROM6  orders7ORDER BY8  customer_id,9  created_at DESC;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output2 sample rows
Expected output
customer_ididcreated_at
79082026-11-20 14:32:00
89142026-11-21 09:08:00

Note: Each customer appears once, represented by the newest matching order.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: DISTINCT works on whole rows; don't use it to hide join duplicates.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1FROM

Pick the table

Start with the table that holds the rows you want.

SQL at this step
1FROM2  customers
What to watch at this step
One row
per customer
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

SELECT chooses which columns (or expressions) to return and FROM says which table they come from: SELECT name, city FROM customers. AS gives a column a readable name (price * qty AS line_total). DISTINCT removes duplicate rows from the result, comparing every selected column together.

Why it matters: Every query starts here, and small habits matter: SELECT * in application code fetches columns you don't need and breaks when the table changes, and DISTINCT is often a band-aid over a join that duplicates rows. Getting the basics right makes everything after easier.

When to reach for it

  • Every query you write
  • Listing unique values for filters and dropdowns
  • Naming computed columns in reports

When to avoid or be careful

  • SELECT * in production code
  • DISTINCT to cover up duplicate rows from a join
  • Expecting rows in a particular order without ORDER BY

SELECT * vs named columns vs DISTINCT

SELECT *
Best for: Quick exploration in a SQL client

Strengths: Fast to type; shows everything.

Watch out: Extra data, brittle code, blocks index-only scans.

Named columns
Best for: Application queries and reports

Strengths: Clear, stable and efficient.

Watch out: Must be updated when you need a new column.

SELECT DISTINCT
Best for: Listing unique values or combinations

Strengths: Removes duplicate rows simply.

Watch out: Extra sort or hash; can mask join bugs.

Interview signals & numbers to know

When this topic comes up

  • “Show me just the names and emails”
  • “List the unique cities”
  • “Why are there duplicates?”
  • Column aliases
  • Fresher SQL rounds

Benchmarks & rules of thumb

* -
all columns
1 -
copy of each distinct row combination
0 -
row order guarantees without ORDER BY

Common mistakes & follow-ups

Common interview mistakes

  • Writing SELECT DISTINCT name, city and expecting unique names.
  • Adding DISTINCT after a join that duplicated rows, instead of fixing the join.
  • Using SELECT * in an API, then breaking clients when a column is added or renamed.

Likely interviewer follow-ups

  • What's the difference between DISTINCT and GROUP BY?
  • Why is SELECT * discouraged in production?
  • How would you get each customer's latest order in PostgreSQL?
Interview tip: Even for basic questions, mention one good habit (named columns over SELECT *, and DISTINCT applying to whole rows). It shows care beyond syntax.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Basic Retrieval (SELECT, Column Aliases AS, DISTINCT) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Deleting Data (DELETE vs TRUNCATE vs DROP)
Next topic
Filtering Rows (WHERE, Comparison Operators =, !=, <, >)