EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

SQL SELECT DISTINCT

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » SQL Tutorial » SQL SELECT DISTINCT

SQL SELECT DISTINCT

Introduction to SQL SELECT DISTINCT

DISTINCT keyword in SQL is used to fetch only unique records from a database table. It is usually used in conjunction with the SELECT statement. For uninitiated, the SELECT statement is used to fetch desired records from the datatable. Distinct keyword removes all duplicate records and fetches only unique ones. It can further be used with aggregate functions like AVG, MAX, MIN, SUM, COUNT, etc.

SELECT DISTINCT keyword is very helpful when a table contains many duplicate values and we have to fetch unique records only, for example in business scenarios where we want to know the distinct locations from where orders are being placed, how many distinct sets of customers do we have, etc.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax and Parameters

The basic syntax for writing a SELECT DISTINCT statement in SQL is as follows:

SELECT DISTINCT column_name1, column_name2,...
FROM table_name;

The parameters used in the above-mentioned syntax are as follows:

  • column_name1, column_name2,..: These are the columns or fields which you want to fetch in your final result set.
  • table_name: This is the name of the table from which said columns or fields will be fetched from.

How Does SELECT Statements with DISTINCT Keyword Work in SQL?

DISTINCT keyword in SQL filters out duplicate values from our returned results. For more simplification of its working, we may look at it in the following way:

  • A SELECT DISTINCT statement first builds our overall result set with all records, i.e including duplicate values based on FROM, JOIN, WHERE, HAVING, etc statements.
  • Next, it sorts the result set based on the column_name or field with which DISTINCT has been used.
  • Then it performs de-duplication (i.e. removes any duplicate values) on the overall result set which was prepared in the first step.

The SELECT DISTINCT statement can be considered semantically equivalent to a GROUP BY with all returned fields mentioned in the GROUP BY clause.

Having discussed the syntax and working of SELECT DISTINCT statements, let us go ahead and try some examples to develop a great understanding of this concept.

Examples of SQL SELECT DISTINCT

In order to illustrate the working of SQL DISTINCT keyword, what could be better than creating a dummy database table. Let us create a table called “customers”.

We can use the code snippet given below for performing this task.

Popular Course in this category
MS SQL Training (13 Courses, 11+ Projects)13 Online Courses | 11 Hands-on Projects | 62+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,998 ratings)
Course Price

View Course

Related Courses
JDBC Training (6 Courses, 7+ Projects)PHP Training (5 Courses, 3 Project)Windows 10 Training (4 Courses, 4+ Projects)SQL Training Program (7 Courses, 8+ Projects)PL SQL Training (4 Courses, 2+ Projects)Oracle Training (14 Courses, 8+ Projects)

Query:

CREATE TABLE public.customers
(
customer_id integer NOT NULL,
sale_date date NOT NULL,
sale_amount numeric NOT NULL,
salesperson character varying(255),
store_state character varying(255),
order_id character varying(255)
);

We have successfully created the table. Now let us insert some records in it to work with.

Query:

INSERT INTO public.customers(
customer_id, sale_date, sale_amount, salesperson, store_state, order_id)
VALUES (1001,'2020-05-23',1200,'Raj K','KA','1001'),
(1001,'2020-05-22',1200,'M K','NULL','1002'),
(1002,'2020-05-23',1200,'Malika Rakesh','MH','1003'),
(1003,'2020-05-22',1500,'Malika Rakesh','MH','1004'),
(1001,'2020-05-23',1320,'Dave Peter','MH','1005'),
(1002,'2020-05-21',1200,'Molly Samberg','NY','1001'),
(1004,'2020-05-22',1210,'M K','NULL','1003');

Output: 

SQL SELECT DISTINCT Example 1

We have successfully inserted 7 records in the table. The customers table after performing the above insertions looks something as follows:

Query:

SELECT * FROM customers;

Output:

SQL SELECT DISTINCT Example 2

