Home Tutorials SQL Tutorial DISTINCT
DISTINCT

DISTINCT


The DISTINCT Keyword

Definition: The DISTINCT keyword is used in conjunction with SELECT to eliminate duplicate rows from your results. It ensures that the output only contains unique values from the specified column(s).

Why: Beginner SQL tutorials introduce DISTINCT early because real-world data is often repetitive. For example, if you have 1,000 students but they all come from only 5 different cities, using DISTINCT allows you to see the list of those 5 cities without scrolling through 1,000 rows.


Syntax

The DISTINCT keyword is placed directly after SELECT and before the column names.

SELECT DISTINCT column_name
FROM table_name;

Example: Finding Unique Locations

If you want to know which cities are represented in your students table without seeing the same city name multiple times, you would run:

SELECT DISTINCT city
FROM students;

Key Notes

  • Null Values: In the eyes of the DISTINCT keyword, NULL is considered a unique value. If you have multiple empty rows in a column, DISTINCT will return exactly one NULL in your list.
  • Multiple Columns: If you use DISTINCT with more than one column (e.g., SELECT DISTINCT city, age), the database looks for unique combinations. It will show the same city multiple times if the ages associated with that city are different.
  • Placement: DISTINCT must always come at the beginning of the column list. You cannot place it in the middle of a SELECT statement.

Quick Comparison

Query Expected Result
SELECT city FROM students; Bengaluru, Mysuru, Bengaluru, Hassan, Mysuru (Full list)
SELECT DISTINCT city FROM students; Bengaluru, Mysuru, Hassan (Unique list only)

🏋️ Test Yourself With Exercises

Take our quiz on DISTINCT to test your knowledge.

Browse Quizzes »