Need help from an expert?
The world’s top online tutoring provider trusted by students, parents, and schools globally.
The DISTINCT keyword in SQL is used to return unique values in the output, eliminating all the duplicate records.
In more detail, when you're working with databases, you often encounter tables that contain duplicate rows. This is especially common when you're dealing with large datasets. The DISTINCT keyword in SQL helps you to deal with this issue by eliminating duplicate rows and returning only unique records.
When you use the DISTINCT keyword, SQL checks each row of the selected columns in the table and discards any duplicates, only keeping the first unique instance of each record. It's important to note that the DISTINCT keyword works on the set of columns in the SELECT clause. If you select multiple columns, the DISTINCT keyword will consider the combination of values in these columns for uniqueness.
For example, if you have a table of customers and you want to know how many different cities your customers come from, you could use the DISTINCT keyword to find out. Your SQL query might look something like this: SELECT DISTINCT city FROM customers. This would return a list of cities, with each city only appearing once in the list, regardless of how many customers come from each city.
However, if you were to select two columns, such as city and country, using the DISTINCT keyword like this: SELECT DISTINCT city, country FROM customers, the query would return unique combinations of city and country. So, if you have customers from London, UK and London, Canada, both would appear in the result set because they are considered unique combinations.
In summary, the DISTINCT keyword in SQL is a handy tool for eliminating duplicate records from your query results. It works by comparing the values in the selected columns and discarding any duplicates, leaving only unique records in the output.
Study and Practice for Free
Trusted by 100,000+ Students Worldwide
Achieve Top Grades in your Exams with our Free Resources.
Practice Questions, Study Notes, and Past Exam Papers for all Subjects!
The world’s top online tutoring provider trusted by students, parents, and schools globally.