Ticker

6/recent/ticker-posts

DISTINCT in SQL

DISTINCT in SQL


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:

sql
SELECT DISTINCT column1, column2, ... FROM table_name;

Example Consider a table named "Employees" with the following data:

EmployeeIDFirstNameLastName
1JohnSmith
2JaneDoe
3JohnSmith
4MarkJohnson

To retrieve a distinct list of employee names, we can use the following query:

sql
SELECT 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:

FirstNameLastName
JohnSmith
JaneDoe
MarkJohnson

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.

Post a Comment

0 Comments