Write a MySQL query where length of the records is longer than 1?

MySQLMySQLi Database

Here, we will use OCTET_LENGTH to check the length of a record since we want the records with length more than 1. Let us first create a table −

mysql> create table DemoTable
(
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserName varchar(20),
   UserGender varchar(20)
);
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(UserName,UserGender) values('John','M');
Query OK, 1 row affected (0.82 sec)
mysql> insert into DemoTable(UserName,UserGender) values('Carol','Male');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(UserName,UserGender) values('Mia','Female');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(UserName,UserGender) values('Emma','F');
Query OK, 1 row affected (0.17 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+----------+------------+
| UserId | UserName | UserGender |
+--------+----------+------------+
| 1      | John     | M          |
| 2      | Carol    | Male       |
| 3      | Mia      | Female     |
| 4      | Emma     | F          |
+--------+----------+------------+
4 rows in set (0.00 sec)

Here is the query where we are getting records with length more than 1.

mysql> select *from DemoTable where OCTET_LENGTH(UserGender) > 1;

This will produce the following output −

+--------+----------+------------+
| UserId | UserName | UserGender |
+--------+----------+------------+
| 2      | Carol    | Male       |
| 3      | Mia      | Female     |
+--------+----------+------------+
2 rows in set (0.00 sec)
raja
Published on 29-Apr-2019 12:22:48
Advertisements