EN VI

MySQL: ignore WHERE clause if column does not exist?

2024-03-15 01:30:04
MySQL: ignore WHERE clause if column does not exist

I have a query which I need to run on different tables. In some of these tables the column country exists, in others not.
The query is: SELECT * FROM students WHERE name = '$name' AND country = '$country'

Is there a way to write the query so that the AND country = '$country' part is ignored if the country column does not exist?

Solution:

Not in straight SQL. If you are sending the SQL query from another programming language, you can selectively add the condition to the query based on the table definition. You can either hard-code the table definition in the program, or get it by querying the database for the table definition.

Hell, if that's the only thing changing the query, you could just have a list of table names with a boolean flag indicating if the country column is present.

(There is a solution to this problem in straight SQL, but it's extremely janky and therefore not recommended. It involves querying information_schema.tables, generating the SQL statements in a file, and then running the file. Very, very not recommended.)

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login