0

I asked SO for a query to find all rows in a table with a 'code' entry that is a substring of the search string, with the added condition that it appears at the end of the search string.

So a query for '12345' should return '2345', '345', '45', and '5'.

I was given this answer, which works. I have read through the documentation but still don't understand the query. Can someone please explain

SELECT * from yourtable
where '12345' like '%' || Code
2
  • See the documentation of Postgres matching functions, or any decent sql documentation on the like operator. Commented Nov 19, 2019 at 21:21
  • I've read the documentation but still don't understand, which is why I was hoping for a walkthrough of this particular query to aid my understanding Commented Nov 19, 2019 at 21:24

2 Answers 2

3

Normally a LIKE is used in the opposite way.

For example:

SELECT * FROM SomeTable
WHERE SomeColumn LIKE '%xxx%'  

So you check if the column matches against a fixed string with a pattern.

But the clever thing about that answer was it did the opposite.

It checks a fixed string again a pattern that's created from a column.

SELECT * FROM SomeTable
WHERE 'bar456' LIKE '%' || SomeColumn;

In this example, if "SomeColumn" contains the value "56"?
Then '%' || SomeColumn forms the string '%56'

So 'bar456' is like '%56', since it ends with '56'
And 'bar456' is also like '%ar456'

Sign up to request clarification or add additional context in comments.

1 Comment

Much better explanation than mine: kudos!
1

There are two relevant documentation links you need:

  1. PostgreSQL Pattern Matching: '12345' like '%'

  2. PostgreSQL CONCATENATE(||) Operator: <match> || Code

The SQL means:

  1. Fetch all columns from the table
  2. IF column "code" is equal to <match> + <value of "code" column>

1 Comment

Thank you so much! I dont know why everyone else was so reluctant to give this simple explanation

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.