0
0
SQLquery~5 mins

DISTINCT for unique values in SQL

Choose your learning style9 modes available
Introduction
Use DISTINCT to get only unique values from a list, removing any duplicates.
When you want to find all different countries customers come from in a sales database.
When you need a list of unique product names from an inventory table.
When you want to count how many different cities appear in an address book.
When you want to see all unique job titles in an employee table.
Syntax
SQL
SELECT DISTINCT column_name FROM table_name;
DISTINCT applies to all columns listed after SELECT.
It removes duplicate rows from the result.
Examples
Get a list of unique countries from the customers table.
SQL
SELECT DISTINCT country FROM customers;
Find all different product names in the products table.
SQL
SELECT DISTINCT product_name FROM products;
Get unique combinations of city and state from addresses.
SQL
SELECT DISTINCT city, state FROM addresses;
Sample Program
This creates an employees table, adds some rows, then selects unique departments.
SQL
CREATE TABLE employees (id INT, name VARCHAR(50), department VARCHAR(50));
INSERT INTO employees VALUES (1, 'Alice', 'HR'), (2, 'Bob', 'IT'), (3, 'Charlie', 'HR'), (4, 'Diana', 'Finance');
SELECT DISTINCT department FROM employees;
OutputSuccess
Important Notes
DISTINCT works on the entire row if multiple columns are selected.
Using DISTINCT can slow down queries on large tables because it needs to check for duplicates.
Summary
DISTINCT helps you find unique values by removing duplicates.
It works on one or more columns in your SELECT statement.
Use DISTINCT when you want to see only different entries, not repeats.