Thursday, December 19, 2024

SQL SELECT DISTINCT Keyword

 The SELECT DISTINCT keyword in SQL is used to retrieve unique (non-duplicate) values from a column or a combination of columns. When you use DISTINCT, it ensures that the result set will only contain distinct (unique) records, eliminating duplicates.

Syntax:

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

Example:

Consider a table named Employees with the following data:

ID Name Department
1 John HR
2 Jane IT
3 John IT
4 Alice HR
5 Jane HR

Query:

SELECT DISTINCT Name, Department
FROM Employees;

Result:

Name Department
John HR
Jane IT
John IT
Alice HR
Jane HR

Here, the DISTINCT keyword ensures that you get unique combinations of Name and Department. Notice that even though there are duplicate names (John and Jane), the query will return distinct rows based on both Name and Department.

Notes:

  • If you use DISTINCT with multiple columns, it considers the combination of all specified columns.
  • If only one column is specified, it will return unique values for that column, eliminating any duplicate entries.

No comments:

Post a Comment