In SQL, how can we match using LIKE up to but not exceeding a number of wildcard characters?

In SQL, how can we match using LIKE up to but not exceeding a number of wildcard characters?



E.g. in regex, we can use n,m to specify that we want to match the previous element at least n times, but no more than m times.



Is there a way to do this in SQL (specifically sqlite) whereby we match a wildcard '_' up to 5 times but no more?



E.g. I want up to 5 characters between the letters j and z



So I would get Jaz or Jaaaaaz but not Jaaaaaaz



Thanks!





Did one of these answers solve your problem? If so, please mark the answer accepted (the green arrow underneath the up/down vote arrows). Otherwise, can you provide more information to help solve the problem. See stackoverflow.com/help/someone-answers
– Nick
Aug 30 at 2:43




2 Answers
2



To answer your specific question, you could just use


WHERE col LIKE 'J%z' AND LENGTH(col) < 8



e.g.


SELECT 'Jaaaz' LIKE 'J%z' AND LENGTH('Jaaaz') < 8, 'Jaaaaaaz' LIKE 'J%z' AND LENGTH('Jaaaaaaz') < 8



Output


1 0





Very clever, thanks!
– user1487547
Aug 30 at 18:01



You can add a regexp module into SQLite. That is probably the best solution to your problem.



You can do what you want as:


where col not like '______' -- 6 underscores



Or, more simply:


when length(col) < 6



That is the direct answer to your question.



EDIT:



For up to five characters, you can do:


where col like 'j%z' and
col not like 'j______z'



Or use the more brute force:


where col like 'jz' or
col like 'j_z' or
col like 'j__z' or
col like 'j___z' or
col like 'j____z' or
col like 'j_____z'



If you want these patterns within a string (rather than the whole string), then include % at the beginning and end of the pattern.


%





It'd have to be not like '%______%' because the LIKE predicate implicitly matches the whole string, unlike regular expressions.
– Bill Karwin
Aug 28 at 23:47


not like '%______%'





Thanks Gordon, Bill. I edited my question to be more clear. I am looking for between 0 and 5 wildcards between a series of characters. E.g. I want up to 5 characters between the letters j and z So I would get Jaz or Jaaaaaz but not Jaaaaaaz
– user1487547
Aug 28 at 23:58







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế