Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert default values in SQL table?

I have a table like this:

create table1 (field1 int,                field2 int default 5557,                field3 int default 1337,                 field4 int default 1337) 

I want to insert a row which has the default values for field2 and field4.

I've tried insert into table1 values (5,null,10,null) but it doesn't work and ISNULL(field2,default) doesn't work either.

How can I tell the database to use the default value for the column when I insert a row?

like image 816
Zbigniew Wazeliniak Avatar asked Jan 08 '12 12:01

Zbigniew Wazeliniak


People also ask

How do you define default value in SQL?

When using CREATE TABLE , you can specify default values for columns by typing DEFAULT and then the desired value after it. If a row is inserted that does not specify a value for that column, the database will fill it in with the default value instead.

What is default value in SQL table?

The default value is used for the column's value when one is not specified (for example, when you insert a row into the table without specifying a value for the column). You can add a default constraint either when creating a table or after the table already exists.


1 Answers

Best practice it to list your columns so you're independent of table changes (new column or column order etc)

insert into table1 (field1, field3)  values (5,10) 

However, if you don't want to do this, use the DEFAULT keyword

insert into table1 values (5, DEFAULT, 10, DEFAULT) 
like image 179
gbn Avatar answered Oct 22 '22 01:10

gbn