How to Use the SELECT DISTINCT Statement in MySQL

08/04/2021

Contents

In this article, you will learn how to use the SELECT DISTINCT statement in MySQL.

Using the SELECT DISTINCT statement in MySQL

The SELECT DISTINCT statement in MySQL is used to retrieve unique values from a column or a set of columns in a table.

Syntax

The basic syntax of the SELECT DISTINCT statement in MySQL is as follows:

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

In this syntax, “column1, column2, …” refers to one or more columns from the table that we want to retrieve unique values from. The DISTINCT keyword is used to eliminate duplicate rows from the result set.

Examples

Suppose we have a table called “customers” with columns “id”, “name”, and “city”. We want to retrieve a list of all cities where we have customers.

SELECT DISTINCT city
FROM customers;

In this example, we are selecting only the “city” column from the “customers” table and using the DISTINCT keyword to eliminate duplicate city names from the result set.

And suppose we have a table called “orders” with columns “id”, “customer_id”, and “order_date”. We want to retrieve a list of all customers who have placed an order.

SELECT DISTINCT customer_id
FROM orders;

In this example, we are selecting only the “customer_id” column from the “orders” table and using the DISTINCT keyword to eliminate duplicate customer IDs from the result set.

And suppose we have a table called “products” with columns “id”, “name”, “category”, and “price”. We want to retrieve a list of all categories of products that we sell.

SELECT DISTINCT category
FROM products;

In this example, we are selecting only the “category” column from the “products” table and using the DISTINCT keyword to eliminate duplicate category names from the result set.

Using multiple columns

The SELECT DISTINCT statement can also be used to retrieve unique combinations of values from multiple columns in a table. Here is an example:

SELECT DISTINCT column1, column2
FROM table_name;

In this syntax, “column1” and “column2” refer to two columns from the table that we want to retrieve unique combinations of values from.

Performance considerations

The SELECT DISTINCT statement can have a significant impact on the performance of a query, especially if the table being queried has a large number of rows. It is generally recommended to use the GROUP BY clause instead of the SELECT DISTINCT statement if possible, as the GROUP BY clause can often be more efficient.