How to Use SELECT DISTINCT in SQL
Are you looking to learn how to use the SELECT DISTINCT statement in SQL? If so, you’re in the right place!
The SELECT DISTINCT statement is a useful tool in SQL that allows you to filter out duplicate rows in your query results. This can be especially helpful when working with large data sets or tables with many columns, as it can help you quickly and easily identify unique values and eliminate unnecessary or redundant information.
The good news is that the DISTINCT keyword is part of the ANSI SQL standard. As such, it will work the same way in any database platform you choose – Microsoft SQL Server, MySQL, PostgreSQL, or others.
Use SELECT DISTINCT in SQL to Get Unique Values
To use the SELECT DISTINCT statement, you simply need to include it in your SELECT statement, followed by the name of the column(s) you want to filter on. For example:
SELECT DISTINCT column_name
FROM table_name;
You can also use SELECT DISTINCT with multiple columns. For example:
SELECT DISTINCT column_name_1, column_name_2
FROM table_name;
This will return all unique combinations of values in column_name_1 and column_name_2.
It’s important to note that the SELECT DISTINCT statement only filters out duplicate rows based on the column(s) specified in the SELECT clause. If a row has duplicate values in other columns, it will still be included in the results.
For example, consider the following table:
ID | Name | Age |
---|---|---|
1 | John | 30 |
2 | Mary | 25 |
3 | John | 35 |
4 | Sarah | 25 |
If we run the following query:
SELECT DISTINCT Name
FROM table_name;
We would get the following results:
Name |
---|
John |
Mary |
Sarah |
However, if we run the following query:
SELECT DISTINCT Age
FROM table_name;
We would get the following results:
Age |
---|
30 |
25 |
35 |
As you can see, the SELECT DISTINCT statement only filters out rows with duplicate values in the specified column(s).
In summary, the SELECT DISTINCT statement is a useful tool for filtering out duplicate rows in your query results. By including it in your SELECT statement and specifying the column(s) you want to filter on, you can quickly and easily identify unique values and eliminate unnecessary or redundant information.
Want to learn more about SQL? Our Beginner SQL Guide will help you get started.