Wildcard for a column name in the WHERE clause of a SELECT statement?

Is it possible to have a wildcard in a column name specified in the WHERE clause? I want to select something but only if a bunch of columns match a certain value (1 in this case). For example:

SELECT COUNT(id) FROM records WHERE *_check = 1

I have a bunch of columns that have _check as the suffix and it would be really nice to use something similar to the above code (which doesn't work).

Asked By: Aaron
||

Answer #1:

You could query the information_schema to get the columns in one query

SELECT column_name FROM information_schema.columns
WHERE table_schema = 'foo'
 AND table_name = 'bar'
 AND column_name LIKE '%_check'

and build your query from the result (pseudo code)

query = "SELECT COUNT(id) FROM records WHERE ";

foreach columName in columnNames
   query = query + " " + column_name + " = 1 OR "
next

query = TrimLastOr(query);

But I wouldn't recommend that because mysql information_schema query have a poor performance since they read from disk for every query.

Better: Use a view that returns

SELECT id FROM records WHERE col1_check=1 or col2_check=2 ...

so you can use it in your logic on multiple places, and only have to update the view if you add another _check column.

Answered By: Jürgen Steinblock

Answer #2:

No.

If you want to do something like this, you need the equivalent of dynamic SQL.

Answered By: Gordon Linoff
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles