
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Query in MySQL for String Fields with Specific Length
To query for string fields with a specific length, use the char_length() or length() from MySQL.
Syntax
The syntax is as follows −
Case 1 − Use of char_length()
This can be used when we are taking length in a number of characters.
The syntax −
select *from yourTableName where char_length(yourColumnName)=anySpecificLengthValue;
Case 2 − Use of length()
This can be used when we are taking the length in bytes.
The syntax −
select *from yourTableName where length(yourColumnName)=anySpecificLengthValue;
To understand the above concept, let us first create a table. The query to create a table is as follows −
mysql> create table StringWithSpecificLength -> ( -> Id int, -> Name varchar(100), -> FavouriteLanguage varchar(50) -> ); Query OK, 0 rows affected (0.52 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into StringWithSpecificLength values(1,'John','Java'); Query OK, 1 row affected (0.66 sec) mysql> insert into StringWithSpecificLength values(2,'Bob','PHP'); Query OK, 1 row affected (0.17 sec) mysql> insert into StringWithSpecificLength values(3,'Carol','Python'); Query OK, 1 row affected (0.16 sec) mysql> insert into StringWithSpecificLength values(4,'Sam','Ruby'); Query OK, 1 row affected (0.25 sec) mysql> insert into StringWithSpecificLength values(5,'Mike','Pascal'); Query OK, 1 row affected (0.19 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from StringWithSpecificLength;
Output
+------+-------+-------------------+ | Id | Name | FavouriteLanguage | +------+-------+-------------------+ | 1 | John | Java | | 2 | Bob | PHP | | 3 | Carol | Python | | 4 | Sam | Ruby | | 5 | Mike | Pascal | +------+-------+-------------------+ 5 rows in set (0.00 sec)
The following is the query to fetch string fields with specific length −
mysql> select *from StringWithSpecificLength where char_length(FavouriteLanguage)=6;
Output
+------+-------+-------------------+ | Id | Name | FavouriteLanguage | +------+-------+-------------------+ | 3 | Carol | Python | | 5 | Mike | Pascal | +------+-------+-------------------+ 2 rows in set (0.00 sec)
Advertisements