Given the following db structure:
Regions
id | name |
---|---|
1 | EU |
2 | US |
3 | SEA |
Customers:
id | name | region |
---|---|---|
1 | peter | 1 |
2 | henry | 1 |
3 | john | 2 |
There is also a PL/pgSQL function in place, defined as sendShipment()
which takes (among other things) a sender and a receiver customer ID.
There is a business constraint around this which requires us to verify that both sender and receiver sit in the same region - and we need to do this as part of sendShipment()
. So from within this function, we need to query the customer table for both the sender and receiver ID and verify that both their region ID is identical. We will also need to ID itself for further processing down the line.
So maybe something like this:
SELECT DISTINCT region FROM customers WHERE id IN (?, ?)
The problem with this is that the result will be either an array (if the customers are not within the same region) or a single value.
Is there are more elegant way of solving this constraint? I was thinking of SELECT INTO
and use a temporary table, or I could SELECT COUNT(DISTINCT region)
and then do another SELECT
for the actual value if the count is less than 2, but I'd like to avoid the performance hit if possible.