3

I have two database columns in a mysql database, A and B. In a select query, I want to implement this logic:

Select the rows where A is 'X'. If A is not set in a row, then check and select the row only if column B='Y'.

So one can say that column B is a fallback for column A.

How could I construct a SELECT query with 'X' and 'Y' as inputs for the WHERE clause?

3 Answers 3

7

Use boolean logic:

SELECT *
FROM table
WHERE A = 'X' OR (A IS NULL AND B = 'Y')
Sign up to request clarification or add additional context in comments.

2 Comments

I have a question on this solution. This query will return both A and B (because of 'SELECT *') and maybe one of them will be null. Is there a way NOT to return A in case it is null?
@frabala If you have a question you should ask using the "Ask Question" link up at the top, it'll get you a lot more responses than a comment on an old answer from last year :)
2

I think this should work:

SELECT * FROM table
WHERE (A='X') OR ((A IS NULL) AND (B='Y'))

Comments

2

SELECT * FROM table WHERE A='X' OR (A IS NULL AND B='Y')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.