Is there a way to write an OR condition so that the second criteria is only checked if the first criteria yields no results?
For example:
CREATE TABLE some_table (
column_a VARCHAR(10),
column_b VARCHAR(10));
INSERT INTO some_table
VALUES ('A1', 'B1'), ('A2', 'B2');
I'd want this query to return only row with A1, B1, because it found a match using the first criteria:
SELECT * FROM some_table
WHERE column_a = 'A1' OR column_b = 'B2';
I'd want this query to return only row with A2, B2, because there was no match on the first criteria:
SELECT * FROM some_table
WHERE column_a = 'X1' OR column_b = 'B2';
Or perhaps there's a solution that doesnt use the OR operator?
I know you can execute multiple queries like in this example, but that's not ideal when the queries are much larger.
Another possible solution might be to use dynamic SQL, so you can store the majority of the query (without the second or criteria) as a variable execute it, and if no results, append the OR criteria and execute it again. This would prevent duplication of code in larger queries, but I'm sure there must be a better solution.
The
wherepredicate clause is correctly phrased withOR. If you want just one row in the resultset, we canorder bya conditional expression that puts first rows that match the first condition, thenlimit:If there might be several rows matching on a given criteria, then you might want to add another column to the
ORDER BYclause to make the sort predictable, say primary key columnid:Alternatively, if you want to retain all rows that match the given criteria, then you use window functions and
fetchinstead: