0
0
PostgresqlHow-ToBeginner · 3 min read

How to Use PERFORM in PL/pgSQL: Syntax and Examples

In PL/pgSQL, use PERFORM to execute a query when you do not need to capture its result. It runs the query for its side effects, such as calling a function or updating data, without returning any rows.
📐

Syntax

The PERFORM statement executes a query but ignores any returned rows. It is useful when you want to run a query for its side effects only.

Syntax:

PERFORM query_expression;

Here, query_expression is any valid SQL query that returns rows, but PERFORM discards the output.

sql
PERFORM query_expression;
💻

Example

This example shows how to use PERFORM to call a function that updates data without returning any result to the PL/pgSQL block.

sql
CREATE OR REPLACE FUNCTION update_counter() RETURNS void AS $$
BEGIN
  PERFORM pg_sleep(1); -- simulate delay
  UPDATE counters SET count = count + 1 WHERE id = 1;
END;
$$ LANGUAGE plpgsql;

-- Assuming table counters(id int primary key, count int) exists

-- Call the function
SELECT update_counter();
Output
update_counter ---------------- (1 row)
⚠️

Common Pitfalls

1. Using PERFORM when you need the query result: PERFORM discards results, so if you need data, use SELECT INTO instead.

2. Forgetting PERFORM for function calls: Calling a function that returns a value without PERFORM or SELECT INTO causes a warning.

sql
/* Wrong: calling function without PERFORM or SELECT INTO */
SELECT my_function(); -- Warning if result unused

/* Correct: use PERFORM to ignore result */
PERFORM my_function();

/* Or capture result */
SELECT my_function() INTO result_var;
📊

Quick Reference

UsageDescription
PERFORM query;Execute query, ignore returned rows
PERFORM function_call();Call function ignoring return value
SELECT ... INTO var;Execute query and store result in variable
Use PERFORM for side-effect queriesWhen you don't need query output

Key Takeaways

Use PERFORM in PL/pgSQL to run queries when you don't need their results.
PERFORM discards any rows returned by the query, running it only for side effects.
If you need query results, use SELECT INTO instead of PERFORM.
Always use PERFORM when calling functions whose return values you want to ignore.
Avoid warnings by not calling functions without PERFORM or SELECT INTO.