Using generated columns in tables

Generated columns are special types of columns in a table whose values are generated by an expression. In this recipe, we will talk about how to create tables with generated columns and will see the use cases for it. In this recipe, we will create a table with a generated column.

Getting ready

We need the privileges to create a table.

How to do it...

  1. Use the GENERATED clause in CREATE TABLE to create the generated columns:
    CREATE TABLE tab1 (c1 INT,
    c2 INT,
    max_col GENERATED ALWAYS AS
    (CASE WHEN c1 > c2 THEN c1 ELSE c2 END));
    
    
  2. Let's see how DB2 populates the values for generated columns automatically:
INSERT INTO tab1(c1, c2) VALUES(5, 10); INSERT INTO tab1(c1, c2) VALUES(30, 20); SELECT * FROM tab1; Results: C1 C2 ...

Get IBM DB2 9.7 Advanced Application Developer Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.