DISTINCT in SQL

For Complete YouTube Video: Click Here

In this class, we will understand DISTINCT in SQL.

We have already discussed the concepts of ‘ORDER BY.’

DISTINCT in SQL

The DISTINCT statement is used to return only different values of a column or a group of columns.

If we want to get the distinct values in a column or a group of columns, we can use the DISTINCT in SQL.

Examples on DISTINCT

To understand this, we will consider the table shown below.

DISTINCT in SQL 1
DISTINCT 1

We can select different salaries paid to the students, and the query is as shown below.

SELECT DISTINCT salary FROM students;

The output of the query is shown below.

DISTINCT in SQL 2
DISTINCT 2

Similarly, to get the distinct sex of the students.

SELECT DISTINCT sex FROM students;

The output of the query is shown below.

DISTINCT in SQL 3
DISTINCT 3

We can apply the distinct on two or more columns also.

When applying the distinct on two or more columns, the different values after combining the columns are obtained.

SELECT DISTINCT salary, sex FROM students;

The output of the query is as shown below.

DISTINCT in SQL 4
DISTINCT 4