Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading