Wednesday, April 23, 2025

MySQL LENGTH Function

The MySQL LENGTH function returns the number of characters in a given string.

It takes a string as an argument and returns an integer value that represents the length of the string.  

What is in our table:


mysql> SELECT * FROM Stores;
+------+--------+------------+-----------------+-----------+-------+
| s_id | city   | store_name | product         | available | price |
+------+--------+------------+-----------------+-----------+-------+
|    1 | London | London_1   | Gold PSU        |       153 |   100 |
|    2 | London | London_2   | Gold PSU        |        75 |   100 |
|    3 | Berlin | Berlin_1   | Green PSU       |        50 |   120 |
|    4 | Berlin | Berlin_2   | XYZ Motherboard |         5 |    75 |
|    5 | Moscow | Moscow_1   | Extension Cable |        50 |    25 |
|    6 | Moscow | Moscow_2   | LPT Cables      |       500 |    10 |
|    7 | Miami  | Miami_1    | COM Cables      |      1450 |     5 |
|    8 | Paris  | Paris_1    | NIC             |       350 |    15 |
+------+--------+------------+-----------------+-----------+-------+
8 rows in set (0.00 sec)

mysql>

We need to give name to our LENGTH instruction:


mysql> SELECT product, LENGTH(product) AS NumberOfCharacters FROM Stores;
+-----------------+--------------------+
| product         | NumberOfCharacters |
+-----------------+--------------------+
| Gold PSU        |                  8 |
| Gold PSU        |                  8 |
| Green PSU       |                  9 |
| XYZ Motherboard |                 15 |
| Extension Cable |                 15 |
| LPT Cables      |                 10 |
| COM Cables      |                 10 |
| NIC             |                  3 |
+-----------------+--------------------+
8 rows in set (0.00 sec)

mysql>

Instruction will select the product column and calculate the number of characters in each value using the LENGTH() function. 

The result shows the name of each product in the product column and the length of the name in the NumberOfCharacters column.

Simple.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...