Skip to content
Advertisement

Is order preserved after UNION in PostgreSQL?

Here is the code:

As you can see the recursive code gives the result in right order, but the non-recursive code does not.
They both use union, why the difference?

Advertisement

Answer

Basically, your query is incorrect to begin with. Use UNION ALL, not UNION or you would incorrectly remove duplicate entries. (There is nothing to say the trail cannot switch back and forth between the same emails.)

The Postgres implementation for UNION ALL returns values in the sequence as appended – as long as you do not add ORDER BY at the end or do anything else with the result.
Be aware though, that each SELECT returns rows in arbitrary order unless ORDER BY is appended. There is no natural order in tables.

The same is not true for UNION, which has to process all rows to remove possible duplicates. There are various ways to determine duplicates, the resulting order of rows depends on the chosen algorithm and is implementation-dependent and completely unreliable – unless, again, ORDER BY is appended.

So use instead:

To get a reliable sort order, and “simulate the record of growth”, you can track levels like this:

db<>fiddle here
Old sqlfiddle

Aside: if old_email is not defined UNIQUE in some way, you can get multiple trails. You would need a unique column (or combination of columns) to keep it unambiguous. If all else fails you can (ab-)use the internal tuple ID ctid for the purpose of telling trails apart. But you should rather use your own columns. (Added example in the fiddle.)

Consider:

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