Search code examples
sqlquery-optimizationprefix

How to write an SQL query to get rows with the same prefix


everyone;

I am working on a database where path information are stored, one simplified table is shown below

path_id | path value
1         //a/b/c/d
2         //a/b/e
3         //a/b
4         //a/bcd

So here is the question, how can I get information where has '//a/b' as the prefix? In this case, the result should be:

path_id | path value
1         //a/b/c/d
2         //a/b/e
3         //a/b

I am seeking for a more elegant and optimized query, other than using logic operators like 'OR'. Thanks.


Solution

  • SELECT * FROM YourTable WHERE path_value like '//a/b/%' OR path_value = '//a/b' 
    

    Note the extra slash before the wild card in the first part of the WHERE statement. This will exclude //a/bcd.