7

I am running the following sql query in my web app:

SELECT EXISTS (
SELECT id
FROM user
WHERE membership=1244)

i was expecting true (boolean data) as the result but I'm getting 't' or 'f' for false. How do I get it to return to my lua code a standard boolean?

I found the following post:

Reading boolean correctly from Postgres by PHP

And so I tried to change my code to something like this:

SELECT EXISTS ::int (
SELECT id
FROM user
WHERE membership=1244)

or

SELECT ::INT (SELECT EXISTS (
SELECT id
FROM user
WHERE membership=1244))

But I'm getting a syntax error.
Can you tell the best way to handle this? Should I be casting the resulting 't' to a boolean somehow? or is there a way to tell postgresql to return true / false instead of 't'/'f'?

Thanks.

4 Answers 4

28

You are so close

SELECT EXISTS (SELECT id FROM user WHERE membership=1244)::int 
Sign up to request clarification or add additional context in comments.

2 Comments

In Postgres 9.1.9, it works fine. See the sqlfiddle.com/#!1/bfe1e/2 Also, a 0 or 1 for PHP works as boolean
No problem. You gave me an excuse to use sqlfiddle. Which I just learned about today, so I'm excited. :)
8

Your first query do indeed return a boolean. A t is shown as the returned value of the query

select exists (select 1);
 exists 
--------
 t

But if you check its type it is a boolean:

select pg_typeof(exists (select 1));
 pg_typeof 
-----------
 boolean

You will have to check with the lua's postgresql driver manual how to properly handle it.

Comments

5

Try it with CASE

select       
  (case when exists (SELECT id FROM user WHERE membership = 1244)
    then 1 
    else 0 
  end) as column;

my test fiddle

Comments

0

Your initial query is fine by itself:

SELECT id FROM user WHERE membership=1244

You just need to check if it returns a row or not.

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.