How to use OCTET_LENGTH() in SQL

The SQL OCTET_LENGTH() function

The OCTET_LENGTH() function returns the number of bytes in a given string.

Syntax

OCTET_LENGTH(string) 

Parameter

  • string: This represents the string whose byte length will be returned.

Example

The following code shows how to use the OCTET_LENGTH() function in SQL:

CREATE TABLE Product (
id int,
product_name varchar(50),
price varchar(50),
product_id varchar (20)
);
-- Insert data
INSERT INTO Product
VALUES (101,'T-shirt','$100','oo-01-345');
INSERT INTO Product
VALUES (102,'Hand Bag','$65','oo-01-238');
INSERT INTO Product
VALUES (103,'Ipad','$1200','oo-01-103');
INSERT INTO Product
VALUES (104,'Cereal','$30','oo-01-775');
INSERT INTO Product
VALUES (105,'Microwave','$520','oo-01-788');
INSERT INTO Product
VALUES (106,'cloth clips','$15','oo-01-924');
INSERT INTO Product
VALUES (108,'Zara Perfume','$120','oo-01-245');
-- Query
SELECT product_id, product_name, OCTET_LENGTH(product_name) AS otlen_name
FROM Product;

Explanation

  • Lines 1–6: We create a table called Product that has the id, product_name, price, and book_id columns.
  • Lines 9–22: We insert data into the Product table.
  • Lines 25–26: We fetch the data in the product_id and product_name columns. We then use the OCTET_LENGTH() function to return the byte length of each product name in the product_name column. This is then stored in a new column, otlen_name.

Free Resources