Introduction The DISTINCT keyword in SQL is used to retrieve unique values from a specific column or a combination of columns in a table. It eliminates duplicate rows from the result set, ensuring that each row returned is distinct.
Syntax The basic syntax for using DISTINCT in SQL is as follows:
sqlSELECT DISTINCT column1, column2, ...
FROM table_name;
Example Consider a table named "Employees" with the following data:
EmployeeID | FirstName | LastName |
---|---|---|
1 | John | Smith |
2 | Jane | Doe |
3 | John | Smith |
4 | Mark | Johnson |
To retrieve a distinct list of employee names, we can use the following query:
sqlSELECT DISTINCT FirstName, LastName
FROM Employees;
Explanation In the given example, the SELECT statement retrieves distinct combinations of the FirstName and LastName columns from the Employees table. The result would be:
FirstName | LastName |
---|---|
John | Smith |
Jane | Doe |
Mark | Johnson |
The duplicate entry "John Smith" has been eliminated from the result set.
Considerations
- The DISTINCT keyword applies to the entire row, not just a specific column. It evaluates the uniqueness of the entire selected row, considering all columns specified in the SELECT statement.
- It is possible to use DISTINCT with multiple columns to obtain unique combinations of values from those columns.
- The DISTINCT keyword is often used in conjunction with the SELECT statement and other clauses such as WHERE, ORDER BY, etc., to refine the result set further.
Conclusion The DISTINCT keyword in SQL is a powerful tool for retrieving unique values from one or more columns in a table. It helps eliminate duplicates and provides a concise and focused view of the data. By understanding its syntax and usage, you can effectively utilize DISTINCT in your SQL queries.
0 Comments