Computed Columns

A computed column stores data generated from other columns by a scalar expression included in the column definition.

Why use computed columns?

Computed columns are especially useful when used with partitioning, JSONB columns, or secondary indexes.

  • Partitioning requires that partitions are defined using columns that are a prefix of the primary key. In the case of geo-partitioning, some applications will want to collapse the number of possible values in this column, to make certain classes of queries more performant. For example, if a users table has a country and state column, then you can make a stored computed column locality with a reduced domain for use in partitioning. For more information, see the partitioning example below.

  • JSONB columns are used for storing semi-structured JSONB data. When the table's primary information is stored in JSONB, it's useful to index a particular field of the JSONB document. In particular, computed columns allow for the following use case: a two-column table with a PRIMARY KEY column and a payload column, whose primary key is computed as some field from the payload column. This alleviates the need to manually separate your primary keys from your JSON blobs. For more information, see the JSONB example below.

  • Secondary indexes can be created on computed columns, which is especially useful when a table is frequently sorted. See the secondary indexes example below.

Considerations

Computed columns:

  • Cannot be used to generate other computed columns.
  • Cannot be a foreign key reference.
  • Behave like any other column, with the exception that they cannot be written to directly.
  • Are mutually exclusive with DEFAULT.

Creation

To define a computed column, use the following syntax:

  1. column_name <type> AS (<expr>) STORED
ParameterDescription
columnnameThe name/identifier of the computed column.
<type>The data type of the computed column.
<expr>The pure scalar expression used to compute column values. Any functions marked as impure, such as now() or nextval() cannot be used.
STORED(Required)_ The computed column is stored alongside other columns.

Examples

Create a table with a computed column

In this example, let's create a simple table with a computed column:

  1. > CREATE TABLE names (
  2. id INT PRIMARY KEY,
  3. first_name STRING,
  4. last_name STRING,
  5. full_name STRING AS (CONCAT(first_name, ' ', last_name)) STORED
  6. );

Then, insert a few rows of data:

  1. > INSERT INTO names (id, first_name, last_name) VALUES
  2. (1, 'Lola', 'McDog'),
  3. (2, 'Carl', 'Kimball'),
  4. (3, 'Ernie', 'Narayan');
  1. > SELECT * FROM names;
  1. +----+------------+-------------+----------------+
  2. | id | first_name | last_name | full_name |
  3. +----+------------+-------------+----------------+
  4. | 1 | Lola | McDog | Lola McDog |
  5. | 2 | Carl | Kimball | Carl Kimball |
  6. | 3 | Ernie | Narayan | Ernie Narayan |
  7. +----+------------+-------------+----------------+

The full_name column is computed from the first_name and last_name columns without the need to define a view.

Create a table with geo-partitions and a computed column

Note:
Partioning is an enterprise feature. To request and enable a trial or full enterprise license, see Enterprise Licensing.

In this example, create a table with geo-partitioning and a computed column:

  1. > CREATE TABLE user_locations (
  2. locality STRING AS (CASE
  3. WHEN country IN ('ca', 'mx', 'us') THEN 'north_america'
  4. WHEN country IN ('au', 'nz') THEN 'australia'
  5. END) STORED,
  6. id SERIAL,
  7. name STRING,
  8. country STRING,
  9. PRIMARY KEY (locality, id))
  10. PARTITION BY LIST (locality)
  11. (PARTITION north_america VALUES IN ('north_america'),
  12. PARTITION australia VALUES IN ('australia'));

Then, insert a few rows of data:

  1. > INSERT INTO user_locations (name, country) VALUES
  2. ('Leonard McCoy', 'us'),
  3. ('Uhura', 'nz'),
  4. ('Spock', 'ca'),
  5. ('James Kirk', 'us'),
  6. ('Scotty', 'mx'),
  7. ('Hikaru Sulu', 'us'),
  8. ('Pavel Chekov', 'au');
  1. > SELECT * FROM user_locations;
  1. +---------------+--------------------+---------------+---------+
  2. | locality | id | name | country |
  3. +---------------+--------------------+---------------+---------+
  4. | australia | 333153890100609025 | Uhura | nz |
  5. | australia | 333153890100772865 | Pavel Chekov | au |
  6. | north_america | 333153890100576257 | Leonard McCoy | us |
  7. | north_america | 333153890100641793 | Spock | ca |
  8. | north_america | 333153890100674561 | James Kirk | us |
  9. | north_america | 333153890100707329 | Scotty | mx |
  10. | north_america | 333153890100740097 | Hikaru Sulu | us |
  11. +---------------+--------------------+---------------+---------+

