21

I have seen many posts about this in SO. But I could not get an answer. I want to the query to check if a particular row exists or not in a table. If it exists, it should return me a string true and stop the search there itself and if not return false.

1
  • 2
    What have you tried? How do you specify the row? By rowid or the values of all attributes? Does it have to be a query or is a PL/SQL function acceptable as well? Commented Jun 30, 2012 at 13:37

2 Answers 2

61
select
  case when exists (select true from table_name where table_column=?)
    then 'true'
    else 'false'
  end;

But it would be better to just return boolean instead of string:

select exists (select true from table_name where table_column=?);
Sign up to request clarification or add additional context in comments.

Comments

-17

Spoiler:

-- EXPLAIN ANALYZE
WITH magic AS (
        WITH lousy AS ( SELECT * FROM one  WHERE num = -1)
        SELECT 'True'::text AS truth
        WHERE EXISTS  (SELECT * FROM lousy)
        UNION ALL
        SELECT 'False'::text AS truth
        WHERE NOT EXISTS (SELECT * FROM lousy)
        )
SELECT *
FROM magic
        ;

11 Comments

It was intended as a spoiler. The OP is definitely homework, and shows no effort.
What you wrote is gibberish even for me. You don't tutor providing an deliberately obfuscated example that is working but The Daily WTF worthy. You could for example point to documentation of case and exists, as it is useful only for somebody that knows what to look for.
It does work, and produces the correct result. Let the OP explain it to his teacher. And he could look up the syntax for case and exists himself, too. Or for the CTE.
-1 Other people besides the OP read this answer trying to solve their own similar problems.
Please note that the OP dis not show any effort, whatsoever. This is just a gimmethecodez question, which can be anwered by anybode sufficiently fluent in SQL (there might even be more methods to get to the same goal than just these two answers)
|

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.