The DISTINCT statement is used in SQL to retrieve unique values from a table. This statement is often used in combination with the SELECT statement to eliminate duplicate values and retrieve a distinct set of data. In this article, we will discuss the basics of the DISTINCT statement and how it differs from a simple SELECT statement.
The basic syntax of the DISTINCT statement is as follows:
SELECT DISTINCT column1, column2, ... FROM table_name;
In the example above, we are retrieving unique values of two columns (column1 and column2) from a table named `table_name`. The `SELECT` keyword is followed by the `DISTINCT` keyword, which specifies that only unique values should be retrieved. The list of column names, separated by commas, follows the `DISTINCT` keyword. The `FROM` keyword is used to specify the name of the table that contains the data we want to retrieve.
Let’s say we have a table named `orders` with the following data:
If we use the following SELECT statement to retrieve the product names:
SELECT product FROM orders;
We will get the following result:
As you can see, there are duplicate values in the result. To eliminate these duplicates, we can use the DISTINCT statement as follows:
SELECT DISTINCT product FROM orders;
This will return the following result:
As you can see, the result now only contains unique values of the `product` column.
Difference between SELECT and SELECT DISTINCT
The main difference between a SELECT statement and a SELECT DISTINCT statement is that the latter only returns unique values, while the former can return duplicate values. This means that the SELECT DISTINCT statement can be used to retrieve a unique set of data, while the SELECT statement retrieves all data from the specified columns, regardless of duplicates. Additionally, the SELECT statement can be used to aggregate data, while the SELECT DISTINCT statement cannot be used to perform aggregations.
In conclusion, the DISTINCT statement is a powerful tool in SQL for retrieving unique values from a table. Whether you are looking to eliminate duplicates or simply retrieve a distinct set of data, the DISTINCT statement can help you achieve your goal. It is important to understand the difference between the SELECT statement and the SELECT DISTINCT statement in order to effectively utilize these statements in your SQL queries.