Home > DeveloperSection > Forums > Inserting into table with a Default column value
Tanuj Kumar

Total Post:134

Posted on    May-04-2013 2:10 AM

 MSSQL Server MSSQL Server 

 1 Reply(s)
 901  View(s)
Rate this:
Hi Everyone!

I have created a table with a default column value male

 (name varchar(20), 
  age int, 
  sex varchar(5) default 'male')
Insert statement #1:

INSERT INTO Persons values('Bob', 20)
Insert statement #2:

INSERT INTO Persons(name,sex) values('Bob', 20)
When I try to insert the values into Persons table using the insert statement #1, I get the error shown below

column name or number of supplied values does not match table definition

But when I insert into Persons using statement #2, it successfully executes.

Can some please explain why this happens?

Thanks in advance!


Total Post:604

Posted on    May-04-2013 9:05 AM


Well, in your statement #1, if you omit the list of columns, you must supply values for all three columns, and you're not doing that. That's why it fails if you provide only two of those values.

And your statement #2 should probably be:

INSERT INTO Persons(name, age) values('Bob', 20)
and then you're clearly specifying which columns to insert into (name and age) and you're providing the two values required to fill two columns - that's why it works. The third column will be filled with the configured default, since you didn't specify anything for it.

For these reasons, I would recommend to always explicitly specify the list of columns you want to insert data into - don't just omit that list and assume that you're getting all columns right...

Don't want to miss updates? Please click the below button!

Follow MindStick