The locality column is computed from the country column. The locality values can then be used for geo-partitioning.

Create a table with a JSONB column and a computed column

In this example, create a table with a JSONB column and a computed column:

  1. > CREATE TABLE student_profiles (
  2. id STRING PRIMARY KEY AS (profile->>'id') STORED,
  3. profile JSONB
  4. );

Then, insert a few rows of data:

  1. > INSERT INTO student_profiles (profile) VALUES
  2. ('{"id": "d78236", "name": "Arthur Read", "age": "16", "school": "PVPHS", "credits": 120, "sports": "none"}'),
  3. ('{"name": "Buster Bunny", "age": "15", "id": "f98112", "school": "THS", "credits": 67, "clubs": "MUN"}'),
  4. ('{"name": "Ernie Narayan", "school" : "Brooklyn Tech", "id": "t63512", "sports": "Track and Field", "clubs": "Chess"}');
  1. > SELECT * FROM student_profiles;
  1. +--------+---------------------------------------------------------------------------------------------------------------------+
  2. | id | profile |
  3. +--------+---------------------------------------------------------------------------------------------------------------------+
  4. | d78236 | {"age": "16", "credits": 120, "id": "d78236", "name": "Arthur Read", "school": "PVPHS", "sports": "none"} |
  5. | f98112 | {"age": "15", "clubs": "MUN", "credits": 67, "id": "f98112", "name": "Buster Bunny", "school": "THS"} |
  6. | t63512 | {"clubs": "Chess", "id": "t63512", "name": "Ernie Narayan", "school": "Brooklyn Tech", "sports": "Track and Field"} |
  7. +--------+---------------------------------------------------------------------------------------------------------------------+

The primary key id is computed as a field from the profile column.

Create a table with a secondary index on a computed column

In this example, create a table with a computed columns and an index on that column:

  1. > CREATE TABLE gymnastics (
  2. id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  3. athlete STRING,
  4. vault DECIMAL,
  5. bars DECIMAL,
  6. beam DECIMAL,
  7. floor DECIMAL,
  8. combined_score DECIMAL AS (vault + bars + beam + floor) STORED,
  9. INDEX total (combined_score DESC)
  10. );

Then, insert a few rows a data:

  1. > INSERT INTO gymnastics (athlete, vault, bars, beam, floor) VALUES
  2. ('Simone Biles', 15.933, 14.800, 15.300, 15.800),
  3. ('Gabby Douglas', 0, 15.766, 0, 0),
  4. ('Laurie Hernandez', 15.100, 0, 15.233, 14.833),
  5. ('Madison Kocian', 0, 15.933, 0, 0),
  6. ('Aly Raisman', 15.833, 0, 15.000, 15.366);
  1. > SELECT * FROM gymnastics;
  1. +--------------------------------------+------------------+--------+--------+--------+--------+----------------+
  2. | id | athlete | vault | bars | beam | floor | combined_score |
  3. +--------------------------------------+------------------+--------+--------+--------+--------+----------------+
  4. | 3fe11371-6a6a-49de-bbef-a8dd16560fac | Aly Raisman | 15.833 | 0 | 15.000 | 15.366 | 46.199 |
  5. | 56055a70-b4c7-4522-909b-8f3674b705e5 | Madison Kocian | 0 | 15.933 | 0 | 0 | 15.933 |
  6. | 69f73fd1-da34-48bf-aff8-71296ce4c2c7 | Gabby Douglas | 0 | 15.766 | 0 | 0 | 15.766 |
  7. | 8a7b730b-668d-4845-8d25-48bda25114d6 | Laurie Hernandez | 15.100 | 0 | 15.233 | 14.833 | 45.166 |
  8. | b2c5ca80-21c2-4853-9178-b96ce220ea4d | Simone Biles | 15.933 | 14.800 | 15.300 | 15.800 | 61.833 |
  9. +--------------------------------------+------------------+--------+--------+--------+--------+----------------+

Now, run a query using the secondary index:

  1. > SELECT athlete, combined_score FROM gymnastics ORDER BY combined_score DESC;
  1. +------------------+----------------+
  2. | athlete | combined_score |
  3. +------------------+----------------+
  4. | Simone Biles | 61.833 |
  5. | Aly Raisman | 46.199 |
  6. | Laurie Hernandez | 45.166 |
  7. | Madison Kocian | 15.933 |
  8. | Gabby Douglas | 15.766 |
  9. +------------------+----------------+

The athlete with the highest combined score of 61.833 is Simone Biles.

