SQL DISTINCT: Return Unique Rows and Values

SQL DISTINCT query

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.

Important: DISTINCT applies to the complete set of selected columns. With SELECT DISTINCT class, gender, uniqueness is based on the combination of class and gender.
Collecting unique data from columns of Database table by using DISTINCT query - SQL basics

SQL DISTINCT Syntax Top ↑

SELECT DISTINCT column1, column2
FROM table_name;

DISTINCT removes duplicate result rows after the selected expressions have been evaluated.

Return Unique Values from One Column Top ↑

Using the Plus2net student table:

idnameclassmark
1John DeoFour75
2Max RuinThree85
3ArnoldThree55
4Krish StarFour60
5John MikeFour60
6Alex JohnFour55
SELECT DISTINCT class
FROM student;

For these six sample rows, the result is:

class
Four
Three

DISTINCT with Multiple Columns Top ↑

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.

classgender
Fourfemale
Fourmale
Threefemale
Threemale
Download Student Table SQL Dump

DISTINCT with WHERE Top ↑

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 with ORDER BY Top ↑

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.

Count Unique Values with COUNT(DISTINCT) Top ↑

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.

DISTINCT and NULL Values Top ↑

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.
DISTINCT with NULL Data

DISTINCT vs GROUP BY Top ↑

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 vs UNIQUE Constraint Top ↑

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.

DISTINCT with JOIN Top ↑

Suppose a customer can make several purchases. A JOIN can therefore return the same customer more than once.

customer
c_idname
1alex B
2Rohn C
3Ravi J
4Jack E
5Raju K
6Roy K
sale
sale_idc_idproductprice
12book40
22CD30
31Book50
43Pen20
54Bag30
63Cap15

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_idname
1alex B
2Rohn C
3Ravi J
4Jack E

For customers who have not purchased anything, use a LEFT JOIN or another anti-match pattern rather than DISTINCT.

Unique Values from Two Columns with UNION Top ↑

Suppose tournament teams are stored in two columns:

Team_1Team_2Winner
IndiaSLIndia
SLAusAus
SAEngEng
EngNZNZ
AusIndiaIndia

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.

SQL for the tournament sample table Top ↑

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');

DISTINCT with PHP PDO Top ↑

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.

DISTINCT with Python SQLAlchemy Top ↑

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 Connection

DISTINCT Performance Notes Top ↑

  • DISTINCT may require sorting, hashing or temporary work to eliminate duplicate result rows.
  • Select only the columns you actually need. Adding more selected columns changes the definition of a duplicate row.
  • Indexes can help some DISTINCT queries, depending on the selected columns, WHERE conditions and execution plan.
  • Do not add DISTINCT merely to hide an incorrect JOIN that is creating unexpected duplicates. Fix the join logic when duplicate rows are not logically expected.
  • Use EXPLAIN when a DISTINCT query is unexpectedly expensive on a large table.

Common SQL DISTINCT Mistakes Top ↑

Thinking DISTINCT applies only to the first column Top ↑

With multiple selected columns, DISTINCT compares the complete selected row.

Confusing SELECT DISTINCT with COUNT(DISTINCT) Top ↑

SELECT DISTINCT returns the unique rows. COUNT(DISTINCT column) returns the number of distinct non-NULL values.

Assuming DISTINCT removes duplicate rows from the table Top ↑

DISTINCT changes only the query result. It does not modify stored data.

Using DISTINCT to hide a bad JOIN Top ↑

If the JOIN should logically return one row but produces many, check the join condition before adding DISTINCT.

Assuming DISTINCT sorts the result Top ↑

Use ORDER BY when output order matters.

Assuming COUNT(DISTINCT) counts NULL Top ↑

COUNT(DISTINCT expression) ignores NULL values.

SQL HAVING SQL GROUP BY COUNT(DISTINCT)

SQL UNION SQL LEFT JOIN Duplicate Records

Student Table SQL Dump

Frequently Asked Questions Top ↑

Q1: What does DISTINCT do in SQL?

DISTINCT removes duplicate rows from a SELECT result and returns each distinct selected row only once.

Q2: Does DISTINCT apply to one column or all selected columns?

It applies to the complete selected row. With SELECT DISTINCT class, gender, uniqueness is based on the combination of class and gender.

Q3: What is the difference between DISTINCT and GROUP BY?

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.

Q4: Does SELECT DISTINCT include NULL?

If NULL values are present, a DISTINCT result can contain one NULL row for that selected expression.

Q5: Does COUNT(DISTINCT column) count NULL?

No. COUNT(DISTINCT column) counts unique non-NULL values.

Q6: Does DISTINCT permanently remove duplicate data?

No. It changes only the SELECT result. Use appropriate constraints or a deliberate data-cleaning operation to control stored duplicates.

Q7: Is UNION the same as UNION ALL for duplicates?

No. UNION removes duplicate result rows by default, while UNION ALL keeps duplicates.



SQL HAVING DATE_FORMAT


Subscribe to our YouTube Channel here



plus2net.com
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.




SQL Video Tutorials










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer