Young Emil
Young Emil

Reputation: 2266

How to use CHAR_LENGTH() in CREATE TABLE query - MYSQL

My question may sound vague but am going to try as much as possible to make it clear enough. Prior to this, I have made some research on the internet and other SO pages but to no avail. Is it possible to use CHAR_LENGTH() function in a CREATE TABLE clause like we usually do in SELECT Clause :

SELECT CHAR_LENGTH("SQL Tutorial") AS LengthOfString;

What I want to do is similar to this:

CREATE TABLE `tbl_content` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` varchar(32) NOT NULL,
  `no_of_chars` int(4) NULL DEFAULT CHAR_LENGTH(`content`) ,
  PRIMARY KEY (`id`)
)

But the above CREATE statement gives an error near CHAR_LENGTH. Precisely, During insertion of a record into such a table, I want the server to be able to read the length of the content field and store in no_of_chars field as default value.

Is this POSSIBLE?

Upvotes: 4

Views: 344

Answers (1)

Lukasz Szozda
Lukasz Szozda

Reputation: 175556

Yes, you could use generated column:

CREATE TABLE `tbl_content` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` varchar(32) NOT NULL,
  `no_of_chars` int(4) AS ( CHAR_LENGTH(`content`)) ,
  PRIMARY KEY (`id`)
);

DBFiddle Demo

Upvotes: 4

Related Questions