select distinct sql

Galaxy Glossary

How do you retrieve unique rows from a table in SQL?

The `SELECT DISTINCT` clause in SQL is used to retrieve only unique rows from a table. It eliminates duplicate rows, returning each distinct combination of values in the specified columns. This is crucial for data analysis and reporting.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The `SELECT DISTINCT` clause is a powerful tool in SQL for filtering out duplicate rows from a result set. When you query a table, you might get multiple rows with identical values in certain columns. `SELECT DISTINCT` ensures that you only see one copy of each unique combination of values. This is particularly useful when you need to identify unique customers, products, or any other entity represented in your database. It's a fundamental part of data manipulation, enabling you to work with clean, non-redundant data. Imagine a table listing orders. Without `SELECT DISTINCT`, you might see multiple rows for the same customer's order. Using `SELECT DISTINCT` on the customer ID column would show you only one row per customer, simplifying analysis and reporting. It's important to note that `SELECT DISTINCT` considers all selected columns. If any column has a different value, it's considered a distinct row. For example, if you have two orders with the same customer ID but different order dates, `SELECT DISTINCT` will treat them as distinct rows.

Why select distinct sql is important

The `SELECT DISTINCT` clause is essential for data integrity and analysis. It helps to avoid redundant data, making queries more efficient and results easier to interpret. It's a fundamental tool for data cleaning and preparation, crucial for accurate reporting and decision-making.

Example Usage

```sql -- Sample table: Customers CREATE TABLE Customers ( CustomerID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50), City VARCHAR(50) ); INSERT INTO Customers (CustomerID, FirstName, LastName, City) VALUES (1, 'John', 'Doe', 'New York'), (2, 'Jane', 'Doe', 'Los Angeles'), (3, 'John', 'Smith', 'Chicago'), (4, 'Jane', 'Doe', 'Houston'); -- Query to retrieve distinct cities SELECT DISTINCT City FROM Customers; ```

Common Mistakes

Want to learn about other SQL terms?