Skip to content
Advertisement

Multi conditional if statement in SQL query

I have a long list of names formatted like below. A person may have a few different representations of their name in the table (e.g. ‘Smith, Tom’ vs ‘Tom Smith’).

A query will come through using a like search (e.g. "SELECT * FROM table WHERE person_name LIKE "%smith%").

If a person has the boolean field is_display checked as true I want only the row with is_display set to true, if the person ID does not have an is_display checked off, I then want to fall back on the is_preferred field.

So ideally, a search for “smith” would only return rows 1 and 4.

I’ve looked into SQL if / else and CASE statements, but haven’t found a command that works for this need yet.

Right the closest I’ve gotten is:

Then I massage the results in code after SQL. But I imagine there’s a much more elegant way to do this only in SQL.

Advertisement

Answer

You seem to want a prioritization by person.

In MySQL 8+, this would look like:

In earlier versions, you can use a correlated subquery:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement