2

I've got a table where identifiers(XXXXX-065-00) should match a division(65). I'd like to query all the rows that don't match.

The following SQL seems to work, but is there a better or more efficient way of doing this?

select id,division,identifier from table where identifier not REGEXP '.....-'+division+'-..'
3
  • Are the division numbers all the same length? And if they are shorter than 3 digits, should the preceding digit(s) be part of the match? Commented Feb 6, 2020 at 23:10
  • The division can be any number between 10 and 175, but they are represented in the identifier as 010 - 175 ( the identifier always has the same number of characters. ) Commented Feb 7, 2020 at 23:31
  • 1
    @GMB solution ought to work for you then? Commented Feb 7, 2020 at 23:33

1 Answer 1

1

You can concat() the regex string:

where identifier not regexp concat('^.{5}-', lpad(division, 3, '0'), '-..$')

Note that in MySQL + is a numeric addition (it does not do string concatenation, like in SQL Server for example).

Other remarks:

  • you probably need to pad the division with '0's so it has exactly 3 characters

  • I added ^/$ to make the regex match on the entire string rather than do partial matching, since this seems to be what you want

  • you can use quantifiers: .{5} stands for .....

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to "loosely" pad the division in the event that it's 150 instead of 050?
@HLD: lpad(division, 3, '1')?
where identifier not regexp concat('^.{5}-', lpad(division, 3, '0'), '-..$') did the trick. I think the + in the last part of the concat is redundant.

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.