Char_length Function - How to find number of characters in string in MySQL

Let's break down the steps to find the number of characters in a string using the `Char_Length` function in MySQL. We'll use an example with a sample table named "customer" and some data inserted into it.

First, we'll define the "customer" table and insert some sample data:
-- Create the customer table
CREATE TABLE `customer` (
  `idcustomer` int,
  `firstname` varchar(50) NULL,
  `lastname` varchar(30) NULL,
  `age` int(11) DEFAULT NULL,
  `phonenumber` char(11) DEFAULT NULL,
  `dob` date DEFAULT NULL,
  `gender` char(1) NOT NULL
);

-- Insert some sample records
INSERT INTO customer(idcustomer, firstname, lastname, age, phonenumber, dob, gender)
VALUES
(1, 'Raza', null, 39, '505-4141969', '1980-01-01', 'M'),
(2, 'Aamir', 'Naz', 39, '505-4141969', '1980-01-01', 'M'),
(3, 'Aamir', 'Shahzad', 39, '505-4141900', '1980-01-01', 'M'),
(4, 'Aamir1', 'Shahzad', 39, '505-4141900', '1980-01-01', 'M'),
(5, 'Robert', 'Ladson', 69, '505-345900', '1960-01-01', 'M');
Now, let's use the `Char_Length` function to find the character count for values in different columns:
-- Retrieve character counts using Char_Length
SELECT
  firstname,
  CHAR_LENGTH(firstname) AS firstname_length,
  lastname,
  CHAR_LENGTH(lastname) AS lastname_length,
  phonenumber,
  CHAR_LENGTH(phonenumber) AS phonenumber_length
FROM customer;
In this SQL query, we're retrieving data from the "customer" table. For each row, we're selecting the "firstname," "lastname," and "phonenumber" columns, along with their respective character lengths using the `CHAR_LENGTH` function. The result will show the original values and the corresponding character counts for each of these columns.

Feel free to use these steps to find the number of characters in a string using the `Char_Length` function in MySQL for your projects or queries!
Next Post Previous Post
No Comment
Add Comment
comment url