Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

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 
SET field = IF(A_FUNCTION_TO_CHECK_IF_ALLOWS_NULL(), NULL, '');
share|improve this question
    
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

1 Answer 1

up vote 2 down vote accepted

You can query the INFORMATION_SCHEMA:

http://dev.mysql.com/doc/refman/5.0/en/columns-table.html

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.

share|improve this answer
    
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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