Regular Expressions Across Platforms — MySQL and SQL Server Implementation Compared

UPI Study › Courses › Database Programming › Free lessons › Lesson 11.7 Free with a free account

Regular Expressions Across Platforms — MySQL and SQL Server Implementation Compared

Database Programming · Chapter 11: Advanced Data Operations and Pattern MatchingSection 11.7 · lesson 69 of 7611 min · free with a free account

← Reshaping Data with PIVOT and UNPIVOTNext lesson: Managing Database Security: Key Practices and Tools →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Match, extract and rewrite text with regex in MySQL and SQL Server.

  • Translate LIKE patterns into anchored regular expressions
  • Use the MySQL functions REGEXP_LIKE, REGEXP_REPLACE, REGEXP_INSTR and REGEXP_SUBSTR
  • Compare SQL Server LIKE brackets and PATINDEX with its 2025 regex functions
  • Explain how flags, escaping and replacement syntax differ between platforms

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,234 words). Read along, or search it.

Opening Scenario

Phone Numbers in Mixed Formats

Leo Park, Lantern Books' developer, receives mixed phone formats. How can he test the whole value, rather than a substring? Amina Diallo, the database administrator, checks the target server. Pattern syntax and available functions vary across platforms and versions. We'll compare MySQL and SQL Server patterns, alongside executable SQLite checks. Server-only listings are labeled non-run.

Sandbox Setup

Invented Phones and Emails

This disposable contact extension keeps our customer identities. Its phone and email values are invented examples. A regular expression, or regex, describes matching strings. It expresses structure beyond simple percent and underscore wildcards. This SQLite shell supplies a regexp matching function. MySQL and SQL Server's other regex functions remain separate dialects. Run the contact setup. A matching format cannot establish whether a phone number is reachable. Asha and Chen use dashes, Ben adds parentheses, and Dara stores only digits. Decide which shapes to accept or clean.

LIKE Basics

Percent and Underscore Match Whole Values

Like tests the whole value against its pattern. A literal 555 pattern matches only that complete string, not every phone containing those digits. Percent can match any sequence, including an empty sequence. Underscore matches one character; neither wildcard independently says that the character must be a digit. Here, the first branch has no matches. The second branch adds percent, asking for phone values that begin with those three digits. Run both branches in SQLite. The names come from the prefix test, not from the exact three-character test. Asha, Chen, and Dara appear. Regex generally searches inside values, so translating from like requires deliberate anchors.

Regex Building Blocks

Anchors, Brackets, Quantifiers and Groups

Anchors tie a pattern to boundaries. The phone pattern uses a start anchor, three digits, a dash, three digits, another dash, four digits, and an end anchor. A bracket expression chooses one character from a set. A caret inside its opening bracket negates the set, rather than anchoring the whole pattern. Quantifiers repeat the preceding item. Braces specify counts, star allows zero or more, plus requires one or more, and question mark makes an item optional. Parentheses group and capture text, while the vertical bar offers alternatives. Dot usually excludes newline unless a flag changes that behavior; brackets can make a dot literal. A prefix becomes a start anchor, and a suffix becomes an end anchor. A contains pattern needs neither; a second-letter condition uses dot after a start anchor.

SQLite Example

An Anchored Dashed Phone Match

This shell supplies regex matching. Another SQLite application may need an extension, so check the actual environment. Run this anchored match locally. It checks the entire dashed shape, without relying on a server-specific replacement function. Asha and Chen match. Ben and Dara use different shapes; an unanchored substring test would not require the whole value to fit.

Quick Check

Which Product Codes Match

A fresh product-code list contains BX1, BX12, and AX1. The regex pattern anchors both ends, with a dot after the prefix. Which values match? Pause, and predict from the pattern on screen. BX1 is the only match. The prefix must be BX, followed by exactly one additional character. Run the new code query. BX12 has too many characters, while AX1 begins with the wrong prefix. Only BX1 appears. With both anchors, the single dot plays the role of one underscore in like.

MySQL Matching

REGEXP_LIKE for Phones and Emails

MySQL provides REGEXP, RLIKE, and REGEXP_LIKE. Its modern regex functions arrived in version 8.0.4. The anchored phone pattern requires the complete dashed structure. Asha and Chen fit; this MySQL listing is not executed locally. MySQL's match test returns one, zero, or null when an input is null. Default case behavior follows collation, so pass a case flag when the rule matters. The email pattern screens a simplified shape, using brackets for a literal dot. It is not a complete email validator, nor proof that a mailbox exists.

REGEXP_REPLACE

Strip Punctuation, Then Reformat Digits

REGEXP_REPLACE rewrites matched text. The negated digit class finds punctuation and spaces, and replacing those matches with an empty string leaves the digits. A second pattern groups exactly ten digits into three captured sections. MySQL's replacement references those sections with $1, $2, and $3. Our anchors prevent a partial ten-digit substring from being reformatted inside a longer value. Still validate length and meaning, rather than calling every cleaned value valid. The non-run example separates cleanup from formatting. A valid shape is an input rule; a pretty display is a presentation choice.

MySQL Functions

Positions, Extraction and Match Flags

