// SQL snippet

Distribution of foreign-key values

Group child rows by parent, count them, and order descending: the top of the list is your skew, the tail is your long tail.

Main statement
PostgreSQL
También cubre
SQL Server

The task

One customer owns most of the orders and you want proof, plus the list of parents with suspiciously many children before a cascade or archive touches them.

The snippet

Written for PostgreSQL. Versions for SQL Server are under Variations.

PostgreSQL
SELECT c.id AS customer_id, c.email,
       COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.email
ORDER BY order_count DESC
LIMIT 20;

Cómo funciona

LEFT JOIN keeps zero-order customers in the census, with COUNT(o.id) returning 0 for them instead of dropping them. Grouping by the parent and ordering by the child count descending ranks the skew; LIMIT trims the head. The tail end of the same query (flip to ASC) shows dormant parents worth archiving.

Variations

SQL Server: TOP instead of LIMIT

SQL Server
SELECT TOP 20 c.id AS customer_id, c.email, COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.email
ORDER BY order_count DESC;

Skew summary: busiest customer and customers with no orders (LIMIT: PostgreSQL, MySQL, SQLite)

SELECT
  (SELECT COUNT(*) FROM orders WHERE customer_id = (
     SELECT customer_id FROM orders GROUP BY customer_id ORDER BY COUNT(*) DESC LIMIT 1
  )) AS top_customer_orders,
  (SELECT COUNT(*) FROM customers c
   WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)) AS customers_without_orders;

Questions that come up

Why LEFT JOIN here instead of an inner join?

With an inner join, parents whose children were all deleted vanish from the report, and those are exactly the rows an archiver needs to see. The LEFT JOIN plus COUNT(child.id) pattern reports them as zero, giving you the full distribution from empty parents to the hottest one.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.