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.
SELECT DISTINCT column1, column2
FROM table_name
WHERE conditions;
Let’s break it down:
Imagine you have a database table named “Students” with the following structure:
student_id | student_name | course |
---|---|---|
1 | Alice | Math |
2 | Bob | Science |
3 | Alice | History |
4 | Charlie | English |
5 | Bob | Math |
You want to retrieve a list of unique courses from the “Students” table.
SELECT DISTINCT course
FROM Students;
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.
Find the unique courses each student is enrolled in.
SELECT DISTINCT student_name, course
FROM Students;
student_name | course |
---|---|
Alice | Math |
Bob | Science |
Alice | History |
Charlie | English |
Bob | Math |
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.