Search code examples
regexsqlitesql-like

How to match a string using a list of characters in SQLite


i have a problem working with SQLite especially like statement. I want to retrieve data from a table where a varchar column is composed of list of characters given by the user.

For example:

If the user passes in awnxov I would want words that have those letters to match, like won and wax that might be in my table.


Solution

  • From your comment, you want to provide a list of letters and find all words that match. You can't do this with LIKE.

    You can, however, use REGEXP. But to use it, you'll need to install a regexp lib or write your own regexp function and provide a callback.

    If you are using Ubuntu:

    sudo apt-get install sqlite3-pcre
    

    Or you can install from the github page here.

    Then when you run sqlite, you need to execute to load the regexp() function:

    .load /usr/lib/sqlite3/pcre.so
    

    (or wherever the lib is)

    Finally you can do something like:

    SELECT word
    FROM   table
    WHERE  word REGEXP '^[awnxov]+$'
    

    Or any other PCRE that you think matches.

    This probably won't perform well. It'll be a scan of all the data most likely. Depending on how much data there is, and how many letters you receive as input, you might want to just create an index and search for each two letter combinations and do a check in code to see if it passes or not.

    Good luck