DISTINCT - (MySQL Clauses)
In MySQL, the DISTINCT keyword is used to retrieve unique values from a table column. In this tutorial, we will discuss the syntax, example, output, explanation, use, important points, and summary of the DISTINCT keyword in MySQL.
Syntax
The basic syntax for using DISTINCT keyword is as follows:
SELECT DISTINCT column_name(s)
FROM table_name;
Here, column_name(s)
refers to the column or columns from which you want to retrieve unique values. table_name
refers to the name of the table from which you want to retrieve data.
Example
Let's say we have a table called employees
with the following data:
id | name | department |
---|---|---|
1 | John | HR |
2 | Jane | Finance |
3 | Sarah | IT |
4 | Peter | HR |
5 | Susan | Finance |
6 | Robert | IT |
If we want to retrieve the unique department values from this table, we can use the DISTINCT
keyword as follows:
SELECT DISTINCT department
FROM employees;
The output of this query will be:
department |
---|
HR |
Finance |
IT |
Explanation
In the example above, we used the DISTINCT
keyword to retrieve unique department values from the employees
table. By specifying the department
column in the SELECT
statement, we retrieved only unique values from that column.
Use
The DISTINCT
keyword is used to retrieve unique values from a table column. It can be used with the SELECT
statement to retrieve unique values from one or more columns. DISTINCT
is useful when you want to get a list of unique values from a table without duplicates.
Important Points
- The
DISTINCT
keyword applies to all columns specified in theSELECT
statement. DISTINCT
only returns unique values; it does not returnNULL
values.DISTINCT
affects the entire row, so if two rows differ by even one column value, they are considered distinct.
Summary
In this tutorial, we discussed the DISTINCT
keyword in MySQL. We covered the syntax, example, output, explanation, use, and important points of using DISTINCT
to retrieve unique values from a table column. With this knowledge, you can now use the DISTINCT
keyword in your MySQL queries to retrieve unique values and avoid duplicates in your results.