Fetch rows where a field value is less than 5 chars in MySQL?

MySQLMySQLi Database

To fetch rows where a field value is less than 5 chars, you need to use LENGTH() function. The syntax is as follows −

SELECT *FROM yourTableName WHERE LENGTH(yourColumnName) < 5;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table fieldLessThan5Chars
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> yourZipCode varchar(10)
   -> );
Query OK, 0 rows affected (0.52 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into fieldLessThan5Chars(yourZipCode) values('35801');
Query OK, 1 row affected (0.10 sec)
mysql> insert into fieldLessThan5Chars(yourZipCode) values('3580');
Query OK, 1 row affected (0.20 sec)
mysql> insert into fieldLessThan5Chars(yourZipCode) values('90001');
Query OK, 1 row affected (0.40 sec)
mysql> insert into fieldLessThan5Chars(yourZipCode) values('100');
Query OK, 1 row affected (0.20 sec)
mysql> insert into fieldLessThan5Chars(yourZipCode) values('10');
Query OK, 1 row affected (0.17 sec)
mysql> insert into fieldLessThan5Chars(yourZipCode) values('0');
Query OK, 1 row affected (0.15 sec)
mysql> insert into fieldLessThan5Chars(yourZipCode) values('90209');
Query OK, 1 row affected (0.11 sec)
mysql> insert into fieldLessThan5Chars(yourZipCode) values('33124');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from fieldLessThan5Chars;

The following is the output −

+----+-------------+
| Id | yourZipCode |
+----+-------------+
|  1 | 35801       |
|  2 | 3580        |
|  3 | 90001       |
|  4 | 100         |
|  5 | 10          |
|  6 | 0           |
|  7 | 90209       |
|  8 | 33124       |
+----+-------------+
8 rows in set (0.00 sec)

Example

Here is the query to fetch all rows where a field value is less than 5 characters −

mysql> select *from fieldLessThan5Chars where length(yourZipCode) < 5;

Output

+----+-------------+
| Id | yourZipCode |
+----+-------------+
|  2 |        3580 |
|  4 |         100 |
|  5 |          10 |
|  6 |           0 |
+----+-------------+
4 rows in set (0.00 sec)
raja
Published on 19-Mar-2019 13:19:09
Advertisements