Insert into a table using only default values
4December 4, 2013 by Kenneth Fisher
A while back I talked about the DEFAULT keyword and using it to tell SQL to use the default value without having to specify an actual value. Well along that same note, what do you do if you want all of the columns to use their defaults? Or if you don’t have any columns except for an identity column? You use the DEFAULT VALUES command.
INSERT INTO TableName DEFAULT VALUES
This is particularly useful if you have a table with just an identity column. In fact to my knowledge it’s the only way to insert a row into a table like this.
CREATE TABLE IdentTable (Id int identity (1,1)) GO INSERT INTO IdentTable DEFAULT VALUES GO
Of course tables like that were more common back before SQL 2012 when SEQUENCES showed up.
One thing I do want to point out when using this particular command. If you haven’t specified a default constraint then the default is NULL. Why does this matter? Well if you have a column without a default constraint that doesn’t allow NULLs then the command will fail.
CREATE TABLE IdentTable2 ( Id int identity (1,1), NotNull char(10) NOT NULL) GO INSERT INTO IdentTable2 DEFAULT VALUES GO
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column ‘NotNull’, table ‘master.dbo.IdentTable2’; column does not allow nulls. INSERT fails.
Hi Ken,
Can I create a check constraint to not allow a value like ‘dummy’ into a column?
For example:
Create table T1(C1 int not null, C2 varchar(50) default ‘N/A’ not null);
Insert into T1 values(1,’road’);
Insert into T1(C1) values(2);
Insert into T1 values(1,’dummy’); —> this insert should fail.
the 3rd insert statement should fail, since I have a value “dummy” for C2 column.
*** I know check constraint lets you insert certain values defined in the constraint, but I want opposite of it.
Is this possible?
Thank you
NikTekk
Actually a CHECK constraint is exactly what you want.
A CHECK constraint will do any type of check you like not just “Is it in a list of values”. You can do LIKEs and NOT LIKEs, =, etc. Very versatile really.
Thank you Ken!
I’m wasn’t sure if of negative check.
.Nik
[…] example of adding some original (o) input (i) words
into our staging table. The use of “DEFAULT VALUES” clause on the insert allows me to add more attributes in the future without disturbing any […]