Chamara Keragala Chamara Keragala - 3 months ago 19
SQL Question

Inserting into table with a Default column value

I have created a table with a default column value


(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
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
using statement #2, it successfully executes.

Can some please explain why this happens?


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.....