MySQL 5.7 introduced a new feature called generated column. It is called generated column because the data in this column is computed based on a predefined expression or from other columns.
The syntax is:
Example
SELECT * FROM `letters_lowercase`
Result-
1 90/20 Hyderabad 90/20 Hyderabad
The values in the full_address column are computed on the fly when you query data from the contacts table
colun_name data_type [ GENERATED ALWAYS ] AS ( )
[ VIRTUAL|STORED ] [ UNIQUE [KEY] ] [ [PRIMARY] KEY ] [ NOT NULL ] [ COMMENT ]
[ VIRTUAL|STORED ] [ UNIQUE [KEY] ] [ [PRIMARY] KEY ] [ NOT NULL ] [ COMMENT ]
Example
CREATE TABLE `letter_lowercase` (
`id` int(11) NOT NULL,
`address1` varchar(45) DEFAULT NULL,
`address2` varchar(45) DEFAULT NULL,
`full_address` varchar(100) GENERATED ALWAYS AS (CONCAT(address1,' ',address2)))
ENGINE=InnoDB DEFAULT CHARSET=latin1;
`id` int(11) NOT NULL,
`address1` varchar(45) DEFAULT NULL,
`address2` varchar(45) DEFAULT NULL,
`full_address` varchar(100) GENERATED ALWAYS AS (CONCAT(address1,' ',address2)))
ENGINE=InnoDB DEFAULT CHARSET=latin1;
Now we insert a record on table.
INSERT INTO `letters_lowercase`(`id`, `address1`, `address2`) VALUES (1,'90/20', 'Hyderabad')
Now read the data from table
SELECT * FROM `letters_lowercase`
Result-
1 90/20 Hyderabad 90/20 Hyderabad
The values in the full_address column are computed on the fly when you query data from the contacts table
No comments:
Post a Comment