1

I am looking to run an SQL query using a regex match in the middle of a string.

For example, I have a string that is

Status Changed from Needs Action to Completed

I want to search where column = Status Changed from {REGEX} to Completed

Is this possible at all? I don't know regex too well so am seeking some help

6
  • What is the regexp that you want to match in the middle? Or do you mean that it can be anything in that place? Commented Sep 9, 2019 at 16:53
  • WHERE column LIKE 'Status Changed from % to Completed' Commented Sep 9, 2019 at 16:53
  • You can put parentheses around a pattern in the middle: WHERE column RLIKE 'Status Changed from (Needs Action|Incomplete) to Completed' Commented Sep 9, 2019 at 16:57
  • is it possible to just match [a-zA-Z0-9] ? Commented Sep 9, 2019 at 17:07
  • @charlie yes... but put a plus after it like so [a-zA-Z0-9]+ Commented Sep 9, 2019 at 18:16

1 Answer 1

1

From your requirement and the comments, it looks like the LIKE operator should be pretty close to what you need:

SELECT *
FROM mytable
WHERE mycolumn LIKE 'Status Changed from % to Completed'

This will allow any sequence of characters as the previous status.


Else, if you know in advance the list of possible status values, you can make the filtering more accurate with a regexp:

SELECT *
FROM mytable
WHERE mycolumn REGEXP 'Status Changed from (Needs Action)|(Open) to Completed'

The REGEXP operator checks whether values in the column match the given regular expression. The pipe (|) stands for the alternation operator (at least one of the value must match).


Demo on DB Fiddle

create table mytable (
  mycolumn varchar(500)
);

insert into mytable values 
    ('Status Changed from Needs Action to Completed'),
    ('Status Changed from Open to Completed'),
    ('Not a relevant record');

Query #1

SELECT *
FROM mytable
WHERE mycolumn LIKE 'Status Changed from % to Completed';

| mycolumn                                      |
| --------------------------------------------- |
| Status Changed from Needs Action to Completed |
| Status Changed from Open to Completed         |

Query #2

SELECT *
FROM mytable
WHERE mycolumn REGEXP 'Status Changed from (Needs Action)|(Open) to Completed';

| mycolumn                                      |
| --------------------------------------------- |
| Status Changed from Needs Action to Completed |
| Status Changed from Open to Completed         |
Sign up to request clarification or add additional context in comments.

2 Comments

i tried using 'Status Changed from % to Completed' but it returns no results
@charlie: this works fine with your sample data though. I added a DB fiddle to my answer for your reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.