Lesson Description
Build confidence in SQL Fundamentals by practicing this lesson with structured prompts and real query execution.
Lesson 4 of 5
Progress: 0/4 exercises solved (0%)
Solve all exercises below to unlock the next lesson.
Lesson Description
Build confidence in SQL Fundamentals by practicing this lesson with structured prompts and real query execution.
Easy Project
Mini project: Turn this lesson into a real-world query artifact by writing one clean business report query and validating output quality.
DISTINCT removes duplicate rows from the result. It considers the combination of all selected columns.
SELECT DISTINCT column1, column2
FROM table_name;
-- How many different departments do employees belong to?
SELECT DISTINCT department_id
FROM employees
ORDER BY department_id;
When you list multiple columns, DISTINCT de-duplicates on the combination:
-- Unique (department, job) pairs
SELECT DISTINCT department_id, job_id
FROM employees
ORDER BY department_id, job_id;
SELECT COUNT(DISTINCT department_id) AS unique_departments
FROM employees;
Counts only the distinct non-NULL values in the column.
For large tables, GROUP BY is often faster and more explicit:
SELECT department_id, COUNT(*) AS headcount
FROM employees
GROUP BY department_id;
DISTINCT applies to the entire row, not just the first column.ORDER BY can only reference columns that appear in the SELECT when DISTINCT is used.DISTINCT ON (col) (PostgreSQL-only) keeps one row per distinct value of a specific column.This lesson is part of SQL Fundamentals. Focus on the core idea in DISTINCT — unique values, then validate with deliberate practice.
What to master
Common mistakes
High-level strategy
Task ladder
Transparent data checks
Retention loop
Logical reasoning for commands
WHERE
Why: Limits rows to only the business-relevant subset.
Memory cue: Filter early to reduce noise.
ORDER BY
Why: Makes output deterministic and reviewable.
Memory cue: No ORDER BY means no guaranteed row order.
AS alias
Why: Makes output columns readable for teams and reports.
Memory cue: If the name is clear, the query is easier to trust.
Concept check
3 quick questions. One at a time. Instant score at the end.
Return the distinct department_id values from the employees table, ordered ascending.
From the store sandbox, return the distinct category_id values from the products table, ordered ascending.
From the hospital sandbox, return a single value specialty_count — the number of distinct specialties across all doctors.
Return distinct (department_id, job_id) pairs from the employees table, ordered by department_id, then job_id.
Lesson 4 of 5
0/4 solved (0%)
Finish this lesson to unlock next.