Simulating Computed Columns within PostgreSQL
Unlike MS SQL Server, PostgreSQL doesn't natively support computed columns. However, several methods effectively replicate this functionality.
PostgreSQL 12 and Later
PostgreSQL 12 introduced STORED generated columns, mirroring the behavior of SQL Server's computed columns. These columns are physically stored within the table, readily accessible during queries.
<code class="language-sql">CREATE TABLE tbl ( int1 int, int2 int, product bigint GENERATED ALWAYS AS (int1 * int2) STORED );</code>
PostgreSQL 11 and Earlier
For older PostgreSQL versions, simulating virtual generated columns requires functions and attribute notation.
Function Syntax:
<code class="language-sql">CREATE FUNCTION col(tbl) RETURNS type AS 'expression';</code>
Usage:
<code class="language-sql">SELECT tbl.col, ... FROM tbl;</code>
This approach mimics a virtual generated column; however, it's not included in SELECT *
.
Alternative Approaches
SELECT *
retrieves both original and computed columns.Important Considerations:
SELECT *
.IMMUTABLE
to enable expression indexes.The above is the detailed content of How Can I Emulate Computed Columns in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!