Fastest check if row exists in PostgreSQL
Use the EXISTS key word for TRUE / FALSE return:
select exists(select 1 from contact where id=12)
Check if a row exists or not in postgresql
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=?);
PL/pgSQL checking if a row exists
Simpler, shorter, faster: EXISTS
.
IF EXISTS (SELECT FROM people p WHERE p.person_id = my_person_id) THEN
-- do something
END IF;
The query planner can stop at the first row found - as opposed to count()
, which scans all (qualifying) rows regardless. Makes a big difference with big tables. The difference is small for a condition on a unique column: only one row qualifies and there is an index to look it up quickly.
Only the existence of at least one qualifying row matters. The SELECT
list can be empty - in fact, that's shortest and cheapest. (Some other RDBMS don't allow an empty SELECT
list on principal.)
Improved with @a_horse_with_no_name's comments.
Efficient way to check if row exists for multiple records in postgres
You just want a left outer join:
SELECT
A.id as id, count(B.foreing_id) as cnt
FROM A
LEFT OUTER JOIN B ON
A.id = B.foreing_id
GROUP BY A.id
failed to check if row with value exists In Postgres with Golang
Why not just a unique index on your users table?
CREATE UNIQUE INDEX unq_uuid ON users (uuid);
Then you don't have to check, you just try to insert and it will return an error if it already exists.
check if row exists with specific value
One simple solution uses aggregation:
SELECT
t.taskid,
t.name
FROM task t
INNER JOIN taskattributes ta
ON t.taskid = ta.taskid
GROUP BY
t.taskid,
t.name
HAVING
COUNT(CASE WHEN "key" = 'A' THEN 1 END) = 0;
If you are using Postgres 9.4 or later, you may use FILTER
in the HAVING
clause:
HAVING COUNT(*) FILTER (WHERE "key" = 'A') = 0
Related Topics
How to Calculate a Running Total in SQL Without Using a Cursor
How to Prevent a Database Trigger from Recursing
Oracle -- Split Multiple Comma Separated Values in Oracle Table to Multiple Rows
SQL Server Convert Integer to Binary String
Postgresql Equivalent for Top N with Ties: Limit "With Ties"
The New Pivot Function in Bigquery
Concatenate Results from a SQL Query in Oracle
Compute Percents from Sum() in the Same Select SQL Query
Insert Command :: Error: Column "Value" Does Not Exist
How to Design a Database for User Defined Fields
How to Create a Copy of an Oracle Table Without Copying the Data
Select Data from Date Range Between Two Dates
Dynamic Sorting Within SQL Stored Procedures
Add Unique Constraint to Combination of Two Columns
Transfer Data from One Database to Another Database
How to Return Multiple Rows from the Stored Procedure? (Oracle Pl/Sql)