Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL SELECT a field as NULL if not existent in table

Tags:

mysql

I like to use a SELECT on a table that maybe contains some field, but maybe not. If not, the value could be returned as NULL like JOIN LEFT would do for not existing rows.

Eg. something like this Pseudo-SQL:

SELECT id, email IF EXISTS, name, address FROM users;

should run without errors on a table 'users' without an 'email' field but return email=NULL then.

like image 442
dronus Avatar asked Jan 30 '12 11:01

dronus


People also ask

How do I select only NULL values in MySQL?

To search for column values that are NULL , you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression: mysql> SELECT * FROM my_table WHERE phone = NULL; To look for NULL values, you must use the IS NULL test.

How do I check if a field is empty in MySQL?

The IS NULL operator is used to test for empty values (NULL values).

How do you set a field to NULL in MySQL workbench?

In MySQL Workbench, right click on the cell and select 'Set Field to NULL'. In MySQL Workbench this setting is now called Set Field(s) to NULL , and is the first option in the list.

How do I select non NULL values in MySQL?

Example - With SELECT Statement Here is an example of how to use the MySQL IS NOT NULL condition in a SELECT statement: SELECT * FROM contacts WHERE last_name IS NOT NULL; This MySQL IS NOT NULL example will return all records from the contacts table where the last_name does not contain a null value.


1 Answers

What you want can not be done in pure SQL.

Essentially, you want SQL that can conditionally select a column that might not exist. Such SQL could not be parsed - all columns selected must exist or the query will be invalid.

You can however achieve this is application code by querying the catalog tables to inspect the schema of the database you're connected to and dynamically build you SQL based on that.

This query may help your app code to build your query:

select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'users'
and TABLE_SCHEMA = 'YOUR-DB-NAME';
like image 83
Bohemian Avatar answered Sep 28 '22 04:09

Bohemian