Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: what is different between DEFAULT NULL vs NULL on alter table

Tags:

postgresql

Is any different between this two queries? If there is what will be faster?

ALTER TABLE mytable ADD COLUMN newcolumn VARCHAR(64) DEFAULT NULL;
ALTER TABLE mytable ADD COLUMN newcolumn VARCHAR(64) NULL;

How does it work under the hood? If we have a table with a millions of rows will any one of queries rewrite every row to set NULL value to a new column?

like image 235
oxana Avatar asked Nov 03 '17 08:11

oxana


People also ask

What does default NULL mean?

If a data type specification includes no explicit DEFAULT value, MySQL determines the default value as follows: If the column can take NULL as a value, the column is defined with an explicit DEFAULT NULL clause. If the column cannot take NULL as a value, MySQL defines the column with no explicit DEFAULT clause.

Is default NULL necessary?

No, it isn't necessary because without adding DEFAULT NULL, it gives NULL value. For example, let's say you haven't added DEFAULT NULL and inserted a record with no value, then the result would display the NULL value as the inserted value.

What does default null mean in SQL?

By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.


2 Answers

https://www.postgresql.org/docs/current/static/sql-createtable.html

NULL The column is allowed to contain null values. This is the default.

and further

DEFAULT default_expr

...

If there is no default for a column, then the default is null.

so your two statements is resetting column to two default creation options.

Whichever in your column is not default will take longer over default one. If both were made not default - will take same time as it will just update catalog, changing two, one or no modifiers...

like image 137
Vao Tsun Avatar answered Sep 20 '22 09:09

Vao Tsun


The first statement adds a column with a default value of NULL, meaning an insert will set null if not explicitly included in the insert.

The second statement adds a column with a “constraint” that the column value may be NULL, as the opposite of the NOT NULL constraint.

like image 24
wmorrell Avatar answered Sep 21 '22 09:09

wmorrell