Reputation: 2119
I have a table that contains multiple ID fields like so:
work_id TEXT DEFAULT NULL,
card_id TEXT DEFAULT NULL,
employee_id TEXT DEFAULT NULL,
school_id TEXT DEFAULT NULL
And I need to find the rows where all of these fields match exactly. My initial syntax for this comparison would be:
SELECT * FROM table
WHERE
work_id = card_id AND
work_id = employee_id AND
work_id = school_id;
Conversely, I also need to find the rows where all of these fields do not match exactly. My initial syntax for this comparison would be:
SELECT * FROM table
WHERE
work_id NOT = card_id OR
work_id NOT = employee_id OR
work_id NOT = school_id;
Is there an easier way to do this comparison across more than two columns at a time? Is there some sort of array operator that will find matching or non-matching values across multiple columns?
I ask this because if the number of columns being compared is high, this type of code could prove unwieldly and hard to maintain down the road. For example, if later on, we add another ID column to the table, I would need to manually add a new line to the comparison logic to include the new column.
Upvotes: 1
Views: 2284
Reputation:
You can use ANY or ALL with an array
SELECT *
FROM the_table
WHERE work_id = all (array[card_id, employee_id, school_id])
SELECT *
FROM the_table
WHERE work_id <> any (array[card_id, employee_id, school_id])
Upvotes: 1
Reputation: 246163
You could use composite values:
WHERE (work_id, work_id, work_id) <>
(card_id, employee_id, school_id)
Upvotes: 0