DISTINCT
Introduction to SQL
Database
SQL Basics
Creating a Database
Using a Database
Creating a Table
Common Data Types
Inserting Data
Selecting Data
WHERE Clause
Comparison Operators
AND, OR, and NOT
ORDER BY Clause
LIMIT Clause
DISTINCT
LIKE Operator
IN, BETWEEN, and IS NULL
Updating Data
Deleting Data
ALTER TABLE
DROP TABLE
PRIMARY KEY and NOT NULL
FOREIGN KEY and Relationships
Aggregate Functions
GROUP BY Clause
HAVING Clause
JOIN Basics
INNER JOIN
LEFT JOIN
Aliases
Subqueries
Indexes
User Permissions and Security
Common Mistakes Beginners Make
Practice Ideas
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
DISTINCTkeyword,NULLis considered a unique value. If you have multiple empty rows in a column,DISTINCTwill return exactly oneNULLin your list. - Multiple Columns: If you use
DISTINCTwith 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:
DISTINCTmust always come at the beginning of the column list. You cannot place it in the middle of aSELECTstatement.
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) |