GENERATED
GENERATED is a clause in SQL used with identity columns. Its purpose is to automatically generate a unique value for a particular column, typically a primary key, whenever a new row is added to the table. It simplifies the handling of unique identifiers within tables. There are two types, namely GENERATED ALWAYS and GENERATED BY DEFAULT, which determine when and how the database will generate and assign the new value.
Example
Output
Explanation
In the example, the total_price
column is a generated column that automatically calculates and stores the total price of each order by multiplying the quantity
and price
. When a new record is inserted into the orders
table, the value for the total_price
column is automatically calculated and stored in the total_price
column.
Example
Output
Explanation
The GENERATED ALWAYS AS
keyword is used to automatically generate a value for a specific column based on the values in other columns. In this case, the full_name
column is automatically generated as a combination of the first_name
and last_name
columns. The STORED
keyword means the generated values are physically stored in the table.
Example
Output
Explanation
In the SQL code snippet, a new table named employees
is created.
This table contains three explicit columns id
, name
, dob
, and a calculated column age
.
The GENERATED ALWAYS
syntax used for the age
column means it always appears with the value calculated from the expression (months_between(sysdate, dob)/12)
. This means, age is calculated automatically based on the date of birth (dob
) and the current date (sysdate
), and the value cannot be manually set or altered.