1

I have a query like:

SELECT (column LIKE 'string')+100

It returns ERROR: operator does not exist: boolean + integer

I couldn't find a function to convert bool to int, there is only text to int: to_number().

Is there a way to resolve this issue?

4
  • 1
    What do you want the boolean true or boolean false to be casted as? Commented Feb 16, 2013 at 19:18
  • Both, it depends on result of clause between (). I need to get integer - 0 or 1. Commented Feb 16, 2013 at 19:23
  • 1
    does (column like 'string')::integer + 100` work? otherwise use CASE WHEN .. THEN Commented Feb 16, 2013 at 19:44
  • thanx a lot @vol7tron, ::integer worked well for me! :) Commented Feb 16, 2013 at 19:49

4 Answers 4

1

Use Conditional Expressions, see http://www.postgresql.org/docs/9.2/static/functions-conditional.html

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

Comments

1

If you want to convert a string comparison to 1 when true and 0 when false, you could use a case statement:

select case when column like '%foo%' then 1 else 0 end as my_int from my_table;

If you wanted to add to that result, you would do something like:

select (case when column like '%foo%' then 1 else 0 end) + 100 as my_int from my_table;

1 Comment

I don't believe so, but if for some reason you find you need to do this kind of thing often, you could put it in a function: create function matches(text, text) RETURNS integer AS $$ select case when $1 like $2 then 1 else 0 end $$ LANGUAGE SQL; Then your sql would be select matches(column, '%foo%') + 100 from my_table
1
SELECT (column LIKE 'string')::integer +100

2 Comments

Could you provide a reference for ::integer?
@Mansoor, check section 4.2.9 of docs.
1

I needed more portable solution, so this one suits me the best:

SELECT CAST((column LIKE 'string') AS integer)+100

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.