Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE all IS NOT NULL

Tags:

How can I run a MySQL query that selects everything that is not null? It would be something like

SELECT * FROM schedule WHERE ((all)) IS NOT NULL 

Do I just remove the all and go..?

SELECT * FROM schedule WHERE IS NOT NULL 
like image 386
Sam Avatar asked Jun 24 '10 08:06

Sam


People also ask

Where if value is not null?

You can easily check if a variable Is Null or Not Null in JavaScript by applying simple if-else condition to the given variable.

Where something is not null in SQL?

Description. The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

WHAT IS NOT NULL with example?

The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.


2 Answers

You'll have to explicitly state the condition on each column, so e.g.

SELECT * FROM schedule  WHERE id IS NOT NULL   AND foo IS NOT NULL   AND bar IS NOT NULL; -- and so on.. 
like image 124
nos Avatar answered Dec 15 '22 13:12

nos


You need to get a list of the columns of your table, by looking at the information_schema database.

Let's suppose that your database is called mydata and your table in question is named mytable. You can get the list of the table's nullable columns by issuing the following statement:

SELECT `COLUMN_NAME` FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA` = 'mydata'     AND `TABLE_NAME` = 'mytable'     AND `IS_NULLABLE` = 'YES' 

Our final query will look like this:

SELECT * FROM `mydata`.`mytable` WHERE CONCAT(<list of columns>) IS NOT NULL 

All we are missing now is the list of nullable columns, comma-separated. We're going to use the GROUP_CONCAT function to produce the final statement, which we will execute like this:

SET @query = CONCAT(     'SELECT * FROM `mydata`.`mytable` WHERE CONCAT(',     (SELECT GROUP_CONCAT(COLUMN_NAME)         FROM `information_schema`.`COLUMNS`         WHERE `TABLE_SCHEMA` = 'mydata' AND         `TABLE_NAME` = 'mytable'         AND `IS_NULLABLE` = 'YES'),     ') IS NOT NULL');  PREPARE stmt_name FROM @query;  EXECUTE stmt_name; 

References:

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html

like image 28
Anax Avatar answered Dec 15 '22 14:12

Anax