Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set default value to null on postgresql

Tags:

sql

postgresql

I read here that I should be able to set the default value of a column like this:

ALTER [ COLUMN ] column SET DEFAULT expression

But this:

ALTER address.IsActive SET DEFAULT NULL

Gives me this error:

ERROR: syntax error at or near "address" LINE 1: ALTER address.IsActive SET DEFAULT NULL

What have I done wrong? Also, how can I specify multiple columns to have their default value be NULL?

like image 845
1252748 Avatar asked Feb 12 '13 17:02

1252748


People also ask

Can a default value be null?

If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.

How do you set a default null in SQL?

You can set a default by using the SQL Server Management Studio (SSMS) Object Explorer or by executing Transact-SQL. If you do not assign a default value to the column, and the user leaves the column blank, then: If you set the option to allow null values, NULL will be inserted into the column.

How do I change the default value of a column in PostgreSQL?

Changing a Column's Default Value. To set a new default for a column, use a command like: ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77; Note that this doesn't affect any existing rows in the table, it just changes the default for future INSERT commands.

Are Postgres fields nullable by default?

All built-in data types shipped with Postgres 12 have NULL as default1.


2 Answers

The correct syntax is:

ALTER TABLE table_name ALTER COLUMN column_name SET DEFAULT NULL;

For several columns you repeat the ALTER COLUMN part as documented in the manual:

ALTER TABLE table_name 
    ALTER COLUMN foo SET DEFAULT NULL,
    ALTER COLUMN bar SET DEFAULT 0;
like image 200
a_horse_with_no_name Avatar answered Oct 06 '22 00:10

a_horse_with_no_name


alter table dogs
alter column breed set default 'boxer'

alter table dogs
alter column breed set default null
like image 38
Tim Avatar answered Oct 06 '22 00:10

Tim