sqlmysqlparameterswildcard

How can I set a numeric wildcard in MySQL?


I'm trying to create a SQL script that finds codes in two different databases. I want to set a parameter that has a numeric wildcard.

Codes are often written like this for example, ABC108, ABC109, DEF47213, etc. I set the parameter as ABC[0-9]+ to return all possible variations of codes that start with ABC, but that resulted in a blank output.

I tried the following, expecting the most recent code made in both databases to be outputted:

SET @investment_code = 'ABC[0-9]+';

SELECT 
    investment_name, 
    i.service_client_id, 
    currency_symbol, 
    investment_code C_investment_codes
FROM client.investments i
LEFT JOIN client.currencies c
    ON i.currency_id = c.id
WHERE i.investment_code COLLATE utf8mb4_unicode_ci LIKE @investment_code
ORDER BY investment_code DESC
LIMIT 1;

SELECT 
`key`, 
service_client_id, 
`value` SD_investment_codes
FROM client_data.standing_data sd
WHERE sd.`value` COLLATE utf8mb4_unicode_ci LIKE @investment_code
ORDER BY `value` DESC
LIMIT 1;

This resulted in a blank output. When I use SET @investment_code = 'ABC%'; I get results, but I specifically want to set the parameter for digits to follow ABC. This is my expected output:

C_investment_codes SD_investment_codes
ABC109 ABC109

Solution

  • In MySQL, the LIKE operator does not support regular expressions directly. Instead, you can use the % wildcard to match any sequence of characters.

    For your script, you can leverage the REGEXP operator available in MySQL, which allows you to use regular expressions. Here's an example

    SET @investment_code = '^ABC[0-9]+$';
    
    SELECT 
        investment_name, 
        i.service_client_id, 
        currency_symbol, 
        investment_code AS C_investment_codes
    FROM client.investments i
    LEFT JOIN client.currencies c
        ON i.currency_id = c.id
    WHERE i.investment_code REGEXP @investment_code
    ORDER BY investment_code DESC
    LIMIT 1;
    
    table
    SELECT 
        `key`, 
        service_client_id, 
        `value` AS SD_investment_codes
    FROM client_data.standing_data sd
    WHERE sd.`value` REGEXP @investment_code
    ORDER BY `value` DESC
    LIMIT 1;