DISTINCT removes duplicate rows from a SELECT result. To return each class only once:
SELECT DISTINCT class
FROM student
ORDER BY class;
If class Four appears several times in the table, it appears only once in this result.
SELECT DISTINCT class, gender, uniqueness is based on the combination of class and gender.SELECT DISTINCT column1, column2
FROM table_name;
DISTINCT removes duplicate result rows after the selected expressions have been evaluated.
Using the Plus2net student table:
| id | name | class | mark |
|---|---|---|---|
| 1 | John Deo | Four | 75 |
| 2 | Max Ruin | Three | 85 |
| 3 | Arnold | Three | 55 |
| 4 | Krish Star | Four | 60 |
| 5 | John Mike | Four | 60 |
| 6 | Alex John | Four | 55 |
SELECT DISTINCT class
FROM student;
For these six sample rows, the result is:
| class |
|---|
| Four |
| Three |
With more than one selected column, DISTINCT removes duplicate combinations.
SELECT DISTINCT class, gender
FROM student
ORDER BY class, gender;
If one class contains both male and female students, that class can appear twice because the two (class, gender) combinations are different.
| class | gender |
|---|---|
| Four | female |
| Four | male |
| Three | female |
| Three | male |
Use WHERE first when only selected rows should contribute to the distinct result.
SELECT DISTINCT class
FROM student
WHERE mark >= 70
ORDER BY class;
This returns the different classes represented by students whose mark is at least 70.
DISTINCT removes duplicate result rows; ORDER BY controls their display order.
SELECT DISTINCT class
FROM student
ORDER BY class ASC;
Do not rely on DISTINCT itself to return values in a particular order.
Use COUNT(DISTINCT ...) when you need the number of unique non-NULL values rather than the values themselves.
SELECT COUNT(DISTINCT class) AS unique_classes
FROM student;
For the complete Plus2net student table, the output is 7.
If a selected column contains several NULL values, SELECT DISTINCT returns one NULL row for that distinct result.
SELECT DISTINCT class
FROM student3;
This differs from COUNT(DISTINCT class), which counts distinct non-NULL class values and does not count NULL.
SELECT DISTINCT class can display one NULL result. COUNT(DISTINCT class) excludes NULL from the count.For simply returning unique values, DISTINCT expresses the intent directly:
SELECT DISTINCT class
FROM student;
A GROUP BY query can produce the same list:
SELECT class
FROM student
GROUP BY class;
However, GROUP BY is primarily used when you want one result row per group together with aggregate calculations:
SELECT class,
COUNT(*) AS total_students,
AVG(mark) AS average_mark
FROM student
GROUP BY class;
Use DISTINCT for deduplicating a SELECT result. Use GROUP BY when the groups themselves are needed for aggregate analysis.
DISTINCT is a query operator. It changes only the rows returned by that SELECT.
A UNIQUE constraint is a table rule used to prevent duplicate values from being stored in a constrained key.
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(255) NOT NULL UNIQUE
);
Using DISTINCT does not clean or permanently remove duplicate data from the table.
Suppose a customer can make several purchases. A JOIN can therefore return the same customer more than once.
| c_id | name |
|---|---|
| 1 | alex B |
| 2 | Rohn C |
| 3 | Ravi J |
| 4 | Jack E |
| 5 | Raju K |
| 6 | Roy K |
| sale_id | c_id | product | price |
|---|---|---|---|
| 1 | 2 | book | 40 |
| 2 | 2 | CD | 30 |
| 3 | 1 | Book | 50 |
| 4 | 3 | Pen | 20 |
| 5 | 4 | Bag | 30 |
| 6 | 3 | Cap | 15 |
Return each customer who has at least one sale only once:
SELECT DISTINCT c.c_id, c.name
FROM customer AS c
INNER JOIN sale AS s
ON s.c_id = c.c_id
ORDER BY c.c_id;
| c_id | name |
|---|---|
| 1 | alex B |
| 2 | Rohn C |
| 3 | Ravi J |
| 4 | Jack E |
For customers who have not purchased anything, use a LEFT JOIN or another anti-match pattern rather than DISTINCT.
Suppose tournament teams are stored in two columns:
| Team_1 | Team_2 | Winner |
|---|---|---|
| India | SL | India |
| SL | Aus | Aus |
| SA | Eng | Eng |
| Eng | NZ | NZ |
| Aus | India | India |
UNION combines the two result sets and removes duplicate rows:
SELECT Team_1 AS team
FROM icc_world_cup
UNION
SELECT Team_2
FROM icc_world_cup
ORDER BY team;
The unique teams are Aus, Eng, India, NZ, SA and SL.
UNION removes duplicate rows by default. UNION ALL keeps duplicates.CREATE TABLE icc_world_cup (
Team_1 VARCHAR(20) DEFAULT NULL,
Team_2 VARCHAR(20) DEFAULT NULL,
Winner VARCHAR(20) DEFAULT NULL
) ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4;
INSERT INTO icc_world_cup
(Team_1, Team_2, Winner)
VALUES
('India', 'SL', 'India'),
('SL', 'Aus', 'Aus'),
('SA', 'Eng', 'Eng'),
('Eng', 'NZ', 'NZ'),
('Aus', 'India', 'India');
For a static DISTINCT query containing no external values, PDO query() is sufficient:
<?php
require 'config.php';
$sql="SELECT DISTINCT class, gender
FROM student
ORDER BY class, gender";
$stmt=$dbo->query($sql);
echo '<table class="table table-striped">';
echo '<tr><th>Class</th><th>Gender</th></tr>';
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$class=htmlspecialchars(
(string)$row['class'],
ENT_QUOTES,
'Windows-1252'
);
$gender=htmlspecialchars(
(string)$row['gender'],
ENT_QUOTES,
'Windows-1252'
);
echo "<tr><td>$class</td><td>$gender</td></tr>";
}
echo '</table>';
If a WHERE condition contains application input, use a prepared statement for those values. See PDO SELECT and record fetching.
The existing Plus2net Python/MySQL example can use the same DISTINCT SQL. With modern SQLAlchemy, execute textual SQL through a connection:
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
engine = create_engine(
"mysql+mysqldb://root:pw@localhost/db"
)
try:
with engine.connect() as connection:
result = connection.execute(
text(
"SELECT DISTINCT class FROM student ORDER BY class"
)
)
for row in result:
print(row[0])
except SQLAlchemyError as error:
print(error)
The DISTINCT logic belongs to SQL; Python only executes the statement and consumes the result.
MySQL and Python ConnectionEXPLAIN when a DISTINCT query is unexpectedly expensive on a large table.With multiple selected columns, DISTINCT compares the complete selected row.
SELECT DISTINCT returns the unique rows. COUNT(DISTINCT column) returns the number of distinct non-NULL values.
DISTINCT changes only the query result. It does not modify stored data.
If the JOIN should logically return one row but produces many, check the join condition before adding DISTINCT.
Use ORDER BY when output order matters.
COUNT(DISTINCT expression) ignores NULL values.
DISTINCT removes duplicate rows from a SELECT result and returns each distinct selected row only once.
It applies to the complete selected row. With SELECT DISTINCT class, gender, uniqueness is based on the combination of class and gender.
DISTINCT is mainly used to remove duplicate result rows. GROUP BY forms groups so aggregate functions such as COUNT, SUM and AVG can calculate values for each group.
If NULL values are present, a DISTINCT result can contain one NULL row for that selected expression.
No. COUNT(DISTINCT column) counts unique non-NULL values.
No. It changes only the SELECT result. Use appropriate constraints or a deliberate data-cleaning operation to control stored duplicates.
No. UNION removes duplicate result rows by default, while UNION ALL keeps duplicates.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| kashif | 05-01-2009 |
| plus2net is gearttttt.....it is 1 of the best sites of da internet..i love this site for my problem solving n learning...plus2net is doing great job...best of luck.... | |
| Shaveen Kaushal | 18-03-2009 |
| Thank u very much | |
| Kamran | 13-07-2009 |
| i want to learn sql, i am the new joiner, so please if have you any basic | |
| Alok Patoria | 21-01-2010 |
| i found dis helpfull.bt dere should be some heierarchy for the topics. | |
| plooger | 01-04-2010 |
| How could this be modified to list only the classes in which a given student is NOT enrolled? | |
| Rayudu | 05-04-2010 |
| How could this be modified to list only the classes in which a given student is NOT enrolled? | |
| xyzzx | 20-04-2010 |
| it is only a introductory knowledge.pls if posible provide a detailed description | |
| srinivas | 04-10-2010 |
| Pls. help me in getting % of records from a table.. ex: 1000 records in a table i want 20% of records..i.e 200 records....how we can do in single statement | |
| Bibin | 18-11-2010 |
| select top 20 percent * from Table_Name Order by Table_Column_Name | |
| kishore | 04-01-2011 |
| how to display each class(field) with number of student name | |
| jacob | 10-05-2011 |
| Hi, This site is great. I appreciate your effort over making this valuable website Thank you | |
| praveen | 21-06-2011 |
| sir.,with the unique or distinct value how to take the related field values.... i.e, "select * from tablename where DISTINCT phoneno=+TextBox71.Text+"; | |
| jeheyr | 22-11-2011 |
| You should try "select DISTINCT phoneno, etc, etc, from tablename where phoneno = +TextBox71.Text+;" :) | |
| The Dod | 19-02-2012 |
| Thanks. Needed to sort timezones by gmtoff for something. SQL made my day. | |
| Roshan Pradhan | 23-02-2012 |
| plus2net is great site for programmer. thanks! | |
| swami naidu | 02-05-2012 |
| i am very happy to watch this site. it is very helpfull to me.. thanks alot... | |
| Rizwan | 04-08-2012 |
| sir, i want to return all fields using distint when i use "select distinct phone from talbe" it only retuns phone field but i also required sr in the same query look like this "select * from table distinct phone" | |
| Sahil Verma | 23-01-2013 |
| Thanx a lot... | |
| Anitha | 14-02-2013 |
| how to get top 10 distinct records modified recently | |
| umesh moradiya | 23-07-2013 |
| useful thank you.... | |
| marcoaugustus | 25-07-2013 |
| I need more discussions about using distinct query between two tables with more fields | |
| Nitesh Srivastva | 16-06-2014 |
| hello sir, i have a table name emply in there some column like department,sex,id,qualification i want each department how much male and how much female on there in a query plz justify me...currently i am using postgresql......... | |
| smo | 16-06-2014 |
| Check group by | |
| ayushi | 18-06-2014 |
| in my table recreg by using command select distinct r_id from recreg .it returns not distinct value but why | |
| Sasikanth | 23-09-2014 |
| Very Useful Site. | |
| gagz | 25-08-2015 |
| i learned a lot from all the tutorial.Thank you so much plus2net. | |
| palaniappan praveen | 22-10-2016 |
| when i insert duplicate values one of the field name record is empty in phpMYADMIN Why? and how to solve this? I need the SQL syntax for only insert statements which we can insert duplicate values in the table..how to do that? I hope you understand my questions clearly!!! | |
| smo1234 | 25-10-2016 |
| You can insert duplicate values if you don't have unique constraint for that field in your MySQL table. Remove that condition and see. | |
| priya | 17-08-2017 |
| How to write a sql query for , first day pen rate. 5 rs and 2nd day pen rate is 8 rs then what ill be the 3rd day pen rate. Write a query | |
13-08-2019 | |
| I stumbled on this while trying to resolve an issue and it was extremely helpful. Thanks and keep up the good work. | |