⬅ Previous Topic
LIMIT / TOP Clause in SQLNext Topic ⮕
SQL Operators - AND, OR, NOT, IN, BETWEEN, LIKE⬅ Previous Topic
LIMIT / TOP Clause in SQLNext Topic ⮕
SQL Operators - AND, OR, NOT, IN, BETWEEN, LIKEImagine you have a student table, and you're asked: "How many different classes are there?" Simply selecting the class
column will list all entries — including duplicates. This is where DISTINCT
shines. It helps you remove duplicates and see only unique values.
SELECT DISTINCT column1, column2, ...
FROM table_name;
Let’s work with this school dataset:
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
class VARCHAR(10),
city VARCHAR(30)
);
INSERT INTO students VALUES
(1, 'Aarav Sharma', '10A', 'Delhi'),
(2, 'Diya Iyer', '9B', 'Chennai'),
(3, 'Rohit Menon', '10A', 'Kochi'),
(4, 'Sneha Patil', '8C', 'Pune'),
(5, 'Mehul Agarwal', '9B', 'Delhi'),
(6, 'Aisha Khan', '8C', 'Hyderabad');
Let’s list all the unique classes:
SELECT DISTINCT class FROM students;
class
-------
10A
9B
8C
If we don’t use DISTINCT:
SELECT class FROM students;
class
-------
10A
9B
10A
8C
9B
8C
You can see how duplicate values clutter the output — DISTINCT solves that instantly.
You can also find unique combinations — like each unique (class, city) pair:
SELECT DISTINCT class, city FROM students;
class | city
------+-----------
10A | Delhi
9B | Chennai
10A | Kochi
8C | Pune
9B | Delhi
8C | Hyderabad
How many unique cities are students from?
SELECT COUNT(DISTINCT city) AS unique_city_count
FROM students;
unique_city_count
-------------------
5
When using multiple columns, DISTINCT returns only rows where the entire combination is unique — not just one column.
SELECT DISTINCT city FROM students;
city
---------
Delhi
Chennai
Kochi
Pune
Hyderabad
Let’s say the principal wants a list of cities to send school newsletters. You’d do:
SELECT DISTINCT city FROM students;
And print just those 5 cities — no duplicates, no redundancy.
The DISTINCT
keyword helps you cut through the noise — showing only what's different. Whether you're counting unique classes, listing hometowns, or generating reports with uniqueness in mind, DISTINCT keeps your data clean and purposeful.
Up next, we’ll explore Subqueries — writing queries inside queries for smarter, more powerful data retrieval.
SELECT DISTINCT class FROM students;
⬅ Previous Topic
LIMIT / TOP Clause in SQLNext Topic ⮕
SQL Operators - AND, OR, NOT, IN, BETWEEN, LIKEYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.