DISTINCT for Unique Results

Uses DISTINCT and DISTINCT ON to eliminate duplicate rows and select unique rows based on specific column ordering for data deduplication.

SqlData Fetching

Code

sqlsnippet
41 lines
-- Get unique cities where customers live
SELECT DISTINCT city, state, country
FROM customers
WHERE is_active = true
ORDER BY country, state, city;

-- DISTINCT ON: get one row per group (PostgreSQL specific)
-- Get the most recent order for each customer
SELECT DISTINCT ON (customer_id)
    customer_id,
    order_id,
    order_date,
    total_amount,
    status
FROM orders
WHERE status IN ('completed', 'shipped')
ORDER BY customer_id, order_date DESC;

-- Count unique values
SELECT
    COUNT(DISTINCT category_id) AS unique_categories,
    COUNT(DISTINCT supplier_id) AS unique_suppliers,
    COUNT(*) AS total_products
FROM products;

-- DISTINCT with multiple columns for unique combinations
SELECT DISTINCT
    p.category_id,
    p.supplier_id,
    COUNT(*) OVER (PARTITION BY p.category_id, p.supplier_id) AS combo_count
FROM products p
WHERE p.stock_quantity > 0
ORDER BY category_id, supplier_id;

-- Eliminate duplicates from a UNION
SELECT product_name FROM products
WHERE category_id = 1
UNION
SELECT product_name FROM discontinued_products
WHERE category_id = 1
ORDER BY product_name;

What the code does

The file runs SELECT statements, touching customers, orders, products and discontinued_products.

What the statements actually assemble: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows; a UNION stitching together the result sets of separate queries.

What to watch for

  • To filter on a window function’s result you need an outer query or CTE; the same-level WHERE runs too early.

Using it

Run the statement against the customers table.

Key statements

SELECT DISTINCT
    p.category_id,
    p.supplier_id,
    COUNT(*) OVER (PARTITION BY p.category_id, p.supplier_id) AS combo_count
FROM products p
WHERE p.stock_quantity > 0
ORDER BY category_id, supplier_id;
SELECT product_name FROM products
WHERE category_id = 1
UNION
SELECT product_name FROM discontinued_products
WHERE category_id = 1
ORDER BY product_name;
SELECT DISTINCT ON (customer_id)
    customer_id,
    order_id,
    order_date,
    total_amount,
    status
FROM orders
WHERE status IN ('completed', 'shipped')
ORDER BY customer_id, order_date DESC;

FAQ

Which tables appear in this script?
`customers`, `orders`, `products`, `discontinued_products`.