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.
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.
WHERE
clause if you want to filter job titles by department or location.SELECT DISTINCT job_title FROM employees WHERE department = 'Engineering';
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.
DISTINCT
with the COUNT
function: SELECT COUNT(DISTINCT customer_location) FROM orders;
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.
GROUP BY
clause: SELECT category, COUNT(*) FROM products GROUP BY category;
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.