A common pattern I still haven't solved is this: I have table A , and now I want to add table B and give it one row for each row in table A . Then I want to add a foreign key column to table A pointing at the row I just added. Of course this is easy to do with a loop, but can you do it all in pure SQL? If you have a solution I would love to see it. Here is my history of attempts: DROP TABLE IF EXISTS dogs; DROP TABLE…
This script works in SQL Server - I would think you could do the same in Postgres, but I'm not as familiar as I'd like to be with Postgres. Note that it does require 2 separate steps rather than 1 as you appear to desire, so may not work for you: IF OBJECT_ID('dbo.dogs', 'U') IS NOT NULL DROP TABLE dbo.dogs GO IF OBJECT_ID('dbo.doghouses', 'U') IS NOT NULL DROP TABLE dbo.doghouses GO CREATE TABLE dogs ( id INTEGER ID…
Modern SQL: With – Organize Complex Queries
61–63 of 63 posts
Yup, the OUTPUT keyword is the key to making this work. Before this was added to TSQL, the only way I knew of to make this work was by using a cursor and handling each record independently.
Re: Modern SQL: With – Organize Complex Queries
#62Earlier quoted context omitted.
If page numbers are important to you, then you have to find a different method anyway because of the drifting issue.
Or just accept that the page won't be exactly "right", but close. The solution proposed in the article doesn't have a "good enough" option for pages, as far as I can tell.
If you can use cursor-based pagination, then definitely do so—but as you point out, you can't always do that. Further, unless you're using bigserials (i.e. incrementing ints), you can't check $last_seen_ID either. With UUIDs (whether v4 or a custom impl.) there's no way to check `WHERE id > $last_seen_id`.
Re: Modern SQL: With – Organize Complex Queries
#63with has completely changed my usage of PostgreSQL. I am a newbie and being able to split queries into logical small steps with this has made SQL much more fun.
But don't you still get big long queries. Or can you make separate statements?
A long query written with CTEs is eminently more readable than the logically equivalent query written with nested sub-queries.
Just like a pipe operator makes long strings of function calls more readable than the semantically identical nested function calls.