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 the 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.

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
Sale
MS SQL Training (14 Courses, 11+ Projects)14 Online Courses | 11 Hands-on Projects | 62+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (9,247 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 customer’s 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

SQL Select Distinct statement

  • It will not work on multiple columns, we can use the same on a single column from the table from which we have retrieved the unique records.
  • We can use select distinct statements with aggregation like min, max, avg, count, etc. Below is the syntax of the select distinct statements.

Syntax –

Select DISTINCT name_of_column1, name_of_column2, …., name_of_columnN

From name_of_table;

  • Select DISTINCT name_of_column1, name_of_column2, …., name_of_columnN
From name_of_table where condition;
  • Select DISTINCT name_of_column from name_of_table order by name_of_column;
  • Below is the description syntax as follows.
  • Select – This is the SQL statement that was used to select the specified data from a table. We can select the data as per the condition which was given in the query. We can use select with a distinct statement to retrieve unique records from the table.
  • Name of column1 to the name of column N – This is the table column that was used with distinct keywords to retrieve data from a table. Suppose we have used a distinct statement with a specified column it will retrieve the distinct records from the table.
  • Name of the table – This is the name of the table from which we have retrieved the unique records. We need to define the table name while using statements.
  • Where condition – The where condition in any statement of SQL will be used to select or retrieved the specified row which we have defined in the where condition. Where a condition is very useful to retrieve a specific condition unique row by using a statement.
  • Order by – This condition is used to fetch the records as per the specified order. The default condition of the order is ascending order. Suppose we have given the explicit condition then it will retrieve the data as per the specified order which was we have given into the query.
  • At the time of using only one expression by using the distinct clause, our query will return the unique values from the expressions.
  • Suppose we are defining more than one expression our distinct clause will return the unique combination of the expressions.
  • We cannot ignore the null values by using the statement, while retrieving data our result will contain the distinct value as null.
  • In the below example, we can see that sql select statement will not ignore the null values from the specified column on which we are using distinct clauses.
Select distinct id, name from sql_distinct;
  • By using sql select distinct statements we can avoid the redundancy of data. This statement will be eliminating the appearance of repetitive data.
  • The below example shows statement keyword is case sensitive. In the first example, we have used keywords in the uppercase letter while in the second example we have used keywords in lowercase letters in both times it will return same result without issuing any error.
select DISTINCT id, name from sql_distinct;
select distinct id, name from sql_distinct;
  • We are using the sql_distinct table from a distinct database. We are using the Postgres database to see the example of sql select distinct. Below is the sample data from the sql_distinct table.
Select * from sql_distinct;
  • In the below example, we have found the distinct count of records from the id column. We can see that the unique records count of the id table is 4.
SELECT COUNT(DISTINCT id) FROM sql_distinct;
  • In the below example, we have found the distinct records from the sql_distinct table. Also, we are using order by clause on the id column as follows.
select distinct id, name from sql_distinct order by id;
  • The below example shows the use of a single column with sql select statement. In the below example, we are using only id column.
Select distinct id from sql_distinct;
  • In the below example we are using two-column names with an order by clause with sql select distinct statement. We are using the id, and name column as follows.
Select distinct id, name from sql_distinct order by id, name;
  • The below example shows a statement with the where condition. We are using where condition on id and name column by using sql select distinct statement. It will be returning only single values from the table.
Select distinct id from sql_distinct where id = 103 and name = 'PQR' order by id;
  • The below example shows with all the columns from the table are as follows.
Select distinct id, name from sql_distinct;

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)

14 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
    • SQL Server Versions
    • SQL Case Insensitive
    • SQL Expressions
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL WAITFOR
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • SQL Enum
    • SQL GROUP BY WHERE
    • SQL ROW
    • SQL EXECUTE
    • SQL EXCLUDE
    • SQL Performance Tuning
    • SQL UUID
    • Begin SQL
    • SQL Update Join
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • sqlplus set 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 DESC
    • 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
    • Timestamp to Date in SQL
    • SQL Window Functions
    • SQL CONCAT
    • SQL ALTER TABLE
    • SQL MOD()
    • SQL Timestamp
    • SQL TO_DATE()
    • SQL DATEADD()
    • SQL DATEDIFF()
    • SQL HOUR()
    • SQLite?functions
    • ANY in SQL
    • LIKE Query in SQL
    • SQL NOT NULL
    • SQL NOT IN
    • SQL MAX()
    • SQL MIN()
    • SQL SUM()
    • SQL COUNT
    • SQL identity
    • SQL DELETE Trigger
    • SQL Declare Variable
    • SQL Text Search
    • SQL COUNT DISTINCT
    • SQL TEXT
    • SQL Limit Order By
    • 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
    • T-SQL Stuff
    • T-SQL ADD Column
    • 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
    • LEFT OUTER JOIN in SQL
    • 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
    • SQL REVOKE
    • SQL Select Distinct Count
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL BIGINT
    • SQL Crosstab
    • SQL Wildcard Character
    • SQLAlchemy Filter
    • SQLAlchemy SQLite
    • SQLAlchemy DateTime
    • SQLAlchemy create_engine
    • SQL INSTR()
    • SQL now
    • SQL synonyms
    • SQLite?export to csv
    • 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
    • ROLLUP in SQL
    • Escape Character SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL pivot
    • SQL Import CSV
    • SQL if then else
    • SQL ignore-case
    • SQL Matches
    • SQL Search String
    • SQL Column Alias
    • SQL extensions
    • SQL Substring Function
    • Charindex SQL
  • NoSQ
    • NoSQL Databases List
    • NoSQL Injection
    • NoSQL vs SQL Databases
  • 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
  • Live Classes
  • 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

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

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

By signing up, you agree to our Terms of Use and Privacy Policy.

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

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

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

By signing up, you agree to our Terms of Use and Privacy Policy.

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