SQL distinct clause is used to remove duplicate rows from database table name. distinct keyword can be used on one column name and more than one column name in SQL query. distinct clause can be implemented in MySQL, oracle, db2, Microsoft SQL server.
SQL distinct query example explains how to use distinct query in SQL.
Table class_name with all records without desired column name sorting
+---------+-------------+------------+------------+ | Roll_No | Name | Class_Name | Year_Start | +---------+-------------+------------+------------+ | 1 | Amit Mishra | B.Science | 2005 | | 2 | Robot | B.Tech | 2005 | | 3 | Rohan | M.Tech | 2005 | | 4 | Vivek | B.Tech | 2009 | | 5 | Chander | B.Science | 2009 | | 6 | Deepak | B.Science | 2009 | | 7 | Gagan Deep | B.Tech | NULL | | 8 | Mohit Garg | M.Tech | NULL | +---------+-------------+------------+------------+
syntax of SQL distinct
SELECT distinct columns FROM table_name
distinct examples
SELECT distinct Roll_No, Name, Class_Name, Year_Start FROM class_name c;
Output
+---------+-------------+------------+------------+ | Roll_No | Name | Class_Name | Year_Start | +---------+-------------+------------+------------+ | 1 | Amit Mishra | B.Science | 2005 | | 2 | Robot | B.Tech | 2005 | | 3 | Rohan | M.Tech | 2005 | | 4 | Vivek | B.Tech | 2009 | | 5 | Chander | B.Science | 2009 | | 6 | Deepak | B.Science | 2009 | | 7 | Gagan Deep | B.Tech | NULL | | 8 | Mohit Garg | M.Tech | NULL | +---------+-------------+------------+------------+
this SQL query returns all rows return because no duplicate row is found. all column name is distinct
SELECT distinct Class_Name, Year_Start FROM class_name;
Output
+------------+------------+ | Class_Name | Year_Start | +------------+------------+ | B.Science | 2005 | | B.Tech | 2005 | | M.Tech | 2005 | | B.Tech | 2009 | | B.Science | 2009 | | B.Tech | NULL | | M.Tech | NULL | +------------+------------+
this SQL query returns those row which column name (Class_Name, Year_Start) not duplicate rows value only from table.
SELECT distinct Class_Name FROM class_name;
Output
+------------+ | Class_Name | +------------+ | B.Science | | B.Tech | | M.Tech | +------------+
this SQL query check distinct on only one column name Class_Name and check duplicate rows in Class_Name column name and remove duplicate rows.
* indicates fetch all columns records from table.




Link to Us