snippetsqlCritical
How to select specific rows if a column exists or all rows if a column doesn't
Viewed 0 times
rowshowcolumnexistsalldoesnspecificselect
Problem
I'm writing a script that gets a count of rows for a few tables, however for some tables I want to only get a count of rows where a flag is set (in this case active=1). Is there a way I can do this in one query?
Eg:
Table
Table
I want to get a count of users where active=1 and just get a count of clients.
Before you say "just hard code it" this is a query that's going inside a python script that could be run on numerous different databases and I have no way of knowing what tables my script will be selecting and if they have a column called
Eg:
Table
users has a column called activeTable
clients does not have a column called activeI want to get a count of users where active=1 and just get a count of clients.
Before you say "just hard code it" this is a query that's going inside a python script that could be run on numerous different databases and I have no way of knowing what tables my script will be selecting and if they have a column called
active, and I would prefer to have just one query to do it all instead of two separate ones and relying on mysql to throw an error so I know to use the other one.Solution
My first thought would be to use the
There is one other, tricky way though that works no matter if the table has or not such a column:
Tested at SQL-Fiddle How it works?
If the table has a column named
If the table doesn't have a column named
INFORMATION_SCHEMA first, so you get to know (in one query for all tables in the MySQL instance) which tables have an active column and then use that info to construct your queries. And this is probably the most sane approach.There is one other, tricky way though that works no matter if the table has or not such a column:
SELECT
( SELECT COUNT(*)
FROM TableName AS t
WHERE active = 1
) AS cnt
FROM
( SELECT 1 AS active
) AS dummy ;Tested at SQL-Fiddle How it works?
If the table has a column named
active, the query is "translated" as if it had:WHERE t.active = 1If the table doesn't have a column named
active, the query is "translated" as if it had:WHERE dummy.active = 1 -- which is trueCode Snippets
SELECT
( SELECT COUNT(*)
FROM TableName AS t
WHERE active = 1
) AS cnt
FROM
( SELECT 1 AS active
) AS dummy ;WHERE t.active = 1WHERE dummy.active = 1 -- which is trueContext
StackExchange Database Administrators Q#44871, answer score: 53
Revisions (0)
No revisions yet.