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?
2
Answers
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.)No.
All columns you reference in the query, even in conditional expressions, must exist in the tables you query.
An alternative solution is to write code to omit some column references from the query based on what you can discover about the table.
In other words, first check the metadata of the table, then format the query you want to run with or without the
country
column.Another solution would be to run the query including the reference to the
country
column, and if it returns an error, catch the error in your application, then try the query without the reference to thecountry
column.