What is the purpose of the DISTINCT keyword in SQL?a)It removes duplic...
The DISTINCT keyword in SQL is used to retrieve unique or distinct values from a specific column in the query result.
View all questions of this test
What is the purpose of the DISTINCT keyword in SQL?a)It removes duplic...
The purpose of the DISTINCT keyword in SQL is to remove duplicate rows from the query result.
The DISTINCT keyword is used in SQL queries to eliminate duplicate rows from the result set. When querying a database table, it is common to have multiple rows with the same values in certain columns. However, in some cases, it is necessary to retrieve only the unique rows based on a specific set of columns. This is where the DISTINCT keyword comes into play.
How does the DISTINCT keyword work?
When the DISTINCT keyword is used in a SELECT statement, it instructs the database to return only the unique rows from the result set. It compares the values of the specified columns and removes any duplicate rows.
Example:
Consider a table called "employees" with the following data:
| ID | Name | Department |
|----|----------|------------|
| 1 | John | HR |
| 2 | Jane | IT |
| 3 | John | HR |
| 4 | Jane | IT |
| 5 | Michael | Sales |
If we want to retrieve the unique values from the "Name" column, we can use the DISTINCT keyword as follows:
```
SELECT DISTINCT Name FROM employees;
```
The result of this query would be:
| Name |
|---------|
| John |
| Jane |
| Michael |
As we can see, the duplicate rows with the names "John" and "Jane" were eliminated, and only the unique values were returned.
Conclusion
In summary, the DISTINCT keyword in SQL is used to remove duplicate rows from the query result. It compares the values of the specified columns and returns only the unique rows. This is useful when you want to retrieve distinct values based on a specific set of columns or eliminate redundancy in the result set.