Distinct on: a confusing, unique and useful feature in Postgres
yogeshchauhan.com
yogeshchauhan.com
e.g. this works in MySQL, and has for many years:
select a, b, c from table group by a
and you'll get undefined (but valid) b and c items from the grouped results per `a`. It's absurdly useful at times - if the non-grouped columns are just denormalized data, it doesn't matter which row they came from, and there's no need to spend time sorting/maxing/etc. And sometimes you truly don't care which entry you get, you just want an entry, e.g. to show a sample of what's in the group.More here: https://dev.mysql.com/doc/refman/8.0/en/group-by-handling.ht...
However...
(1) AFAIK it's not default in MySQL (version 5.7.5+). You have to disable ONLY_FULL_GROUP_BY to get this to work.
(2) Often you will care about which one is chosen. It would have been more useful if MySQL had let you influence this with ORDER BY.
(3) I create a current_value() aggregate which gives me even more flexibility than either approach for selecting the value.
SELECT a,
current_value(b ORDER BY x),
current_value(c ORDER BY x DESC)
FROM table GROUP BY aDo you have much experience with Postgres WINDOW[1] expressions? That might be a useful tool for you even if it takes a bit of time to fully grok it. I don't use WINDOW often but one place I found it was insanely useful was for supplying a tabular page with aggregate data points outside of the data currently being paged to the client - we have a query that returns row information in a paged manner but the query driving it both narrows the row scope to fit the page size request while also using WINDOW functions over the un-partitioned data to calculate a few business useful averages.
1. https://www.postgresql.org/docs/current/tutorial-window.html
PostgreSQL would have to do a separate sort for each different ORDER BY, yes.
Also, it can't use the the index to scan only some values as it could for DISTINCT ON, because the aggregate is opaque. That may or may not actually matter though.
Another option (though more verbose) is LATERAL plus LIMIT 1.
> Do you have much experience with Postgres WINDOW expressions?
Yes.
SELECT DISTINCT
a,
first_value(b) OVER (PARTITION BY a ORDER BY x),
first_value(c) OVER (PARTITION BY a ORDER BY x DESC)
FROM table
One downside is that I can't use FILTER with those as with aggregates, though sometimes you can hack something together with PARTITION/ORDER BY/RANGEMySQL has quite a few "impure" but useful features. Postgres pretty often comes up with a sane, predictable version some years later (which often does not perform quite as well, but I'll happily take that tradeoff).
Note: it would be theoretically trivial to actually normalize this schema, but sadly that’s beyond my remit. At first glance I can’t think of a scenario where I would choose this design pattern unless I was forced to work within similar constraints (which does happen all the time in the real world).
Maybe that'd be some help?
It’s a bit of a moot point for me in this case though, as I’m not allowed to make any DDL changes to this DB, I just have to produce periodic reports. Which is perhaps a bit of a contrived situation, but it’s absolutely not my first time dealing with it. In reality there’s other even more trivial solutions to this problem. It could be solved by adding a row to table A (or creating a new related table), and then adding an update to the code that inserts the transaction logs (or even just with a table trigger - though that’s a bit more spaghetti). That would be all that’s required to bring this schema (or at least this particular portion of it) in line with a normal form. This particular DB is a large component in a generally spaghttified architecture, that lots of stakeholders write to and consume data from, so over the years it’s grown too complex to reliably tolerate simple changes. I imagine constraints similar to these is what drives a lot of use for features like DISTINCT ON, where the more “correct” approach might just be to fix your schema.
select a, last(b), last(c) from table group by a
As it’s name implies, returns the last value that the aggregate encountered for the group. You can add an “order by” within the parenthesis to make it deterministic.https://www.postgresqltutorial.com/postgresql-last_value-fun...
So it would be:
select a, last_value(b) over(partition by a), last_value(c) over(partition by a) from table
Note the lack of a "GROUP BY" so this will result in duplicates unless you add a DISTINCT. select a, any_value(b), any_value(b) from table group by a
https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functi...do you know if it allows different row values for a and b though? (tbh I'm not sure if the old version did or did not, but I've never seen it return data blended from multiple rows...)
It also allows you to use multiple entities/expressions in the distinct on, so you can pivot the logic between granularity levels. Which comes in handy when needing to pull rollups latest/first/biggest/smallest style rollups from varying perspectives.
I would have liked to see equivalent queries written with GROUP BY so people could understand and translate that knowledge even if they don't have direct Postgres experience.
Thanks for the article!
SELECT DISTINCT ON (location) location, time, report
FROM weather_reports
ORDER BY location, time DESC;
could also be written with a self-join like so SELECT location, time, report
FROM weather_reports
JOIN (
SELECT location, max(time) AS time
FROM weather_reports
GROUP BY location
) as _ USING (location, time)
ORDER BY location;
though I'd be curious what the query-plan differences are. I suspect the DISTINCT ON might translate more closely to a lateral join SELECT
FROM (
SELECT DISTINCT(location)
FROM weather_reports
) AS locations
JOIN LATERAL (
SELECT location, time, report
FROM weather_reports
WHERE location = locations.location
ORDER BY ts DESC
LIMIT 1
) AS reports ON TRUE
ORDER BY location;
But I really can't say.And yes, the JOIN LATERAL would be a good substitute.
P.S. More concise is CROSS JOIN ... rather than JOIN ... ON TRUE
The main exception I’ve seen is when using it in a view, if you try to filter the results of the view, it usually can’t optimize a DISTINCT ON, but sometimes can for GROUP BY (though that might have improved on newer versions)
Nice!
Scroll a bit down here for a similar example.
https://stackoverflow.com/questions/11472790/postgres-analog...
https://sqlite.org/quirks.html#aggregate_queries_can_contain...
> if an aggregate query contains a single min() or max() function, then the values of columns used in the output are taken from the row where the min() or max() value was achieved. If two or more rows have the same min() or max() value, then the columns values will be chosen arbitrarily from one of those rows.
Also here:
https://sqlite.org/lang_select.html#bareagg
> When the min() or max() aggregate functions are used in an aggregate query, all bare columns in the result set take values from the input row which also contains the minimum or maximum. [...] There is still an ambiguity if two or more of the input rows have the same minimum or maximum value or if the query contains more than one min() and/or max() aggregate function.
Would have been nice if adding an ORDER BY would allow disambiguating.
The alternative would have been a lot less concise and would have required a much longer stored procedure.
Guess that's however true for any well written language when you master it enough to enjoy theses gems hidden in plain sight.
Back before PG and others were viable competitors to the big commercial databases, about the only leverage customers had against aggressive sales people was the threat to switch to a competitor. So people would preserve that as a credible threat by not using proprietary SQL extensions.
No vampiric salesdroid from Postgres is going to knock on your door demanding 8 figures.
Now, there may be other reasons you want to switch away from it, or you may want to support a variety of DBs in whatever you're building, or some other reason. So it is good to be aware of. But shying away from SQL extensions is usually no longer a matter of budgetary apocalypse.
1. Only because I hacked it in during my free-time since it is such a trivial dialect to support.