PostgreSQL: How to Set Default Value for a Column

Updated: January 4, 2024 By: Guest Contributor Post a comment

Overview

In PostgreSQL, setting default values for columns can streamline database operations and ensure consistency. This tutorial will guide you through the steps to define default values at column creation as well as how to alter existing columns to add default values.

Setting Default Values

Setting default values for table columns in PostgreSQL is a fundamental database design technique. A default value is the value a column will adopt in the absence of a specified value during an INSERT operation. Default values are crucial for ensuring data integrity and can be a constant or an expression evaluated at the time of row insertion. They are defined using the DEFAULT clause in the column definition. Below, we delve into defining default values for new tables and altering existing tables to include default values.

Creating a New Table with Column Defaults

CREATE TABLE user_accounts (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

This example shows how to create a new table with a timestamp default value for the “created_at” column, which captures the current date and time whenever a new row is added.

Altering Existing Tables

If you need to add a default value to an existing column, you can use the ALTER TABLE statement:

ALTER TABLE user_accounts
ALTER COLUMN created_at SET DEFAULT CURRENT_TIMESTAMP;

This modifies the “created_at” column of the “user_accounts” table to have a default value of CURRENT_TIMESTAMP.

Using Expressions as Default Values

PostgreSQL allows for the use of expressions as default values:

CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    hire_date DATE,
    vacation_days INT DEFAULT (SELECT avg(vacation_days) FROM employees)
);

This example sets a default for the “vacation_days” column based on the average vacation days of employees already recorded in the table. Remember that this could have performance implications and should be used judiciously.

Resetting a Default Value

To remove a default value, you can use ALTER TABLE with DROP DEFAULT:

ALTER TABLE user_accounts
ALTER COLUMN created_at DROP DEFAULT;

Now, the “created_at” column no longer has a default value, and unless a value is specified during data insertion, it will be NULL (assuming the column allows NULLs).

Using Functions for Dynamic Defaults

Dynamically computed defaults can be set using functions. For instance, you might want to create a UUID for each row:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE items (
    id UUID DEFAULT uuid_generate_v4(),
    name VARCHAR(255) NOT NULL
);

This creates a unique identifier for each item using the uuid_generate_v4() function from the uuid-ossp extension.

Constraints on Default Values

While setting defaults, it’s important to ensure that the default values comply with any constraints defined for the column. For example, for a NOT NULL constraint, you should not define a default value that is NULL.

Take constraints like CHECK into consideration when setting defaults. For example, if a column defines a CHECK constraint limiting the values to within a certain range, the default value must also adhere to this constraint.

Advanced Usage: Trigger-Based Defaults

This section outlines how to use triggers to create complex default values. A trigger can call a function whenever a new row is inserted, providing a flexible way to compute default values.

CREATE OR REPLACE FUNCTION custom_default()
RETURNS TRIGGER AS $
BEGIN
    NEW.vacation_days := (SELECT avg(vacation_days) FROM employees);
    RETURN NEW;
END;
$ LANGUAGE plpgsql;

CREATE TRIGGER set_custom_default
BEFORE INSERT ON employees
FOR EACH ROW
WHEN (NEW.vacation_days IS NULL)
EXECUTE FUNCTION custom_default();

In this example, the custom_default function sets the “vacation_days” column’s default value only if it is NULL at the time of insertion.

Common Pitfalls and Best Practices

Here are some common mistakes and best practices to consider when dealing with default values:

  • Always consider the impact of a default value on the overall database schema.
  • Test default values thoroughly to ensure they are working as intended.
  • Use expressions judiciously as they might affect performance.
  • Keep in mind that changing a default value does not affect existing rows, only new ones.

Conclusion

Setting default values for PostgreSQL table columns simplifies the insertion process and helps maintain data integrity. This tutorial covered how to set, alter, and remove default values in detail. Remember to ensure that your default values adhere to all column constraints and to consider the implications of using expressions or functions. By understanding and applying these concepts effectively, you will be able to design cleaner and more efficient databases.