REGEXP_INSTR returns a match position, or zero when no match exists. REGEXP_SUBSTR extracts matching text, or returns null when it finds none. Flag positions differ by function. Replacement accepts start position and occurrence before its match type; copying the shortest function's argument layout would be wrong. MySQL supports case-sensitive and case-insensitive flags, plus multiline, dot-newline, and Unix-line options. The letters on this guide identify those choices. MySQL normally doubles backslashes, unless no-backslash-escapes mode is enabled. Bracket ranges and bracket dots avoid that layer.

Before SQL Server 2025

LIKE Brackets and PATINDEX

SQL Server through 2022 has no native regex functions. Its like supports bracket expressions, so digit positions can be written out individually. That is still like syntax, with whole-value matching and no regex quantifiers. MySQL like does not give brackets this same character-class meaning. PATINDEX uses like-style patterns and returns a one-based position, or zero for no match. This negated class locates a character outside digits and dashes. Percent at both ends enables an anywhere search here. It is not universally required; leaving an end constrained can deliberately anchor a PATINDEX search.

SQL Server 2025

Native Regex and Compatibility Level 170

SQL Server 2025 adds native regex functions, using a different engine from MySQL. REGEXP_LIKE also requires database compatibility level 170 or higher. Check the database setting after an upgrade. A newer server alone does not guarantee that this match function is enabled for the database. SQL Server defaults to case-sensitive regex matching. Its flags include case, multiline, and dot-newline controls; explicitly choosing case behavior makes the rule clearer. A check can enforce the rule after cleanup; existing invalid rows prevent adding this constraint. Case supplies a numeric report flag. Count and table-valued matching or splitting complement extraction and replacement. Shared function names do not guarantee identical arguments or pattern features.

Dialect Differences

Replacement Syntax Differs by Server

SQL Server's replacement argument can be omitted to remove matches. MySQL requires that argument, even when the intended replacement is an empty string. Replacement captures also differ: SQL Server uses \1, while MySQL uses $1. SQL Server can use ampersand for the entire matched text. SQL Server string literals do not require MySQL's usual doubled backslash. Newline flags differ too, so copy the intended behavior rather than just the pattern text. Keep like for simple prefixes. Performance depends on the query plan; regex is neither universally slower nor automatically seekable.

Final Check

A Dot Is Literal in LIKE

A fresh text field contains a.b and axb. This query uses like, with a dot between the two letters. Which values match this exact pattern? Pause, and decide which pattern language the query is actually using. a.b is the only match. Dot is literal in this like pattern, so axb has a different middle character. Run the new query. In a regex pattern, an unescaped dot would have a wildcard role; bracket-dot would restore its literal meaning. The literal-dot value remains. Treating both strings as matches would import regex rules into like; selecting only axb would reverse the literal comparison.

Key Takeaways

An Explicit Pattern Policy for Imports

Leo first chooses whether to find, validate, extract, or rewrite text. Anchors, character classes, quantifiers, and groups express the intended structure. Amina checks server version, compatibility, case flags, and escaping. MySQL and SQL Server share ideas, while differing in native availability and replacement syntax. Their import has an explicit pattern policy. A matching shape still does not prove a phone number works or an email address exists.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Regular Expressions Across Platforms — MySQL and SQL Server Implementation Compared

What is the difference between LIKE and REGEXP in SQL?
LIKE tests the entire value against a simple pattern, where % matches any sequence and _ matches exactly one character, while a regular expression usually searches anywhere inside the value and adds character classes, quantifiers and alternatives. So phone LIKE '555%' finds values beginning with 555, but the regex 555 matches those digits anywhere. To make a regex test the whole value, anchor it with a caret at the start and a dollar-sign anchor at the end.
How do you use REGEXP_LIKE in MySQL?
REGEXP_LIKE(expr, pattern, match_type) returns 1 for a match, 0 for no match and NULL when an input is NULL; REGEXP and RLIKE are operator forms of the same test. For example, WHERE REGEXP_LIKE(code, '^BX[0-9]', 'c') finds codes that start with uppercase BX followed by a digit. REGEXP_LIKE and its companion functions arrived in MySQL 8.0.4, although the REGEXP operator is older. Case sensitivity otherwise follows the collation, so pass 'c' or 'i' when it matters.
Does SQL Server support regular expressions?
Yes, from SQL Server 2025, which adds native functions such as REGEXP_LIKE, REGEXP_REPLACE and REGEXP_SUBSTR; REGEXP_LIKE also requires database compatibility level 170 or higher. Through SQL Server 2022 there is no native regex, but LIKE and PATINDEX accept bracket expressions, so phone LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' checks each digit position. Those patterns have no quantifiers, so every position must be written out.
Why does a regex replacement from MySQL fail in SQL Server?
The two systems use different regex engines and argument rules. MySQL's REGEXP_REPLACE always requires a replacement argument and refers to captured groups with a dollar sign and the group number, while SQL Server 2025 uses a backslash and the number, accepts an ampersand for the whole match, and lets you omit the replacement to delete matches. MySQL string literals also usually need doubled backslashes. Test each pattern on the target server.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →