The book is awesome, but I disagree with some parts.
The abuse of positional syntax in GROUP BY, IMO, is a code smell:
GROUP BY
1,
2,
3
It leads error-prone and unreadable code. The author's argument is that it's more applicable for complex expressions in SELECT that you don't want to repeat in GROUP BY.
The following example shows that's not true, bc you can use aliases in GROUP BY too:
with txs(id, amount) as (
values
(1, 100),
(2, 280),
(3, 100)
)
select
count(id) as count_id,
sum(amount) as sum_amount,
round(amount, -2) / 100 as bucket
from
txs
group by
bucket;
Another thing is bad examples of working with duplicates. The author shows a couple of techniques with GROUP BY and SELECT DISTINCT...
The proper Business Deduplication by row_number() is missing:
with customer(id, updated_ts) as (
values
(1, '2000-01-01'::date),
(1, '2000-01-02'::date),
(1, '2000-01-03'::date),
(1, '2000-01-04'::date),
(1, '2000-01-05'::date),
(2, '2000-01-05'::date)
),
ranked as (
select
*,
row_number() over (partition by id order by updated_ts desc) as rn
from
customer
)
-- Deduplicate.
select
'Most Recent' as kind,
*
from
ranked
where
rn = 1
union all
-- Show Duplicates.
select
'Duplicate',
*
from
ranked
where
1 < rn
;
It's much better, because:
1. You're able to easily select all the columns.
2. You're able to write complex deduplication logic compactly.
And another problem is abuse of subqueries which are less readable than CTEs. Subqueries lead to messy and hard to debug code.
Aside from that the book is awesome.