Is there a way to write an insert/update query that checks if a column allows NULLs: If it does set the column to NULL, and '' (empty string) otherwise?

I would be something like:

UPDATE mytable 
  • Would this work for you? UPDATE mytable SET field = ''; UPDATE mytable SET field = NULL; (the 2nd statement will not succeed if the column has NOT NULL attribute. – ypercubeᵀᴹ Nov 30 '12 at 17:07
  • @ypercube I'm trying to avoid errors. – Wolf480pl Dec 1 '12 at 8:34

You can query the INFORMATION_SCHEMA:


In the INFORMATION_SCHEMA.COLUMNS table there is a IS_NULLABLE column.

You could turn it into a function, I imagine, but I would probably put this logic in an outer part.

  • 1
    That should do it. In fact, I wrote up how to collect all null and non-null column names for a given table using INFORMATION_SCHEMA.COLUMNS : dba.stackexchange.com/a/28745/877. Your direct answer gets +1 !!! – RolandoMySQLDBA Nov 30 '12 at 19:33
  • What do you mean by "outer part" ? The program that is connecting to MySQL? – Wolf480pl Dec 1 '12 at 9:43
  • @Wolf480pl in whatever generates the SQL statement. Typically your schema is not changing that frequently. I was thinking you would have to be generating this code. Because putting it in manually is no more efficient than just matching the code to the schema in the first place. – Cade Roux Dec 3 '12 at 7:41
  • So basically a clientside schema cache? – Wolf480pl Dec 4 '12 at 15:19
  • 1
    @Wolf480pl I guess so. Certainly you don't need to be inquiring about the schema in every call. – Cade Roux Dec 4 '12 at 15:24

Cade's answer is correct, but the information directly from the link:

  WHERE table_name = 'mytable'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.