How to use CHAR_LENGTH() in MySQL CREATE TABLE query?


Use CHAR_LENGTH(yourColumnName) at the time of table creation. Let us first see an example and create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Title varchar(200),
   `Number_of_characters` int as (char_length(Title))
   );
Query OK, 0 rows affected (0.18 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Title) values('Introduction To MySQL');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Title) values('Introduction To Java');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Title) values('Introduction To MongoDB');
Query OK, 1 row affected (0.04 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------------------------+----------------------+
| Id | Title                   | Number_of_characters |
+----+-------------------------+----------------------+
| 1  | Introduction To MySQL   | 21                   |
| 2  | Introduction To Java    | 20                   |
| 3  | Introduction To MongoDB | 23                   |
+----+-------------------------+----------------------+
3 rows in set (0.00 sec)

Updated on: 30-Jul-2019

56 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements