SQL DISTINCT: Simplify Your Queries

DbVisualizerDbVisualizer
2 min read

SQL DISTINCT is a simple yet powerful keyword for filtering unique data in your database queries. Here’s a quick guide with examples to help you understand its application in different scenarios.

Unique cities list

If you have a table of orders and want to find the unique cities where customers are located, you can use the DISTINCT keyword. The query below demonstrates how to achieve this.

SELECT DISTINCT city 
FROM orders;

Combining multiple columns

In scenarios where you need unique combinations across multiple fields, such as customer names, cities, and the products they ordered, the following query is helpful.

SELECT DISTINCT customername, city, product 
FROM orders;

Count unique entries

To perform calculations on unique values, you can combine DISTINCT with aggregate functions. For example, the query below counts unique customers for each city.

SELECT city, COUNT(DISTINCT customername) AS UniqueCustomersCount
FROM orders
GROUP BY city;

Conditional DISTINCT queries

Using DISTINCT with a WHERE clause allows for more precise filtering. For instance, to list unique customers in New York, along with their contact details, use this query.

SELECT DISTINCT customername, address, phone
FROM orders
WHERE city = 'New York';

FAQ

What does DISTINCT do in SQL?

It removes duplicate rows, ensuring only unique values appear in the result.

How is DISTINCT applied?

Use DISTINCT after SELECT, followed by column names to filter duplicates.

Is DISTINCT the same as UNIQUE?

No, DISTINCT filters query results, while UNIQUE enforces unique entries in a table.

Can DISTINCT combine with WHERE?

Yes, it works with WHERE and other clauses for filtered results.

Conclusion

SQL DISTINCT is a powerful yet easy-to-use tool for cleaning up query results and focusing on unique data points. By integrating it into your database work, you can ensure higher data accuracy and relevance. Dive into the full guide for more practical examples and tips SQL DISTINCT: A Comprehensive Guide.

Whether you're a beginner or experienced, mastering these foundational tools enhances your data analysis skills.

0
Subscribe to my newsletter

Read articles from DbVisualizer directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

DbVisualizer
DbVisualizer

DbVisualizer is the database client with the highest user satisfaction. It is used for development, analytics, maintenance, and more, by database professionals all over the world. It connects to all popular databases and runs on Win, macOS & Linux.