Now let us try some examples using the DISTINCT keyword in conjunction with the SELECT statement.

Example #1

Find the customer ids of all the unique customers who have bought or ordered something from the departmental store.

Query:

SELECT DISTINCT customer_id
FROM customers;

Output:

SQL SELECT DISTINCT Example 3

In this example, we can see that the distinct keyword has fetched only the unique customer ids.

Example #2

Find all the unique dates on which sales were made at the departmental store.

Query:

SELECT DISTINCT sale_date
FROM customers;

Output:

SQL SELECT DISTINCT Example 4

Example #3

Find all the distinct store locations where the departmental store is located.

Query:

SELECT DISTINCT store_state
FROM customers
ORDER BY store_state ASC;

Output:

SQL SELECT DISTINCT Example 5

Explanation: The thing with NULL values and the DISTINCT keyword is that DISTINCT lets the first NULL in the final result set and removes all other subsequent NULL values. This can be observed in this example also. We had two NULL values in the store_state column, but DISTINCT has made room for only one NULL in the final result set.

Example #4

Find all the unique orders that were made on a particular date in the departmental store.

Query:

SELECT DISTINCT sale_date,
salesperson,
order_id,
store_state
FROM customers
ORDER BY sale_date;

Output:

SQL SELECT DISTINCT Example 6

Example #5

Find the sum of revenue collected for all the unique orders that were made on a particular date at a particular store of the departmental store.

Query:

SELECT DISTINCT sale_date, store_state,
sum(sale_amount) as total_sales
FROM customers
GROUP BY store_state, sale_date
ORDER BY sale_date ASC;

Output:

unique orders Example 7

Example #6

Find all the unique customers and the sum of total money spent by them at the departmental store.

Query:

SELECT DISTINCT customer_id,
sum(sale_amount) as total_sales
FROM customers
GROUP BY customer_id
ORDER BY customer_id ASC;

Output:

unique customers Example 8

Example #7

Find all the unique salespeople working in the departmental store.

Query:

SELECT DISTINCT salesperson
FROM customers;

Output:

unique salespeople Example 9

Conclusion

SQL DISTINCT keyword is used mostly in the conjugation of SELECT statements to fetch only unique records from the specified table by removing duplicate values from the final result set.

Recommended Articles

This is a guide to SQL SELECT DISTINCT. Here we discuss the Introduction of SELECT DISTINCT in SQL and the practical examples and different subquery expressions. You can also go through our suggested articles to learn more –

  1. Top 5 Examples of SQL Server Substring
  2. Overview of Triggers in SQL
  3. Introduction to SQL Arithmetic Operators
  4. ANY in SQL | Examples | Syntax

MS SQL Training (13 Courses, 11+ Projects)

13 Online Courses

11 Hands-on Projects

