In this SQL tutorial for beginners, you will learn about SQL SELECT DISTINCT
Statement with examples. The SQL SELECT DISTINCT
statement retrieves distinct values from a database table.
-- select the unique ages from the Customers table
SELECT DISTINCT age
FROM Customers;
Here, the SQL command selects only the unique values of age from the Customers table.
The syntax of the SQL DISTINCT
statement is:
SELECT DISTINCT column1, column2 ...
FROM table;
Here,
column1, column2, ...
are the table columnstable
is the table name from where we retrieve the distinct columnsFor example,
-- select the unique countries from the customers table
SELECT DISTINCT country
FROM Customers;
Here, the SQL command selects unique countries from the Customers table.
Example: Selecting unique countries
We can also use SELECT DISTINCT
with multiple columns.
For example,
-- select rows if the first name and country of a customer is unique
SELECT DISTINCT country, first_name
FROM Customers;
Here, the SQL command selects rows if the combination of country and first_name is unique.
Example: Selecting the unique combined fields
If we need to count the number of unique rows, we can use the COUNT()
function with DISTINCT
.
-- count the unique countries where customers are from
SELECT COUNT(DISTINCT country)
FROM Customers;
Here, the SQL command returns the count of unique countries.
Example: Counting unique countries
#sql