0
0
MySQLquery~5 mins

DISTINCT for unique values in MySQL

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 a product table.
When you want to count how many different cities appear in an address list.
When you want to avoid repeated entries in a report or dropdown menu.
Syntax
MySQL
SELECT DISTINCT column_name FROM table_name;
DISTINCT applies to all columns listed after SELECT.
It removes duplicate rows based on the selected columns.
Examples
Gets a list of unique countries from the customers table.
MySQL
SELECT DISTINCT country FROM customers;
Gets unique combinations of product names and categories.
MySQL
SELECT DISTINCT product_name, category FROM products;
Lists all different cities from the addresses table.
MySQL
SELECT DISTINCT city FROM addresses;
Sample Program
This creates a table of employees with departments, inserts some data with duplicates, then selects unique departments.
MySQL
CREATE TABLE employees (id INT, department VARCHAR(20));
INSERT INTO employees VALUES (1, 'Sales'), (2, 'HR'), (3, 'Sales'), (4, 'IT'), (5, 'HR');
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 it when you want clean lists without repeated entries.