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


-- Find all customers whose names start with 'A'.
SELECT customer_name
FROM Customers
WHERE customer_name LIKE 'A%';

-- Find all products containing the word 'Laptop'.
SELECT product_name
FROM Products
WHERE product_name LIKE '%Laptop%';

-- Find all customers whose names have exactly 5 characters.
SELECT customer_name
FROM Customers
WHERE customer_name LIKE '_____';

-- Find all products whose names contain a space.
SELECT product_name
FROM Products
WHERE product_name LIKE '% %';

-- Find all products whose names start with 'T' and have exactly 7 characters.
SELECT product_name
FROM Products
WHERE product_name LIKE 'T_____';

Common Mistakes

Want to learn about other SQL terms?