SQL DISTINCT

What is DISTINCT?

DISTINCT removes duplicate values from query results.

It ensures only unique values are returned.

Basic Syntax

SELECT DISTINCT column_name
FROM table_name;

Example

SELECT DISTINCT department
FROM employees;

Multiple Columns

SELECT DISTINCT department, role
FROM employees;

DISTINCT vs Default Behavior

SELECT department FROM employees;

SELECT DISTINCT department FROM employees;

Using with WHERE

SELECT DISTINCT department
FROM employees
WHERE salary > 50000;

Using with ORDER BY

SELECT DISTINCT department
FROM employees
ORDER BY department;

Full Example

SELECT DISTINCT department
FROM employees
WHERE salary > 40000
ORDER BY department;

Why DISTINCT is Important

  • Removes duplicate data
  • Cleans query results
  • Improves readability
  • Used in reporting

Common Mistakes

  • Thinking DISTINCT applies to only one column
  • Using DISTINCT when not needed
  • Confusing it with GROUP BY

Practice

Get unique values from a column in a table.

SELECT DISTINCT column_name
FROM table_name;

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic