MySQL DISTINCT
In MySQL, the DISTINCT clause is used with the SELECT statement to retrieve the unique records from the result set.
Syntax:
SELECT DISTINCT expressions FROM tables WHERE conditions;
Parameters:
expressions: It is used to specify the columns to be selected.
table_name: It is used to specify the name of the table from which the data needs to be retrieved.
conditions: It is used to specify the conditions to be strictly fulfilled for the selection.
Example 1: Using Distinct Select for a single column. Items table:
| ID | NAME | QUANTITY |
| 1 | Electronics | 30 |
| 2 | Sports | 45 |
| 3 | Fashion | 50 |
| 4 | Grocery | 30 |
| 5 | Toys | 50 |
Distinct Select Query:
SELECT DISTINCT quantity FROM items;
Output:
QUANTITY 30 45 50
Explanation:
The ‘items’ is an already existing table from which we are fetching the unique quantity of the items.
Example 2: Using Distinct Select for multiple columns. Items table:
| ID | NAME | QUANTITY |
| 1 | Electronics | 30 |
| 2 | Sports | 45 |
| 3 | Fashion | 50 |
| 4 | Grocery | 30 |
| 5 | Toys | 50 |
Distinct Select Query:
SELECT DISTINCT name, quantity FROM items;
Output:
| NAME | QUANTITY |
| Electronics | 30 |
| Sports | 45 |
| Fashion | 50 |
| Grocery | 30 |
| Toys | 50 |
Explanation:
The ‘items’ is an already existing table from which we are fetching the unique name and quantity of the items.