select unique sql

Galaxy Glossary

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

The `DISTINCT` keyword in SQL is used to eliminate duplicate rows from a result set, returning only unique values for a specified column or set of columns. This is crucial for data analysis and reporting, ensuring accurate counts and summaries.
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

In SQL, retrieving unique data is a common task. Imagine you have a table of customer orders, and you want to see a list of all the unique products ordered. Using the `DISTINCT` keyword, you can easily achieve this. The `DISTINCT` keyword filters out duplicate rows, ensuring that each row in the result set is unique. This is particularly useful when you need to identify distinct categories, values, or combinations of values within your data. For example, you might want to find the unique cities where your customers reside or the unique product types sold. The `DISTINCT` keyword is a fundamental tool for data analysis and reporting, ensuring that your results are accurate and reliable. It's important to note that `DISTINCT` operates on the entire row, not just a single column. If you want to select unique values from a specific column, you specify that column in the `SELECT` statement. This ensures that only the unique values from that column are returned.

Why select unique sql is important

The `DISTINCT` keyword is essential for accurate data analysis and reporting. It ensures that results are not skewed by duplicate entries, providing a clear picture of the unique values present in your data. This is crucial for tasks like calculating unique customer counts, identifying distinct product types, or generating accurate summaries.

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, 'Peter', 'Pan', 'New York'), (4, 'Alice', 'Wonderland', 'Los Angeles'); -- Query to retrieve unique cities SELECT DISTINCT City FROM Customers; ```

Common Mistakes

Want to learn about other SQL terms?