1

So let's say I have a function that takes in one parameter

create function(i_param VARCHAR)

I want to do a select one the table WHERE col_name LIKE 'i_param%'

I tried doing LIKE i_param||'%' but I think it literally returns the string 'i_param' not the value put into the function.

It doesn't give me any errors but returns zero rows. How would I do a LIKE on the input parameter?

Pretty new to this stuff, so any help would be great! Thanks!

4
  • 1
    Regarding the number of matches - note that the Postgres' LIKE is case-sensitive. Commented Apr 12, 2011 at 7:25
  • If LIKE i_param||'%' is not working than you are not showing us everything. Can you post a complete example that shows that it is not working? Commented Apr 12, 2011 at 8:37
  • Thanks I didnt realize that LIKE was case sensitive. I just found out about ILIKE which isn't so I will use that instead. Commented Apr 12, 2011 at 14:49
  • It worked by changing to the following LIKE $1||'%' Commented Apr 12, 2011 at 18:33

1 Answer 1

2

As a note, starting in 9.2, you can do things the way you are. In previous versions, you should get an error instead.

The fact that you didn't get an error suggests that your use of i_param is in colliding with a column name. I recommend prefixing input variables for this reason (I use "in_" in my work).

For example, if you:

CREATE TABLE foo (
   foo text,
   bar text
);

Then the following will not generate an error:

CREATE FUNCTION search_foo(bar text) RETURNS SETOF foo LANGUAGE SQL AS $$

SELECT * FROM foo WHERE foo ilike bar || '%';

$$;

However this will in fact be comparing the column foo against the column bar. The following will give you errors:

CREATE FUNCTION search_foo(in_bar text) returns setof foo language sql as $$

SELECT * from foo where foo ilike in_bar ||'%';

$$;

I highly recommend avoiding variables with the same names as arguments. That leads to problems in many places.

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

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.