Blog Post

Insert into a table using only default values

,

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.

Filed under: Microsoft SQL Server, SQLServerPedia Syndication, T-SQL Tagged: code language, language sql, microsoft sql server, sql statements, T-SQL

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating