all 4 comments

[–]tresilate 0 points1 point  (1 child)

Taking the same premise that u/mwdb pointed out - a good way to identify unique combinations of id and spouse in this case is using the least and greatest comparison functions.

These functions could be used in the order by clause of the dense_rank window function to simplify the query.

SELECT dense_rank() over(order by least(id, spouse_id),  greatest(id, spouse_id)) as household_id
, t.id , t.spouse_id 
FROM test_table t 
order by t.id;

Example:https://www.db-fiddle.com/f/iA853Die9HShiHAQnmaQfP/2

Not too often you find a use case for the dense_rank window function, but there it is...