]> begriffs open source - ai-pg/blob - full-docs/txt/ddl-default.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / ddl-default.txt
1
2 5.2. Default Values #
3
4    A column can be assigned a default value. When a new row is created and
5    no values are specified for some of the columns, those columns will be
6    filled with their respective default values. A data manipulation
7    command can also request explicitly that a column be set to its default
8    value, without having to know what that value is. (Details about data
9    manipulation commands are in Chapter 6.)
10
11    If no default value is declared explicitly, the default value is the
12    null value. This usually makes sense because a null value can be
13    considered to represent unknown data.
14
15    In a table definition, default values are listed after the column data
16    type. For example:
17 CREATE TABLE products (
18     product_no integer,
19     name text,
20     price numeric DEFAULT 9.99
21 );
22
23    The default value can be an expression, which will be evaluated
24    whenever the default value is inserted (not when the table is created).
25    A common example is for a timestamp column to have a default of
26    CURRENT_TIMESTAMP, so that it gets set to the time of row insertion.
27    Another common example is generating a “serial number” for each row. In
28    PostgreSQL this is typically done by something like:
29 CREATE TABLE products (
30     product_no integer DEFAULT nextval('products_product_no_seq'),
31     ...
32 );
33
34    where the nextval() function supplies successive values from a sequence
35    object (see Section 9.17). This arrangement is sufficiently common that
36    there's a special shorthand for it:
37 CREATE TABLE products (
38     product_no SERIAL,
39     ...
40 );
41
42    The SERIAL shorthand is discussed further in Section 8.1.4.