← Blog overview

Create Computed Column In MySQL

To create computed columns in MySQL you can use the following code:

alter table unique_table_name add discriminator varchar(255) generated always as (key);

  • ALTER TABLE: This specifies that you are going to make changes to an existing table.
  • unique_table_name: This is the name of the table to which you want to add a column. Replace "unique_table_name" with the actual name of the table.
  • ADD: This keyword indicates that you are adding a new column to the table.
  • discriminator: This is the name of the new column being added to the table.
  • varchar(255): This specifies the data type of the new column. In this case, it's a variable-length character string with a maximum length of 255 characters.
  • GENERATED ALWAYS AS (key): This part defines the expression used to generate the values for the new column. Here, it seems to be generating values based on the existing column named key. This means that the values in the new column (discriminator) will be automatically generated based on the values in the key column.

The overall effect of this command is to add a new column named discriminator to the specified table, where the values in this column are generated based on the values in the existing key column. The new column will have a maximum length of 255 characters and will always be populated with values derived from the key column.