What is the purpose of the DISTINCT keyword in SQL?

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


In the seemingly infinite world of Structured Query Language (SQL), one keyword that often brings confusion, especially among beginners is the DISTINCT keyword. This post aims to demystify this keyword, providing you with all the knowledge you need to use it accurately and effectively in SQL.

Understanding the DISTINCT Keyword

In SQL, the DISTINCT keyword is used in the SELECT statement to eliminate all the duplicate records and fetching only unique records. It is beneficial when you want to obtain a list of unique elements from the specified column(s).

SQL DISTINCT Syntax

Example of DISTINCT Keyword

Let’s use a simple example to understand its use; imagine we have a ‘Students’ table with a ‘Course’ column. If we want to see only the unique course names where our students are enrolled, we can use the DISTINCT keyword as follows:

This statement will return only distinct (different) course names where students are enrolled despite many students possibly being enrolled in the same course.

DISTINCT in Multiple Columns

Sometimes, you might need to use DISTINCT on more than one column. In such a situation, the DISTINCT keyword considers the combinations of the result set. Here’s how you can use the DISTINCT keyword with multiple columns:

This SQL statement will return all distinct combinations of ‘Course’ and ‘Semester’ from the ‘Students’ table.

Conclusion

Understanding the DISTINCT keyword and its functionality plays a pivotal role in crafting efficient SQL queries. It helps eliminate redundancies, providing a cleaner and more precise data set. However, be cautious while using DISTINCT as it can significantly hamper the performance with larger data sets.

Leave a Comment