Add a computed column to an existing table

In this example, create a table:

  1. > CREATE TABLE x (
  2. a INT NULL,
  3. b INT NULL AS (a * 2) STORED,
  4. c INT NULL AS (a + 4) STORED,
  5. FAMILY "primary" (a, b, rowid, c)
  6. );

Then, insert a row of data:

  1. > INSERT INTO x VALUES (6);
  1. > SELECT * FROM x;
  1. +---+----+----+
  2. | a | b | c |
  3. +---+----+----+
  4. | 6 | 12 | 10 |
  5. +---+----+----+
  6. (1 row)

Now add another computed column to the table:

  1. > ALTER TABLE x ADD COLUMN d INT AS (a // 2) STORED;

The d column is added to the table and computed from the a column divided by 2.

  1. > SELECT * FROM x;
  1. +---+----+----+---+
  2. | a | b | c | d |
  3. +---+----+----+---+
  4. | 6 | 12 | 10 | 3 |
  5. +---+----+----+---+
  6. (1 row)

For more information, see ADD COLUMN.

Convert a computed column into a regular column

You can convert a stored, computed column into a regular column by using ALTER TABLE.

In this example, create a simple table with a computed column:

  1. > CREATE TABLE office_dogs (
  2. id INT PRIMARY KEY,
  3. first_name STRING,
  4. last_name STRING,
  5. full_name STRING AS (CONCAT(first_name, ' ', last_name)) STORED
  6. );

Then, insert a few rows of data:

  1. > INSERT INTO office_dogs (id, first_name, last_name) VALUES
  2. (1, 'Petee', 'Hirata'),
  3. (2, 'Carl', 'Kimball'),
  4. (3, 'Ernie', 'Narayan');
  1. > SELECT * FROM office_dogs;
  1. +----+------------+-----------+---------------+
  2. | id | first_name | last_name | full_name |
  3. +----+------------+-----------+---------------+
  4. | 1 | Petee | Hirata | Petee Hirata |
  5. | 2 | Carl | Kimball | Carl Kimball |
  6. | 3 | Ernie | Narayan | Ernie Narayan |
  7. +----+------------+-----------+---------------+
  8. (3 rows)

The full_name column is computed from the first_name and last_name columns without the need to define a view. You can view the column details with the SHOW COLUMNS statement:

  1. > SHOW COLUMNS FROM office_dogs;
  1. +-------------+-----------+-------------+----------------+------------------------------------+-------------+
  2. | column_name | data_type | is_nullable | column_default | generation_expression | indices |
  3. +-------------+-----------+-------------+----------------+------------------------------------+-------------+
  4. | id | INT | false | NULL | | {"primary"} |
  5. | first_name | STRING | true | NULL | | {} |
  6. | last_name | STRING | true | NULL | | {} |
  7. | full_name | STRING | true | NULL | concat(first_name, ' ', last_name) | {} |
  8. +-------------+-----------+-------------+----------------+------------------------------------+-------------+
  9. (4 rows)

Now, convert the computed column (full_name) to a regular column:

  1. > ALTER TABLE office_dogs ALTER COLUMN full_name DROP STORED;

Check that the computed column was converted:

  1. > SHOW COLUMNS FROM office_dogs;
  1. +-------------+-----------+-------------+----------------+-----------------------+-------------+
  2. | column_name | data_type | is_nullable | column_default | generation_expression | indices |
  3. +-------------+-----------+-------------+----------------+-----------------------+-------------+
  4. | id | INT | false | NULL | | {"primary"} |
  5. | first_name | STRING | true | NULL | | {} |
  6. | last_name | STRING | true | NULL | | {} |
  7. | full_name | STRING | true | NULL | | {} |
  8. +-------------+-----------+-------------+----------------+-----------------------+-------------+
  9. (4 rows)

The computed column is now a regular column and can be updated as such:

  1. > INSERT INTO office_dogs (id, first_name, last_name, full_name) VALUES (4, 'Lola', 'McDog', 'This is not computed');
  1. > SELECT * FROM office_dogs;
  1. +----+------------+-----------+----------------------+
  2. | id | first_name | last_name | full_name |
  3. +----+------------+-----------+----------------------+
  4. | 1 | Petee | Hirata | Petee Hirata |
  5. | 2 | Carl | Kimball | Carl Kimball |
  6. | 3 | Ernie | Narayan | Ernie Narayan |
  7. | 4 | Lola | McDog | This is not computed |
  8. +----+------------+-----------+----------------------+
  9. (4 rows)

See also

Was this page helpful?
YesNo