SQL DISTINCT Keyword Examples Explained

Explore practical examples of the SQL DISTINCT keyword to enhance your database queries.
By Jamie

Understanding the SQL DISTINCT Keyword

The SQL DISTINCT keyword is used to return unique values from a database query. It helps eliminate duplicate records in the result set, ensuring that each entry is represented only once. This is particularly useful when you want to analyze data without redundancy, making it a fundamental component in effective SQL querying. Below are three diverse and practical examples that showcase its usage in different contexts.

Example 1: Retrieve Unique Job Titles

Context

In a company database, you may want to see all the unique job titles held by employees to understand the diversity of roles within the organization.

SELECT DISTINCT job_title 
FROM employees;

This query selects all unique job titles from the employees table. If the table contains multiple entries for the same job title, such as “Software Engineer” appearing several times, this query will return each job title only once.

Notes

  • You can add conditions to the query using the WHERE clause if you want to filter job titles by department or location.
  • Example: SELECT DISTINCT job_title FROM employees WHERE department = 'Engineering';

Example 2: Unique Customer Locations

Context

When analyzing customer data, you may want to find out all the unique locations from where customers have placed orders. This can be useful for marketing and logistics planning.

SELECT DISTINCT customer_location 
FROM orders;

In this case, the query will return a list of unique customer locations from the orders table, helping you identify where your customers are based without any duplicates.

Notes

  • If you want to count the number of unique locations, you can combine DISTINCT with the COUNT function: SELECT COUNT(DISTINCT customer_location) FROM orders;

Example 3: Unique Product Categories

Context

In an e-commerce database, you may want to analyze the different categories of products available without counting how many products exist in each category. This helps in inventory management and marketing strategies.

SELECT DISTINCT category 
FROM products;

This query retrieves all unique categories from the products table. Each category will be listed only once, regardless of how many products belong to it.

Notes

  • To see the unique product categories along with their respective counts, you can use the GROUP BY clause: SELECT category, COUNT(*) FROM products GROUP BY category;

Conclusion

The SQL DISTINCT keyword is a powerful tool for ensuring data integrity and clarity in your results. By using these examples of SQL DISTINCT keyword example, you’ll be better equipped to handle data queries effectively in various contexts.