Table
---------------------------------------------
| id | first_name | middle_name | last_name |
---------------------------------------------
| 1 | abc | | def |
---------------------------------------------
| 2 | | | xyz |
---------------------------------------------
| 3 | xyz | | |
---------------------------------------------
I want sql query which gives output as fields name which contains values and exclude fields which has empty value or null value.
like
id,
first_name,
last_name
First try, see fiddle for result:
http://sqlfiddle.com/#!2/b6d7b/7
To my best knowledge you can’t create MySQL queries which uses dynamically created table/field names. The query optimizer has to exactly know before actual execution what tables and fields will be used in the query, that’s why the above query contains manually written field names.
While you can create queries about database columns using
INFORMATION_SCHEMA, you can’t use the received column names for querying, unless if you generate the needed sql code with php code, stored procedure, etc.See http://dev.mysql.com/doc/refman/5.0/en/columns-table.html
If you wanted to find persons with ‘joh’ in their names, and the field names actually containing ‘joh’, you could use a similar query:
http://sqlfiddle.com/#!2/f2597/3
If you want every column name, where there is at least one NOT NULL value in that column, then try this query:
http://sqlfiddle.com/#!2/8dec7/5
It uses COUNT( expr ), which ( http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_count )
Returns a count of the number of non-NULL values of expr.