PostgreSQL Generated Columns
Summary: in this tutorial, you will learn about PostgreSQL generated columns whose values are automatically calculated from other columns.
Introduction to PostgreSQL Generated Columns
In PostgreSQL, a generated column is a special type of column whose values are automatically calculated based on expressions or values from other columns.
A generated column is referred to as a computed column in the SQL Server or a virtual column in Oracle.
There are two kinds of generated columns:
- Stored: A stored generated column is calculated when it is inserted or updated and occupies storage space.
- Virtual: A virtual generated column is computed when it is read and does not occupy storage space.
A virtual generated column is like a view, whereas a stored generated column is similar to a materialized view. Unlike a material view, PostgreSQL automatically updates data for stored generated columns.
PostgreSQL currently implements only stored generated columns.
Defining generated columns
Typically, you define a generated column when creating a table with the following syntax:
In this syntax:
column_name
: Specify the name of the generated column.type
: Specify the data type for the column.expression
: Provide an expression that returns values for the calculated column.STORED
keyword: Indicate that the data of the generated column is physically stored in the table.VIRTUAL
keyword: Indicate that the data of the generated column is computed when queried, not stored physically.
To add a generated column to a table, you can use the ALTER TABLE … ADD COLUMN statement:
When defining an expression for a generated column, ensure that it meets the following requirements:
- The expression can only use immutable functions and cannot involve subqueries or reference anything beyond the current row. For example, the expression cannot use the CURRENT_TIMESTAMP function.
- The expression cannot reference another generated column or a system column, except
tableoid
.
A generated column cannot have a default value or an identity definition. Additionally, it cannot be a part of the partition key.
PostgreSQL Generated Column examples
Let’s explore some examples of using generated columns.
1) Concatenating columns
First, create a new table called contacts
:
Second, insert rows into the contacts
table. The values of the full_name
column will be automatically updated from the values in the first_name
and last_name
columns:
Output:
2) Calculating net prices
First, create a table called products
that stores the product information:
In the products
table, the net_price
column is a generated column whose values are calculated based on the list price, tax, and discount with the following formula:
Second, insert rows into the products
table:
Output:
Summary
- Use generated columns to automate calculations within your table.