Group BY and COUNT in PostgreSQL
Here's the basic syntax to perform a GROUP BY
with COUNT
in PostgreSQL:
Here's an example where we count order statuses:
This will return the count of each unique status present in the orders
table.
Distinct Counts: Uniqueness in Focus
When you're interested in counting distinct values, you'll employ COUNT(DISTINCT column)
:
Here each status will correlate to the count of unique customers. It's like turning customers into snowflakes, each one unique!
Performance Tuning: Speedy Gonzales with Indexing
You can reduce query times significantly by creating an index on the columns often used in filtering or joining:
Consider this the Fast&Furious mode for your PostgreSQL queries.
Avoid Overdoing GROUP BY
: Because Moderation is Essential
Avoid resorting to GROUP BY
when you're simply counting distinct values. Use COUNT(DISTINCT)
instead, like:
That way the GROUP BY
clause takes a vacation, and we get cleaner, perhaps faster code!
Conditional Light Saber: Use the FILTER!
FILTER
clause lets you count rows where certain conditions are met:
Now we're wielding a light saber, nimbly slicing data to count refunded and completed orders for each status.
CTEs and Window Functions: Our Swiss Army Knife
CTEs help structure the query, while Window Functions allow COUNT
over a range of rows. They’re PostgreSQL’s Swiss Army knife.
Our SQL turned from a blunt blade to a poison-dipped tactical dagger, ranking orders within each status before counting.
EXISTS over Aggregate: The Quickening
Leverage EXISTS
when you're merely checking for presence rather than counting. It can be swifter:
This forms groups of orders that have at least one European customer. It's like picking out ripe fruits without actually counting them.
Was this article helpful?