Using DISTINCT in SQL for Unique Record Selection
Standard SQL SELECT * FROM table
queries often return duplicate rows. To ensure data accuracy and efficient analysis, SQL provides the DISTINCT
keyword. This allows you to retrieve only unique values from specified columns.
Illustrative Example:
Consider this sample table:
<code>| Column1 | Column2 | Column3 | |---------|---------|---------| | 1 | item1 | data1 | | 2 | item1 | data2 | | 3 | item2 | data3 | | 4 | item3 | data4 |</code>
A SELECT *
query would return all rows, including duplicates based on Column2
.
To retrieve only unique rows, use the DISTINCT
keyword:
<code class="language-sql">SELECT DISTINCT Column1, Column2, Column3 FROM table;</code>
This produces the following result, eliminating the duplicate item1
entry:
Column1 | Column2 | Column3 |
---|---|---|
1 | item1 | data1 |
3 | item2 | data3 |
4 | item3 | data4 |
The DISTINCT
keyword is a powerful tool for data cleaning and ensuring the accuracy of your SQL queries. It guarantees that only unique combinations of the specified columns are returned.
The above is the detailed content of How Can DISTINCT in SQL Help Me Select Only Unique Records?. For more information, please follow other related articles on the PHP Chinese website!