EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials SQL Tutorial SQL REGEX
Secondary Sidebar
SQL Tutorial
  • Functions
    • SQL Date Function
    • SQL Server Functions
    • SQL String Functions
    • SQL Compare String
    • Timestamp to Date in SQL
    • SQL REGEX
    • SQL Window Functions
    • SQL Syntax
    • SQL CONCAT
    • SQL ALTER TABLE
    • SQL MOD()
    • SQL Timestamp
    • SQL Min and Max
    • SQL TO_DATE()
    • SQL DATEADD()
    • SQL DATEDIFF()
    • SQL HOUR()
    • SQLite? functions
    • ANY in SQL
    • LIKE Query in SQL
    • SQL NOT NULL
    • SQL NOT IN
    • SQL MAX()
    • SQL MIN()
    • SQL SUM()
    • SQL COUNT
    • SQL identity
    • SQL DELETE Trigger
    • SQL Declare Variable
    • SQL Text Search
    • SQL COUNT DISTINCT
    • SQL TEXT
    • SQL Limit Order By
    • BETWEEN in SQL
    • LTRIM() in SQL
    • TOP in SQL
    • SQL Select Top
    • Merge SQL
    • SQL TRUNCATE()
    • SQL UNION
    • SQL ALL
    • SQL INTERSECT
    • SQL Alias
    • SQL Server Substring
    • CUBE in SQL
    • SQL RANK()
    • SQL CTE
    • SQL LAG()
    • SQL MID
    • SQL avg()
    • SQL WEEK
    • SQL DELETE
    • SQL DATEPART()
    • SQL DECODE()
    • SQL DENSE_RANK()
    • SQL NTILE()
    • SQL NULLIF()
    • SQL Stuff
    • SQL Ceiling
    • SQL EXISTS
    • SQL LEAD()
    • SQL COALESCE
    • SQL BLOB
    • SQL ROW_NUMBER
    • SQL Server Replace
    • SQL Ranking Function
    • SQL Server Permission
  • Basic
    • What is SQL
    • Careers in SQL
    • Careers in SQL Server
    • IS SQL Microsoft?
    • SQL Management Tools
    • What is SQL Developer
    • Uses of SQL
    • How to Install SQL Server
    • What is SQL Server
    • SQL Quick References
    • SQL Like Wildcard
    • SQL Like with Multiple Values
    • SQL Examples
    • SQL Server Versions
    • SQL DROP DB
    • SQL Case Insensitive
    • SQL Expressions
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL WAITFOR
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • SQL Enum
    • SQL GROUP BY WHERE
    • SQL ROW
    • SQL EXECUTE
    • SQL EXCLUDE
    • SQL Performance Tuning
    • SQL UUID
    • Begin SQL
    • SQL Update Join
    • SQL Between Dates
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • sqlplus set commands
    • SQL Alter Command
    • SQL Commands Update
    • SQL DML Commands
    • SQL DDL Commands
    • FETCH in SQL
  • Clause
    • SQL Clauses
    • SQL IN Operator
    • SQL SELECT DISTINCT Multiple Columns
    • SQL Null Values
    • SQL LIKE
    • SQL LIKE Query
    • SQL LIKE Operator
    • SQL LIKE Clause
    • SQL NOT Operator
    • SQL Minus
    • SQL WHERE Clause
    • SQL with Clause
    • SQL HAVING Clause
    • SQL HAVING Clause
    • SQL GROUP BY DAY
    • ORDER BY Clause in SQL
    • SQL ORDER BY CASE
    • SQL ORDER BY DESC
    • SQL ORDER BY DATE
    • SQL ORDER BY Alphabetical
    • SQL ORDER BY Ascending
    • SQL Order by Count
    • SQL GROUP BY Month
    • SQL GROUP BY Multiple Columns
    • SQL GROUPING SETS
  • Queries
    • SQL Insert Query
    • SQL SELECT Query
    • SQL SELECT RANDOM
    • SQL Except Select
    • SQL Subquery
    • SQL SELECT DISTINCT
    • SQL WITH AS Statement
  • Keys
    • SQL Keys
    • SQL Foreign Key
    • Primary Key in SQL
    • Foreign Key in SQL
    • Unique Key in SQL
    • SQL UNIQUE Constraint
    • SQL Primary Key
    • Alternate Key in SQL
    • SQL Super Key
  • T-SQL
    • T-SQL pivot
    • T-SQL Formatter
    • T-SQL TRY CATCH
    • T-SQL CTE
    • T-SQL CASE
    • T-SQL DATEPART
    • T-SQL Date Format
    • T-SQL ROUND
    • T-SQL Loop
    • T-SQL IIF
    • T-SQL Union
    • T-SQL CREATE TABLE
    • T-SQL INSERT
    • T-SQL Stuff
    • T-SQL ISNULL
    • T-SQL ADD Column
    • T-SQL DATEDIFF
  • Joins
    • Join Query in SQL
    • Types of Joins in SQL
    • Types of Joins in SQL Server
    • SQL Inner Join
    • SQL Join Two Tables
    • SQL Delete Join
    • SQL Left Join
    • LEFT OUTER JOIN in SQL
    • SQL Right Join
    • SQL Cross Join
    • SQL Outer Join
    • SQL Full Join
    • SQL Self Join
    • Natural Join SQL
    • SQL Multiple Join
  • Advanced
    • MDF File in SQL Server
    • SQL Aliases
    • SQL Hosting
    • SQL Auto Increment
    • SQL Injection
    • SQL Wildcards
    • SQL Check
    • SQL Indexes
    • Select Distinct
    • SQL BETWEEN
    • SQLPlus spool
    • SQL Create Table
    • SQL Schema
    • Comparison Operators in SQL
    • SQL_plus
    • SQL Formatter
    • SQL LEFT INNER JOIN
    • SQL Plus Command
    • SQLPlus not found
    • SQL Injection Attack
    • Aggregate Functions in SQL
    • SQL REVOKE
    • SQL Select Distinct Count
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL BIGINT
    • SQL Crosstab
    • SQL Wildcard Character
    • SQL INSTR()
    • SQL now
    • SQL synonyms
    • SQLite?export to csv
    • What is Procedure in SQL
    • Stored Procedure in SQL?
    • SQL Server Constraints
    • SQL DELETE ROW
    • Column in SQL
    • Table in SQL
    • SQL Virtual Table
    • SQL Merge Two Tables
    • SQL Table Partitioning
    • SQL Temporary Table
    • SQL Clone Table
    • SQL Rename Table
    • SQL LOCK TABLE
    • SQL Clear Table
    • SQL DESCRIBE TABLE
    • SQL Mapping
    • Cursors in SQL
    • AND in SQL
    • Wildcard in SQL
    • SQL FETCH NEXT
    • SQL Views
    • SQL Delete View
    • Triggers in SQL
    • SQL UPDATE Trigger
    • SQL AFTER UPDATE Trigger
    • SQL Update Statement
    • SQL DROP TRIGGER
    • SQL DROP Table
    • Types of SQL Views
    • SQL Port
    • SQL Clustered Index
    • SQL COMMIT
    • Distinct Keyword in SQL
    • PARTITION BY in SQL
    • SQL Set Operators
    • SQL UNION ALL
    • Metadata in SQL
    • SQL Bulk Insert
    • Array in SQL
    • SQL REGEXP
    • JSON in SQL
    • SQL For loop
    • EXPLAIN in SQL
    • ROLLUP in SQL
    • Escape Character SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL pivot
    • SQL Import CSV
    • SQL if then else
    • SQL ignore-case
    • SQL Matches
    • SQL Search String
    • SQL Column Alias
    • SQL extensions
    • SQL Substring Function
    • Charindex SQL
  • SqlAlchemy
    • What is SQLAlchemy
    • SqlAlchemy ORM
    • SQLAlchemy count
    • SQLAlchemy update object
    • SQLAlchemy pip
    • SQLAlchemy Connection
    • SQLAlchemy Transaction
    • SQLAlchemy Metadata
    • SQLAlchemy Raw SQL
    • SQLAlchemy Filter in List
    • SQLAlchemy Alias
    • SQLAlchemy unique
    • SQLAlchemy JSONB
    • SQLAlchemy Async
    • SQLAlchemy Types
    • SQLAlchemy Many to Many
    • SQLAlchemy Example
    • SQLAlchemy Model
    • SQLAlchemy Data Types
    • SQLAlchemy Filter
    • SQLAlchemy SQLite
    • SQLAlchemy DateTime
    • SQLAlchemy create_engine
    • SQLAlchemy Delete
    • SQLAlchemy Migrations
  • NoSQL
    • NoSQL Databases List
    • NoSQL Data Modeling
    • Types of NoSQL Databases
    • NoSQL Injection
    • NoSQL vs SQL Databases
    • NoSQL Use Cases
    • NoSQL Key Value
  • Interview Questions
    • SQL Interview Questions
    • Advance SQL Interview Questions
    • SQL Joins Interview Questions
    • SQL Server Interview Questions
    • SQL Current Month