62+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
SQL Tutorial
  • Queries
    • SQL Insert Query
    • SQL SELECT Query
    • SQL SELECT RANDOM
    • SQL Except Select
    • SQL Subquery
    • SQL SELECT DISTINCT
    • SQL WITH AS Statement
  • Basic
    • What is SQL
    • Careers in SQL
    • Careers in SQL Server
    • IS SQL Microsoft?
    • SQL Management Tools
    • What is SQL Developer
    • Uses of SQL
    • How to Install SQL Server
    • What is SQL Server
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • SQL Enum
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • SQL Alter Command
    • SQL Commands Update
    • SQL DML Commands
    • SQL DDL Commands
    • FETCH in SQL
  • Clause
    • SQL Clauses
    • SQL IN Operator
    • SQL LIKE Clause
    • SQL NOT Operator
    • SQL Minus
    • SQL WHERE Clause
    • SQL with Clause
    • SQL HAVING Clause
    • GROUP BY clause in SQL
    • SQL GROUP BY DAY
    • ORDER BY Clause in SQL
    • SQL ORDER BY CASE
    • SQL ORDER BY DATE
    • SQL ORDER BY Alphabetical
    • SQL ORDER BY Ascending
    • SQL Order by Count
    • SQL GROUP BY Month
    • SQL GROUP BY Multiple Columns
    • SQL GROUPING SETS
  • Keys
    • SQL Keys
    • Primary Key in SQL
    • Foreign Key in SQL
    • Unique Key in SQL
    • Alternate Key in SQL
    • SQL Super Key
  • Functions
    • SQL Date Function
    • SQL String Functions
    • SQL Compare String
    • SQL Window Functions
    • SQL Timestamp
    • SQL TO_DATE()
    • SQL DATEADD()
    • SQL DATEDIFF()
    • ANY in SQL
    • LIKE Query in SQL
    • BETWEEN in SQL
    • LTRIM() in SQL
    • TOP in SQL
    • SQL Select Top
    • Merge SQL
    • SQL TRUNCATE()
    • SQL UNION
    • SQL ALL
    • SQL INTERSECT
    • SQL Alias
    • SQL Server Substring
    • CUBE in SQL
    • SQL RANK()
    • SQL MOD()
    • SQL CTE
    • SQL LAG()
    • SQL MID
    • SQL avg()
    • SQL WEEK
    • SQL DELETE
    • SQL DATEPART()
    • SQL DECODE()
    • SQL DENSE_RANK()
    • SQL NTILE()
    • SQL NULLIF()
    • SQL Stuff
    • SQL Ceiling
    • SQL EXISTS
    • SQL LEAD()
    • SQL COALESCE
    • SQL BLOB
    • SQL ROW_NUMBER
    • SQL Server Replace
    • SQL Server Permission
    • T-SQL INSERT
    • SQL Ranking Function
  • Joins
    • Join Query in SQL
    • Types of Joins in SQL
    • Types of Joins in SQL Server
    • SQL Inner Join
    • SQL Join Two Tables
    • SQL Delete Join
    • SQL Left Join
    • SQL Right Join
    • SQL Cross Join
    • SQL Outer Join
    • SQL Full Join
    • SQL Self Join
    • Natural Join SQL
    • SQL Multiple Join
  • Advanced
    • SQL Formatter
    • SQL Injection Attack
    • Aggregate Functions in SQL
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL INSTR()
    • What is Procedure in SQL
    • Stored Procedure in SQL?
    • SQL Server Constraints
    • SQL DELETE ROW
    • Column in SQL
    • Table in SQL
    • SQL Virtual Table
    • SQL Merge Two Tables
    • SQL Table Partitioning
    • SQL Temporary Table
    • SQL Clone Table
    • SQL Rename Table
    • SQL LOCK TABLE
    • SQL Clear Table
    • SQL DESCRIBE TABLE
    • SQL Mapping
    • Cursors in SQL
    • AND in SQL
    • Wildcard in SQL
    • SQL FETCH NEXT
    • SQL Views
    • SQL Delete View
    • Triggers in SQL
    • SQL UPDATE Trigger
    • SQL AFTER UPDATE Trigger
    • SQL Update Statement
    • SQL DROP TRIGGER
    • Types of SQL Views
    • SQL Port
    • SQL Clustered Index
    • SQL COMMIT
    • Distinct Keyword in SQL
    • PARTITION BY in SQL
    • SQL Set Operators
    • SQL UNION ALL
    • Metadata in SQL
    • SQL Bulk Insert
    • Array in SQL
    • SQL REGEXP
    • JSON in SQL
    • SQL For loop
    • EXPLAIN in SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL pivot
    • SQL Import CSV
  • Interview Questions
    • SQL Interview Questions
    • Advance SQL Interview Questions
    • SQL Joins Interview Questions
    • SQL Server Interview Questions

Related Courses

JDBC Training Course

PHP course

Windows 10 Training

SQL Course Training

PL/SQL Certification Courses

Oracle Certification Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - MS SQL Training (13 Courses, 11+ Projects) Learn More