SELECT DISTINCT command to find UNIQUE value in SQL

SQL

SQL command “SELECT DISTINCT” is used to retrieve unique values from a specified column or set of columns in a database table. It eliminates duplicate entries, ensuring that only distinct (unique) values are returned in the result set.

Syntax

SELECT DISTINCT column1, column2
FROM table_name
WHERE conditions;

Let’s break it down:

  • SELECT DISTINCT: This part of the command specifies that you want to select unique values.
  • column1, column2, …: Here, you list the columns from which you want to retrieve unique values. If you specify multiple columns, the combination of values in those columns should be unique.
  • FROM table_name: Specifies the table from which you want to select the data.
  • WHERE conditions (optional): You can include conditions to filter the data based on certain criteria if needed.

Practical Example

Scenario

Imagine you have a database table named “Students” with the following structure:

student_idstudent_namecourse
1AliceMath
2BobScience
3AliceHistory
4CharlieEnglish
5BobMath

Problem

You want to retrieve a list of unique courses from the “Students” table.

Solution

SELECT DISTINCT course
FROM Students;

Output

course
Math
Science
History
English

In this example, the “SELECT DISTINCT” statement fetches unique values from the “course” column in the “Students” table, eliminating duplicate entries.

Example 2: Unique Courses for Each Student

Scenario

Find the unique courses each student is enrolled in.

Solution

SELECT DISTINCT student_name, course
FROM Students;

Output

student_namecourse
AliceMath
BobScience
AliceHistory
CharlieEnglish
BobMath

Here, the query returns a combination of unique student names and the courses they are enrolled in, ensuring no duplicate pairs are included.

Ensure you include the “DISTINCT” keyword; otherwise, the query will retrieve all values, including duplicates.

Combine “SELECT DISTINCT” with aggregate functions like COUNT, AVG, etc., for more advanced queries.