Wednesday, December 18, 2024

SQL SELECT DISTINCT Keyword

 The SELECT DISTINCT keyword in SQL is used to retrieve unique values from a column or a combination of columns in a database table. When you use DISTINCT, it removes duplicate rows from the result set.

Here is the basic syntax:

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

Example 1: Using DISTINCT on a Single Column

If you have a table of employees and you want to get all unique job titles:

SELECT DISTINCT job_title
FROM employees;

This query will return a list of distinct (non-duplicate) job titles from the employees table.

Example 2: Using DISTINCT on Multiple Columns

If you want to get distinct combinations of two or more columns (for example, getting unique combinations of job titles and departments), you can use DISTINCT across multiple columns:

SELECT DISTINCT job_title, department
FROM employees;

This query will return unique combinations of job_title and department, excluding any duplicates.

Example 3: Using DISTINCT with Aggregate Functions

You can also combine DISTINCT with aggregate functions like COUNT(), SUM(), etc. For example, to count how many unique job titles exist in the employees table:

SELECT COUNT(DISTINCT job_title)
FROM employees;

This query counts the number of unique job titles in the employees table.

Notes:

  • DISTINCT operates across the entire row when used with multiple columns. This means it will only return rows where the combination of values in all specified columns is unique.
  • The DISTINCT keyword can slow down query performance on large tables, as the database must filter out duplicates.

No comments:

Post a Comment