MySQL Regular Expression Exercise

Write a mysql statement to get name of students containing exactly four characters.

Suppose the student table is -

 
+----+-------+---------+------------+
| id | name  | dept_id | birth      |
+----+-------+---------+------------+
|  1 | Maria | 2       | 1994-03-12 |
|  2 | John  | 1       | 1993-02-07 |
|  3 | Gal   | 4       | 1992-09-11 |
|  4 | Jakey | 2       | 1990-08-31 |
|  5 | Rama  | 1       | 1994-12-09 |
|  6 | Maria | 4       | 1993-10-09 |
+----+-------+---------+------------+

Solution

To apply extended regular expression REGEXP operator is used with pattern matching characters. The caret (^) is used to start the match at the beginning of string. The [...] matches any character between the square bracket. The caret ($) is used to start the match at the end of string.

The following statement retrieves the name of students containing exactly four characters.

mysql> SELECT * FROM student where name REGEXP '^....$';

Output of the above statement -

+----+------+---------+------------+
| id | name | dept_id | birth      |
+----+------+---------+------------+
|  2 | John | 1       | 1993-02-07 |
|  5 | Rama | 1       | 1994-12-09 |
+----+------+---------+------------+




Related MySQL Exercises

MySQL concatenate
MySQL Get Current Date, User, Version
MySQL Get Maximum Value
MySQL Administrator
MySQL where clause
MySQL order by
MySQL get difference between two dates
MySQL Pattern Matching
MySQL Join
MySQL delete duplicate row
MySQL update multiple rows
Get nth highest salary using MySQL
Display the nth row from MySQL
Commit and rollback in mysql
MySQL SELECT top 5
MySQL display the alternate rows





Read more articles


General Knowledge



Learn Popular Language