SQL REGEX

Definition of SQL REGEX

Regular expressions or SQL REGEX are the types of operations or a method to find a pattern in a string. In SQL, we can use regular expressions to find a particular string or pattern from the database. There is no need to install any package or a module to use the regular expressions in SQL; one could just use the term REGEX in the SQL query to implement the regular expressions. Here it is to be noted that the query here with regex is not case sensitive, and the backslash here is used to esca[e the particular character, so it is suggested to use a double backslash to find a particular pattern.

SQL Regex

Key Takeaways

After carefully reading this article, one would be able to:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

  1. Understand the core intuition of SQL queries and use regular expressions in the same.
  2. One would be able to understand the key concept of regular expressions and the need for the same.
  3. One would be able to implement regular expressions in SQL queries.
  4. One would be able to perform the pattern-matching task easily and efficiently with REGEX in SQL.

Syntax of SQL Regex

To Implement the regular expression in the SQL query, one needs to add the term “REGEXP” just above the regular expression.

For example, the syntax could look like:

SELECT name FROM student_table WHERE name REGEXP 'REGEX_Query';

Here as we can see in the above code, the SQL query with REGEX looks the same as the normal query, just an additional term REGEXP is used, and the regular expression is written just after that.

Listed Regular Expressions

[A-Z] Matches the upper case letters
[a-z] Matches the lower case letters
[0-9] Matches any number between 0 to 9
[^abc] Matches any character that is not listed in the bracket
{n} Matches n instances
[[:<:]] Matches the beginning of the words
[[:>:]] Matches the ending of the words
* Matches zero or all instances
+ Matches one or more instances.
. Matches any single character

Need for SQL Regex

In a large dataset, there can be a need for pattern matching in the string to perform some of the search operations to get a part of the small for some important task. The pattern-matching task can be also done in normal SQL. Using SQL queries like LIKE or WHERE.

Using Regular Expressions in SQL queries makes the process of pattern searching more easy, fast, and more efficient Using SQL queries, pattern searching is a very easy task as compared to normal SQL queries, as some of the complex patterns can not be searched easily with normal SQL queries.

How to Work with SQL?

There are 3 ways to work with regex in SQL.

  1. LIKE
  2. SIMILAR TO
  3. POSIX

1. LIKE

LIKE is used to implement the Regex in SQL. LIKE operator is written just before the regex operations o execute the SQL query. It matches the condition and returns the value if true.

Code:

SELECT * FROM People
WHERE Name LIKE 'p%';

Here the above SQL query would return the name of the people starting with the character “p”.

2. SIMILAR TO

The SIMILAR TO operator is also the same as the LIKE operator, which matches the condition of the regex patterns and returns a value if the condition is True.

Code:

SELECT * FROM People
WHERE Name LIKE 'p%';

The above query would also returns all the names of people starting with the character “p”.

3. POSIX

The POSIX is different than the LIKE and SIMILAR TO Operators. Unlike the LIKE and SIMILAR to operators, first of all, POSIX is not an operator which is not written before the regex pattern.

As there are not any = and != in SQL, POSIX uses its own operators to command over regex, which is one of the most powerful techniques to use Regex in SQL.

Operators
  1. ~ : It is case-sensitive. It compares the two strings and returns true if the two strings are the same.
  2. !~ : It is case-sensitive. It also compares the two strings and returns false if the two strings are the same.
  3. ~*: It is not case-sensitive. It returns true if the first stirring is contained in the second string.
  4. !~*: It is not case-sensitive. It returns false if the first string is contained in the second string.
Examples

1. “Parth” ~ “P%” — True

“Parth” ~ “p%” — False (Case Sensitiveness)

2. “Parth” ~* “P%” — True

“Parth” ~* “p%” — True (Not Case-sensitive)

3. “Parth” !~ “P%” — False (It matches – returns false)

“Parth” !~ “p%” — True (Does not match – returns True)

4. “Parth” !~* “P%” — False (Matches – returns false)

“Parth” !~* “p%” — False (Matches — returns false)

SQL Regex Implementation

As we discussed above, the Regex can be implemented in the SQL query easily by adding the term REGEXP at the end of the query just before the pattern.

Syntax:

SELECT name FROM student_table WHERE name REGEXP 'Pattern';

Examples of SQL Regex

Following are the examples of SQL Regex with query:

1. Searching a String
SELECT title FROM websites WHERE title REGEXP 'eduCBA';

This query returns all the strings containing the word eduCBA in the title or a string.

Like, eduCBA writer, Course on eduCBA, etc.

2. Matching the End of the string
SELECT name FROM websites WHERE name REGEXP 'eduCBA';

This query returns the strings or sentences that are ending with the word eduCBA.

For Example, a Data Science course on eduCBA.

3. Matching the beginning of the string
SELECT name FROM websites WHERE name REGEXP '^eduCBA';

This query returns all the strings that are starting with the word eduCBA.

For example, eduCBA is a great platform for data science courses.

4. Matching the end of the words
SELECT title FROM websites WHERE REGEXP 'CBA[[:>:]]';

This query returns all the words that are ending with CBA.

For example, eduCBA.

5. Matching the start of the word
SELECT title FROM websites WHERE title REGEXP '[[:<:]]edu';

This query returns the words that are starting with edu.

For example, eduCBA.

6. Matching spaces and tabs
SELECT title FROM websites WHERE title REGEXP '[[:blank:]]';

This query matches all the blank spaces and tabs in the string in the document.

7. Matching number of characters
SELECT title FROM websites WHERE title REGEXP 'Ohk{3}';

This SQL query matches the number of characters that are listed in the curly bracket.

For example, this particular query will return all the matches with Ohkkk.

8. Matching all email addresses
SELECT email FROM data WHERE email REGEXP 'educba.com$';

This SQL query will return all the email addresses that end with educba.com

For example, [email protected]

9. Searching Keyword from a string
SELECT * FROM `name` WHERE `title` REGEXP 'eduCBA';

This SQL query returns the strings or a sentence that has the word “code” at the start, end, or in the middle of the sentence.

10. Alternative Search
SELECT * FROM `names` WHERE `title` REGEXP '^[ps]|^[i]';

This query returns all the names that are starting with either ps or i. The | vertical bar is used as an alternative here.

For Example, names like Parth, Ishan, etc.

11. Searching Multiple numbers of characters
SELECT * FROM `names` WHERE `title` REGEXP 'ok{2,4}';

This query will return all the matching string that is okk or okkkk.

Note that it will not return the string like ok or okkk.

Conclusion

In this article, we discussed the regular expression in SQL that can be used to make the pattern-matching process easier and more efficient. We discussed the brief idea of the Regex in SQL, with its core intuition, working mechanism, syntax, the need for it, and some of the examples of using and implementing the regular expressions in SQL. Knowledge about these concepts will help one to understand and use SQL queries on complex datasets easily. It will be able to perform well in tasks related to pattern matching in interviews.

Recommended Articles

We hope that this EDUCBA information on “SQL REGEX” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. SQL Aliases
  2. SQL Hosting
  3. SQL Check
  4. SQL Auto Increment
Popular Course in this category
JDBC Training (6 Courses, 7+ Projects)
  6 Online Courses |  7 Hands-on Projects |  37+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

PHP Training (5 Courses, 3 Project)4.9
Windows 10 Training (4 Courses, 4+ Projects)4.8
SQL Training Program (10 Courses, 8+ Projects)4.7
PL SQL Training (4 Courses, 2+ Projects)4.7
Oracle Training (17 Courses, 8+ Projects)4.7
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more