SQL Select Distinct
In SQL, the DISTINCT keyword is used to remove duplicate rows from the result set of a query.
What is DISTINCT in SQL?
Syntax:
You can also apply DISTINCT to multiple columns:
Example: STUDENTS Table
Without DISTINCT - Duplicates Included
Output:
With DISTINCT - Only Unique Ages
Output:
- DISTINCT eliminates duplicate records from the output of a SELECT statement.
- It returns only unique values from a column or a set of columns.
- DISTINCT can also be used with aggregate functions like COUNT(), SUM(), AVG(), etc.
- It works on one or more columns, filtering out rows where all selected columns are identical.
Syntax:
SELECT DISTINCT column_name
FROM table_name;
- column_name: The name of the column you want to fetch unique values from.
- table_name: The name of the table you are querying.
You can also apply DISTINCT to multiple columns:
SELECT DISTINCT column1, column2
FROM table_name;
Example: STUDENTS Table
Roll No | Name | Age |
---|---|---|
101 | Nobita | 18 |
102 | Suneo | 16 |
103 | Shizuka | 18 |
104 | Gian | 23 |
Without DISTINCT - Duplicates Included
SELECT age AS Age
FROM students;
Output:
Age |
---|
18 |
16 |
18 |
23 |
As you can see, age 18 appears twice because it is stored for two students.
With DISTINCT - Only Unique Ages
SELECT DISTINCT age AS Age
FROM students;
Output:
Age |
---|
18 |
16 |
23 |
Here, duplicate age 18 is removed, and only unique ages are returned.
Key Point
- Use DISTINCT when you want to avoid repeated values.
- It filters entire rows, not just individual columns.
- You can use it with single or multiple columns.
- Helps keep your query results clean and readable.