Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to test for null on all columns in a wildcard select?

Tags:

mysql

PSEUDO:

select * from foo where [every column is not null]

Is there a way to do this without specifying the actual column names?

like image 857
Yevgeny Simkin Avatar asked Jul 01 '13 17:07

Yevgeny Simkin


1 Answers

A possible solution that I can think of involves using dynamic-SQL

SELECT GROUP_CONCAT(column_name SEPARATOR ' IS NOT NULL AND ')
   INTO @sql
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE table_schema = SCHEMA()
   AND table_name = 'foo'
 GROUP BY table_name;

SET @sql = CONCAT('SELECT * FROM foo WHERE ', @sql, ' IS NOT NULL');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Here is SQLFiddle demo


Obviously it can be wrapped into a stored procedure with a parameter for a table name

DELIMITER $$
CREATE PROCEDURE sp_select_all_not_null(IN tbl_name VARCHAR(64))
BEGIN
  SELECT GROUP_CONCAT(column_name SEPARATOR ' IS NOT NULL AND ')
     INTO @sql
    FROM INFORMATION_SCHEMA.COLUMNS
   WHERE table_schema = SCHEMA()
     AND table_name = tbl_name
   GROUP BY table_name;

  SET @sql = CONCAT('SELECT * FROM ', tbl_name, ' WHERE ', @sql, ' IS NOT NULL');

  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END
DELIMITER ;

And then use it

CALL sp_select_all_not_null('foo');

Here is SQLFiddle demo for that

like image 121
peterm Avatar answered Oct 17 '22 00:10

peterm