tags:

views:

142

answers:

4

How do you insert a record with a nullable column ?

+6  A: 

you omit that column from the insert statement, or set it to NULL

northpole
+5  A: 

if column2 is null

insert into table(column1, column3) values (1, 3)

or just include it

insert into table(column1, column2, column3) values (1, null, 3)
Martin
see my code edit
KM
@Martin L, see latest edit...
KM
A: 

You guys got me thinking: move -1 to the null indicator, To insert a valid value, move 0 to the null indicator.

Kombucha
+3  A: 

always name all columns in the INSERT. If the table schema changes, your INSERTs are more likely to not break or work wrong. As a result, so just put a NULL in:

INSERT INTO YourTable (col1, col2, col2) VALUES (1, null, 'A')

EDIT
there are many ways for problems to happen, here is just one example of how schema change breaks poorly coded INSERTs:

YourTable
col1  int      not null
col2  int      null
col3  char(1)  null

you code this in several places:

INSERT INTO YourTable VALUES (1, null, 'A')
--OR this                             ---<<<<EDIT2
INSERT INTO YourTable VALUES (1, 'A') ---<<<<EDIT2

you change your table to:

YourTable
col1  int      not null
col1a int      null  default(0)
col2  int      null
col3  char(1)  null

what happens with your code? what values go in what columns?

if you had coded it this way

INSERT INTO YourTable (col1, col2, col2) VALUES (1, null, 'A')

it will still work

KM
I don't understand how adding all columns in will affect anything not breaking. Can you give an example?
Martin
@Martin L, see edit
KM
I thought you meant there was a difference between YourTable(col1, col3) and YourTable(col1, col2, col3). I know your example is bad, I just thought you meant not including col2 was bad.
Martin
Of course, if you want to use the default value rather than explicitly using null then omitting the column is fine.
KeeperOfTheSoul
gotcha, I know it was way off topic, but thanks for clearing that up. I'm not a DB guy ... as you can probably tell.
Martin
@KeeperOfTheSoul, it is hard to add a column, to an existing table, without setting a default value, which is why I put it in my simple example.
KM