Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: SELECT with equals before LIKE

Tags:

sql

select

sqlite

I need to query a SQLite database for items that either match a given string, or are LIKE query%. However, it's not as simple as

SELECT id, type, number FROM roads WHERE number = '12' OR number LIKE '12%'

I need all equal matches to come before the LIKE matches. I picture there being an AS in there somewhere and ordering by it, but I'm not sure how it would work. I want to avoid making two queries if possible.

like image 532
Jonah Avatar asked Apr 03 '26 03:04

Jonah


2 Answers

SELECT id, type, number
FROM roads 
WHERE number = '12' OR number LIKE '12%'
ORDER BY CASE WHEN number = '12' THEN 0 ELSE 1 END, number
like image 177
Cade Roux Avatar answered Apr 08 '26 04:04

Cade Roux


I'm not sure if this syntax is supported on Sqlite, but here's an idea:

SELECT id, type, number FROM roads WHERE number LIKE '12%'
ORDER BY
   CASE
      WHEN number = '12' THEN 0
      ELSE 1
   END
like image 31
dcp Avatar answered Apr 08 '26 06:04

dcp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!