SQL Distinct
Example Table
We will use the following table named employees for our examples:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10, 2)
);
INSERT INTO employees (employee_id, employee_name, department, salary) VALUES
(1, 'John Doe', 'HR', 50000.00),
(2, 'Jane Smith', 'Finance', 60000.00),
(3, 'Sam Brown', 'IT', 70000.00),
(4, 'Nancy White', 'HR', 55000.00),
(5, 'Mike Green', 'Finance', 65000.00);
| employee_id | employee_name | department | salary |
|---|---|---|---|
| 1 | John Doe | HR | 50000.00 |
| 2 | Jane Smith | Finance | 60000.00 |
| 3 | Sam Brown | IT | 70000.00 |
| 4 | Nancy White | HR | 55000.00 |
| 5 | Mike Green | Finance | 65000.00 |
Using SQL DISTINCT
The SQL DISTINCT keyword is used to return only distinct (different) values.
Selecting Distinct Values from a Column
To select distinct values from a column, use SELECT DISTINCT column_name FROM table_name:
SELECT DISTINCT department
FROM employees;
Result:
| department | HR |
|---|---|
| Finance | |
| IT |
Selecting Distinct Values from Multiple Columns
To select distinct values from multiple columns, use SELECT DISTINCT column1, column2 FROM table_name:
SELECT DISTINCT department, salary
FROM employees;
Result:
| department | HR |
|---|---|
| salary | 50000.00 |
| department | Finance |
| salary | 60000.00 |
| department | IT |
| salary | 70000.00 |
| department | HR |
| salary | 55000.00 |
| department | Finance |
| salary | 65000.00 |
Counting Distinct Values
To count the number of distinct values in a column, use SELECT COUNT(DISTINCT column_name) FROM table_name:
SELECT COUNT(DISTINCT department) AS unique_departments
FROM employees;
Result:
| unique_departments | 3 |
|---|