I have two result sets:
rs1
:
id name
serial text
________________
1 Nick
....................
1233112 Pete
rs2
:
id name
serial text
________________
123121 Mike
....................
221233112 Junior
If we write a query:
SELECT *
FROM
(
SELECT *
FROM rs1
UNION ALL
SELECT *
FROM rs2
) as rs
OFFSET 100000 LIMIT 10;
How the result of the query computed? What algorithm is going to be used?
I believe that the server performs lazy evaluation in the sense of not loading the entire union, iterating over it and then returning the required result.
I would be glad if you described algorithms using in other SQL servers as an addition.
UPD: I'm quite new in database internals and don't know if it's possible to ask the sql-server itself about the exectuin plan of the query.
Here is a query plan:
"Limit (cost=77.11..77.88 rows=10 width=522)"
" -> Append (cost=0.00..140.18 rows=1818 width=522)"
" -> Seq Scan on tbl (cost=0.00..70.09 rows=909 width=522)"
" -> Seq Scan on tbl tbl_1 (cost=0.00..70.09 rows=909 width=522)"
The saqme query with order by id:
"Limit (cost=33.16..36.42 rows=10 width=522)"
" -> Merge Append (cost=0.56..593.16 rows=1818 width=522)"
" Sort Key: tbl.id"
" -> Index Scan Backward using pk_tabl on tbl (cost=0.28..285.21 rows=909 width=522)"
" -> Index Scan Backward using pk_tbl on tbl tbl_1 (cost=0.28..285.21 rows=909 width=522)"