I asked a question yesterday and one answer is making me think about performance.
Resuming, I have a table which represents a parenthood relationship:
PARENT | CHILD
1 | 2
1 | 3
2 | 4
Both fields are numbers that represents one person.
I was needing to take the group of distinct persons of this table, not importing if child or parent. The query that came first in my mind was the most obvious one:
SELECT DISTINCT PARENT FROM TABLE1
UNION SELECT DISTINCT CHILD FROM TABLE1
But the one bellow seems to perform much better (in my real data at least):
SELECT DISTINCT CASE WHEN N.n=1 THEN parent ELSE child END
FROM TABLE1
CROSS APPLY(SELECT 1 UNION SELECT 2)N(n)
My questions are:
- Is this second query really faster than the first I built always?
- Just for curious, is there a faster way to do it?