Use of regular expression in SQL Queries

Find the matching pattern with help of regular expression in SQL Queries

Find the name starting with ‘ma’ like martin, mahesh

^ is used to match first character in regular expression

SELECT name FROM employee WHERE name REGEXP '^ma';

Find the last string matching use $ sign in regular expression

SELECT name FROM employee WHERE name REGEXP 'on$';

Find the string either RAM or SHAM from name list using Regular expression

SELECT name  FROM employee WHERE name REGEXP 'RAM|SHAM';

Find the 5 digit number from the string by using Regular Expression

SELECT name,salary FROM employees WHERE salary REGEXP '^.{5}$';
PatternDescription
^Match the beginning of the string
$Match the end of the String
*Match zero or more occurrence
.Match any single character
\Match alternative string (either side match)
?Match zero or one instance of the preceding string
[abc]Match any character listed in Square Bracket
+Match one or more instances of string preceding it
[A-Z]Match any character present in Upper Case
[a-z]Match any character present in lower case
[^abc]Match any character not listed in the Square Bracket
[0-9]Match any digit for 0 to 9
[[:class:]]Matches the character class , for example , matches [[:digit:]] to digits, [[:space:]] to space, [[:alnum:]_] to alphanumerics, [:punct:] is match punctuations and [:upper:] for upper class letters. etc
{m}Matches exactly m occurrences of the preceding element.
{m,n}Matches at least m and at most n occurrences of the preceding element.
[[:<:]]matches the beginning of words.
[[:>:]]
matches the end of words.
Regular Expression patterns

Leave a Reply