PostgreSQL 12 introduced a new feature called generated columns. Other popular databases already support to generated columns as the Computed column and virtual column.
Result
![]()
What is a generated column?
A generated column is for columns that are a view on a table. The value of the generated column is always computed or generated from other columns in the table.
Create generated column in PostgreSQL
Using GENERATED ALWAYS ASclause we can create the generated column
PostgreSQL Syntax
CREATE TABLE table_name ( col_1 data_type, column_2 data_type, ......... ......... col_3 data_type GENERATED ALWAYS AS (some_calculation) STORED ); |
table_nameis your table name.
col_1, col_1 is the columns used in the calculation to create "generated column."
some_calculationis calculation of col_1 and col_2 like (col_1+col_2)
col_3is the name of the generated column.
Example of creating Generated Column
I am creating an employee table, here we need to calculate the provident fund distribution of employees, it is fixed and no need to change again and again then here we can use the concept of the generated column. The idea behind the calculation of PF (provident fund) is 12 percent of the basic salary of the employee.
CREATETABLEemployee ( ID INTGENERATEDBYDEFAULTASIDENTITY, nametext, basic_salarydecimal, pf_percentagedecimal, emp_pf_distributiondecimalGENERATEDALWAYSAS ((basic_salary*pf_percentage)/100)STORED ); INSERT INTOemployee(name,basic_salary,pf_percentage) VALUES('Dilip', 50000,12); |
SELECT*FROMemployee; |
Result
