3

Let's say I have a column called 'code' in my database table containing string data types.

I want a query that will return all rows with a 'code' value that is a substring of a given search string, with the added condition that the substring appears at the end of the search string.

For example, if the search string is '12345', the query should return all rows with a 'code' value of:
12345
2345
345
45
5

2 Answers 2

6

Simply use like operator:

SELECT * from yourtable
where '12345' like '%' || Code 
Sign up to request clarification or add additional context in comments.

2 Comments

Genius! But I would add and code != '' otherwise the blank string will match too (probably not what the OP wants)
2

You can use a recursive CTE:

with recursive cte as (
      select code
      from yourtable t
      union all
      select substring(code, 2)
      from cte
      where code > ''
     )
select *
from cte;

Or, you could use a lateral join and generate_series():

select substring(code, i)
from t cross join lateral
     generate_series(1, length(code)) gs(i)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.