PostgreSQL - Generate Columns
Last Updated :
16 Aug, 2024
When working with databases, there are scenarios where you need a column’s value to be automatically computed based on other columns. In PostgreSQL, this can be achieved through generated columns. These special columns are calculated based on an expression using other columns in the table. The value of a generated column is updated automatically whenever any of the referenced columns change, ensuring that the derived value is always accurate.
What are Generated Columns?
A generated column is a computed column whose value is derived from other columns within the same row. You cannot directly insert or update data into these columns because their values are determined by the expression defined when the table is created. In PostgreSQL, generated columns can only use immutable functions and cannot involve subqueries.
Types of Generated Columns
In theory, generated columns can be of two types:
- Stored Generated Columns: These columns are computed and stored in the database. The values are calculated during INSERT or UPDATE operations and occupy physical storage. Stored generated columns function similarly to materialized views, except they are automatically updated.
- Virtual Generated Columns: These columns are calculated when they are accessed and do not occupy storage. They are similar to standard views, as the values are computed on the fly during SELECT queries.
Note: As of the latest PostgreSQL versions, only stored generated columns are supported.
Syntax of PostgreSQL for CREATE TABLE using Generated Columns as follows:
CREATE TABLE table_name (
column_name_1 datatype(length) column constrain (if any),
column_name_2 datatype(length) column constrain (if any) ,
.
.
.
.
column_name datatype GENERATED ALWAYS AS (expression) STORED
);
- datatype: Specifies the data type of the generated column.
- expression: Defines the formula or expression used to calculate the value of the generated column.
- STORED: Indicates that the generated column is physically stored in the database.
PostgreSQL Generate Columns Example
Let us take a look at an example to Generate Columns in PostgreSQL to better understand the concept.
CREATE TABLE Addition (
number_1 int,
number_2 int,
number_3 int,
add int GENERATED ALWAYS AS (number_1 + number_2 + number_3) STORED
)
INSERT INTO Addition(number_1, number_2, number_3) VALUES (1,2,3) , (8,-9,2) , (7,1 ,NULL);
TABLE Addition;
Output:

The 'total_sum' column will display the sum of the three numbers for each row. If a NULL value is encountered, the result will also be NULL unless you handle it in the expression using functions like 'COALESCE()'.
Important Points About PostgreSQL Generated Columns
- Generated columns automatically update their values whenever referenced columns change.
- The expression for a generated column can only use immutable functions. Functions that produce different results for the same inputs over time (e.g., 'random()', 'now()') cannot be used.
- You can apply constraints (e.g., NOT NULL, UNIQUE) to generated columns just like any other column.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read