Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Like and greater than Function

I have a dataset like below:

table_a

Product_Name      Product_Orders
    game_296                   1
    game_298                   2
    game_299                   4
    300_game                   6
    xyz_game                   9
    game-tyw                  12

How do I do use a like function in SQL and combine with a greater than? My overall goal is to filter games that are greater than a certain number like 297.

I would ideally like to do something like this:

select * from table_a
where Product_Name > ilike %297%

The expected output here would be this:

Product_Name      Product_Orders
    game_298                   2
    game_299                   4
    300_game                   6
like image 368
Nick Knauer Avatar asked Apr 06 '26 17:04

Nick Knauer


2 Answers

One way would be to remove all non-digits from the string and then do the comparison:

where cast(regexp_replace(product_name, '[^0-9]', '') as int) > 297
like image 112
Gordon Linoff Avatar answered Apr 08 '26 06:04

Gordon Linoff


Try this:

-- your input ....
WITH
indata(Product_Name,Product_Orders) AS (
          SELECT 'game_296', 1
UNION ALL SELECT 'game_298', 2
UNION ALL SELECT 'game_299', 4
UNION ALL SELECT '300_game', 6
UNION ALL SELECT 'xyz_game', 9
UNION ALL SELECT 'game-tyw',12
)
-- real query starts here ...
SELECT
  product_name
, product_orders
FROM indata
WHERE CAST(REGEXP_SUBSTR(product_name,'\d+') AS INTEGER) > 297;
-- out  product_name | product_orders 
-- out --------------+----------------
-- out  game_298     |              2
-- out  game_299     |              4
-- out  300_game     |              6
-- out (3 rows)
like image 42
marcothesane Avatar answered Apr 08 '26 05:04

marcothesane