Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a row exists or not in postgresql

Tags:

postgresql

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.

like image 863
Ashwin Avatar asked Jun 30 '12 13:06

Ashwin


People also ask

Is exists in Postgres?

In PostgreSQL, the EXISTS operator is used to test for the existence of rose in a subquery.It is generally used with correlated subqueries. If the subquery returns at least one row, the result of EXISTS is true. In case the subquery returns no row, the result is of EXISTS is false.

What is Upsert in PostgreSQL?

The UPSERT statement is a DBMS feature that allows a DML statement's author to either insert a row or if the row already exists, UPDATE that existing row instead. That is why the action is known as UPSERT (simply a mix of Update and Insert).

How do I get out of Postgres prompt?

Type \q and then press ENTER to quit psql . As of PostgreSQL 11, the keywords " quit " and " exit " in the PostgreSQL command-line interface have been included to help make it easier to leave the command-line tool.


1 Answers

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=?);
like image 189
Tometzky Avatar answered Sep 19 '22 10:09

Tometzky