MySQL DISTINCT usage
How to use the distinct keyword in MySQL to eliminate duplicated values in the result list of a select statement.
Tutorial info:
| Name: | MySQL DISTINCT usage |
| Total steps: | 1 |
| Category: | MySQL |
| Date: | 2010-11-10 |
| Level: | Beginner |
| Product: | See complete product |
| Viewed: | 6166 |
Bookmark MySQL DISTINCT usage
Step 1 - MySQL DISTINCT explained
MySQL DISTINCT usage
In cases you want to eliminate duplicate values in the result list of a SELECT statement you can use the DISTINCT keyword. Simple put the DISTINCT before the column name.
The syntax is:
Let’s see a simple example where we have a list of cars. Every car has an id, brand, type and color but now we just simply list all brands:
As you can see the brands displayed several times. However what we want is to know how many different brands are in the db. To get this extend the query as follows:
What if if you also want to know how many times the different brands occur in the table. To do this we need to use a bit different approach using COUNT() and GROUP BY as you can see in this example:
SELECT brand, COUNT(brand) FROM car GROUP BY brand;
And the result is:
brand count(brand)
Audi 3BMW 2Lexus 2
Tags: mysql distinct, remove duplicates, group by, unique values, distinct values
| MySQL DISTINCT usage - Table of contents |
|---|
| Step 1 - MySQL DISTINCT explained |