patternsqlMinor
SQL - find records that are prefixes of my string
Viewed 0 times
prefixessqlarerecordsthatfindstring
Problem
I have a table with a column named
How can I do it in Postgres?
I tried
but it does not match.
prefix storing 'aaaa'. My application has a long string, eg. 'aaaabbbbccccdddd'. I want to select all rows in which a particular column is a prefix of 'aaaabbbbccccdddd'. The length of the prefix is variable.How can I do it in Postgres?
I tried
SELECT * FROM my_table WHERE '%' || prefix || '%' ILIKE 'aaaabbbbccccdddd'but it does not match.
Solution
First, your way of using
So, string first, pattern second.
Furthermore, as you are after prefixes only, the starting wildcard is not needed. Something like this should work:
A small proof of this:
[I]LIKE is wrong:string LIKE patternSo, string first, pattern second.
Furthermore, as you are after prefixes only, the starting wildcard is not needed. Something like this should work:
SELECT * FROM my_table WHERE 'aaaabbbbccccdddd' ILIKE prefix || '%';A small proof of this:
WITH my_table (prefix) AS (
VALUES ('abcde'),
('abcd'),
('abcE'),
('bcde')
)
SELECT * FROM my_table WHERE 'abcdefghijkl' ILIKE prefix || '%';
prefix
────────
abcde
abcdCode Snippets
string LIKE patternSELECT * FROM my_table WHERE 'aaaabbbbccccdddd' ILIKE prefix || '%';WITH my_table (prefix) AS (
VALUES ('abcde'),
('abcd'),
('abcE'),
('bcde')
)
SELECT * FROM my_table WHERE 'abcdefghijkl' ILIKE prefix || '%';
prefix
────────
abcde
abcdContext
StackExchange Database Administrators Q#149630, answer score: 8
Revisions (0)
No revisions yet.