0 of 3 saved

Database Management Systems2 min read

DISTINCT keyword

Read this chapter, write the program on this page, then pass a short check to open the next one.

Distinct keyword is used with Select statement to retrieve unique values from the table. Distinct removes all the duplicate records while retrieving from database.

DISTINCT keyword

SQL DISTINCT is a keyword in SQL that is used with the SELECT statement to retrieve unique values from the table. It removes all the duplicate records while retrieving records from any table in the database.

Important Points:

  • It can be used with aggregate functions: COUNT, AVG, MAX, etc.
  • DISTINCT operates on a single column. Multiple columns are not supported for DISTINCT.
  • If we apply the DISTINCT clause to a column that has a NULL value, it will keep only one NULL value and eliminates the other.

Syntax:

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

Sample Table

Let us use the below Employee table to perform the DISTINCT keyword.

SQL table

Example: DISTINCT with Single Field

In the employee table, multiple employees have the same salary, so we will use DISTINCT keyword to list down distinct salary amount, that is currently being paid to the employees. The below SQL query will return only the unique salary from the employee table.

    SELECT DISTINCT salary 
    FROM employee;

Output:

SQL table

Example: DISTINCT with Multiple Field

In the employee table, multiple employees have the same age, so we will use DISTINCT keyword to list down distinct ages with names. The below SQL query will return only the unique ages and their corresponding names from the employee table.

    SELECT DISTINCT(age), name
    FROM employee
    where age >= 35;

Output:

SQL table

Note:

  • Both the DISTINCT and GROUP BY clauses reduce the number of returned rows in the result set by removing the duplicates. However, you should use the GROUP BY clause when you want to apply an aggregate function on one or more columns.
  • A SQL SELECT UNIQUE and SQL SELECT DISTINCT statements are the same but most databases use the DISTINCT keyword. Microsoft Access database does not support the DISTINCT keyword.

Conclusion

In this article, we discussed SQL SELECT DISTINCT keyword that finds the unique values from the given column using different examples.