Home > Database > Mysql Tutorial > How to Get Unique Records in SQL Using DISTINCT?

How to Get Unique Records in SQL Using DISTINCT?

Patricia Arquette
Release: 2025-01-14 14:57:43
Original
635 people have browsed it

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>
Copy after login

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>
Copy after login

This would yield a table resembling:

<code>╔══════════╦═════════╗
║   item1   ║   data1  ║
╠══════════╬═════════╣
║ item1     ║ data1    ║
║ item2     ║ data3    ║
║ item3     ║ data4    ║
╚══════════╩═════════╝</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template