Skip to content
Advertisement

Merge two tables and chain id fields in order

I’m looking for a way to merge two tables (or more) and modify/order their numeric id. To put it simply here is what I want to do schematically :

Table example 1 :

Id Field
4 x
1 x
5 x
3 x
2 x

Table example 2 :

Id Field
1 x
3 x
5 x
2 x
4 x

Expected result (modify table 1 as 1-2-3-4-5 and table 2 as 6-7-8-9-10 THEN order both id by asc)

Id Field
1 x
2 x
3 x
4 x
5 x
6 x
7 x
8 x
9 x
10 x

I was aiming for a union tables nested in a select row_number() over (order by id) but I don’t really know how to modify table 2 as 6-7-8-9-10 before

Advertisement

Answer

Try using this example:

SELECT id, Field FROM t1
UNION ALL
SELECT (SELECT MAX(id) FROM t1) + ROW_NUMBER() OVER (ORDER BY id) AS id, Field
FROM t2
ORDER BY id

fiddle

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement