Home >Database >Mysql Tutorial >How to Get Unique Records in SQL Using DISTINCT?
Extracting Unique Data from SQL Tables
Working with large databases often involves dealing with duplicate entries. To efficiently retrieve only unique records, SQL offers the DISTINCT
keyword. This powerful function ensures you only receive one instance of each unique value combination.
For instance, if your table contains duplicate values in a column named "column2", you can use the following SQL query to obtain only the unique entries:
<code class="language-sql">SELECT DISTINCT column2, column3, ... FROM table_name;</code>
The DISTINCT
keyword, placed before the column names, instructs SQL to filter out duplicates, returning only the first occurrence of each unique combination of specified column values.
Let's consider a practical example. Given a table with redundant data, the query below will isolate unique records:
<code class="language-sql">SELECT DISTINCT item1, data1 FROM table_name;</code>
This would yield a table resembling:
<code>╔══════════╦═════════╗ ║ item1 ║ data1 ║ ╠══════════╬═════════╣ ║ item1 ║ data1 ║ ║ item2 ║ data3 ║ ║ item3 ║ data4 ║ ╚══════════╩═════════╝</code>
Observe that the duplicate "item1" entry has been eliminated, leaving only unique rows based on the specified columns. This demonstrates the effectiveness of DISTINCT
in retrieving clean, unique datasets from your SQL database.
The above is the detailed content of How to Get Unique Records in SQL Using DISTINCT?. For more information, please follow other related articles on the PHP Chinese website!