187 points · by rsecora · 3y ago · 70 comments
Here’s a cheat code, in case you need to write a database query and don’t remember all the fancy join tricks: Problems like this often have a very straightforward solution with subselects. In this case, the main select gets the departments, and a subselect (with limit 1) fetches the top employee for each department.
That’s a very natural, compositional way of thinking. Granted, it’s not the most optimized way to do it, but more often then not, the resulting query plan is perfectly fine.
Depending on the details, the query plan might be exactly the same. I remember once (in SQL Server 2000, so long time ago) writing the same query in 3 completely different ways, only to see the DB generate the same plan for each one.
It would surprise most people how sophisticated the query transformations databases can do.
More recently, I've found that mysql sometimes behaves poorly with subselects, so I tend to avoid them out of habit.
It usually is the exactly same. (MySQL has a potato for a query optimizer tho.)
The biggest case it is suboptimal is when you need to produce multiple fields from the sub-select. Because then you need multiple sub-selects.
The nice thing about lateral joins is that they're very easy to understand conceptually once you get over the weird syntax.
It would be nice to have this feature; its a handy hammer for the right type of nail.
I've discovered a small number of queries actual do become faster when switching a column to a subselect.
Why? You cannot access the row id or any values within the row as a return value unless the row changes. The top stackexchange answer goes into some detail about why you really don't want to simply make a dummy update in Postgres.
You can access these old row values in some scope for the no-update case, and this allows you to leverage CTEs instead of dummy updates. However… you can't use CTEs with prepared statements (and it's a non-obvious fail for the uninitiated). So yeah there are still lots of little sharp edges.
Fortunately the records are locked, so a second query will pick them up. Still sad tho.
Prepared statements work fine with CTEs.
Prepared statements work fine with CTEs.
My experience was that this was not the case. Basically the CTE was materialized and the variables were resolved as part of PREPARE, so each invocation got the same values. I couldn't find the blurb I'd read previously but I did a little digging today and it looks like maybe NOT MATERIALIZED would fix the problem?I've hit this many, many times. It's such a common need, and yet I keep having to write it out as multiple queries to "select row" and if no result, do then insert query.
This is often a smell, but it’s a little inflexible.
I also dislike that `ON CONFLICT ... DO NOTHING` increments numerical primary keys. I understand why it happens but it seems counter-intuitive given the name "DO NOTHING". (And, yes, relying on the values of primary keys to never change is an anti-pattern. However, if you have a table of 10 values and the primary keys have massive gaps like 1, 500_211, 2_521_241, 15_631_121, etc., it feels weird nonetheless.)
ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome; provided there is no independent error, one of those two outcomes is guaranteed, even under high concurrency. This is also known as UPSERT — “UPDATE or INSERT”.
https://www.postgresql.org/docs/current/sql-insert.html
What are you referring to?
That is annoying about sequences, I agree.
I've never needed that, and it's not clear why I would.
Like, my new record is a duplicate of record A according to one constraint and record B according to another constraint, so it updates both A and B?
One "upsert" but two resulting records?
Can someone fill me in on when this would crop up?
For example, let's say you're tracking GitHub repositories and have a table `repository(id, gh_id, gh_node_id, owner, name, description)` where `gh_id` and `gh_node_id` are both unique.
If you want to insert or update a repository you might want to do something like below, however, this is not a valid syntax and as you need to define a separate `DO UPDATE` for `gh_id` and `gh_node_id`:
INSERT INTO repository (gh_id, gh_node_id, owner, name, description)
VALUES (:id, :node_id, :owner, :name, :description)
ON CONFLICT DO UPDATE
SET name = excluded.name,
description = excluded.description;
------To my knowledge there's no way to define a single constraint `UNIQUE(gh_id || gh_node_id)` instead of `UNIQUE(gh_id && gh_node_id)`.
Theres very few cases where you shouldnt be doing a group by with aggregates instead. (window functions count here)
I’ve avoided ChatGTP until recently and at least for SQL refactoring, it’s great. The interesting part is the ranked example ChatCTP gave me was almost identical to the one in this post. I wonder if they’re (ChatGTP) is training up on technical blog posts.
It seems like eventually database automation is going be self-optimizing (more than the query planner already is).
Sure it is. As long as you're not storing any other information on the department in the employee table.
https://www.mssqltips.com/sqlservertip/5542/using-for-xml-pa...
https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions....
Bonnie Robertson is a thriving 10X support high earner