
For an instructor lead, in-depth look at learning SQL click below.
When you’re dealing with a large database, it’s not uncommon to find duplicate records. SQL, a powerful language for managing and manipulating databases, provides a straightforward way to remove these replicated records and retrieve only the unique ones. This article is about the ‘DISTINCT’ keyword in SQL, which can be used to retrieve unique records from a table.
Introduction to DISTINCT keyword
The DISTINCT keyword is used in SQL SELECT statements to eliminate all the duplicate records and fetch only the unique records. The syntax for using DISTINCT keyword in SQL is as follows:
|
1 |
SELECT DISTINCT column_name FROM table_name; |
The DISTINCT keyword, in the SQL query, is placed directly before the name of the column where you want to remove duplicates.
Example
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
-- Assume we have a table named 'Employees' with below data: -- Employees -- | ID | Firstname | Lastname | -- |----|-----------|----------| -- | 1 | John | Doe | -- | 2 | Jane | Doe | -- | 3 | John | Doe | -- | 4 | Mary | Johnson | -- To get the unique values from column 'Firstname' in employees table, you could write this Query: SELECT DISTINCT Firstname FROM Employees; -- Output -- | Firstname | -- |-----------| -- | John | -- | Jane | -- | Mary | |
Distinct for Multiple Columns
We are not limited to a single column. The DISTINCT clause can include multiple columns. This will ensure the combination of values in these columns is unique across all the records returned.
Example
|
1 2 3 4 5 6 7 8 9 10 11 12 |
-- To get the unique combination of 'Firstname' and 'Lastname' in employees table, you would write this Query: SELECT DISTINCT Firstname, Lastname FROM Employees; -- Output -- | Firstname | Lastname | -- |-----------|----------| -- | John | Doe | -- | Jane | Doe | -- | Mary | Johnson | |
Conclusion
In this guide, we’ve understood the basic usage of the DISTINCT keyword in SQL to retrieve only unique records from a table. With the help of examples, not only did we delve into retrieving unique values from a single column, but also from multiple columns in a table. Keep practicing your SQL skills with more different scenarios and don’t forget to use DISTINCT when necessary!
