MySQL query to get the length of all columns and display the result in a single new column?


To get the length of all columns i.e. the count of all the characters for column values, use char_length(). Let us first create a table. Here, we have two columns, therefore we will calculate for each row consisting of both the values FirstName and LastName −

mysql> create table DemoTable
(
   FirstName varchar(100),
   LastName varchar(100)
);
Query OK, 0 rows affected (1.07 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris','Brown');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('David','Miller');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Carol','Taylor');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable −

This will produce the following output −

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Chris     | Brown    |
| David     | Miller   |
| Carol     | Taylor   |
+-----------+----------+
3 rows in set (0.00 sec)

Following is the query to get the length of all the columns −

mysql> select char_length(concat(FirstName,LastName)) from DemoTable;

This will produce the following output −

+-----------------------------------------+
| char_length(concat(FirstName,LastName)) |
+-----------------------------------------+
|                                      10 |
|                                      11 |
|                                      11 |
+-----------------------------------------+
3 rows in set (0.00 sec)

Updated on: 01-Oct-2019

548 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements