Skip to content
Advertisement

Truncate if exists in psql function and call function

I have the following code to create a function that truncates all rows from the table web_channel2 if the table is not empty:

Unfortunately I don’t know how should I continue … How to execute the function?

Advertisement

Answer

TLDR

To execute a Postgres function (returning void), call it with SELECT:

Proper solution

… how should I continue?

Delete the function again.

It does not offer any way to schema-qualify the table. Using it might truncate the wrong table …

Looks like you are trying to avoid an exception if the table is not there.

And you only want to truncate …

if the table is not empty

To that end, I might use a safe function like this:

To execute, call it with SELECT:

If no schema is provided, the function falls back to traversing the search_path – like your original did. If that’s unreliable, or generally, to be safe (which seems prudent when truncating tables!) provide the schema explicitly:

db<>fiddle here

When providing identifiers as strings, you need to use exact capitalization.

Why the custom variable _row_found instead of FOUND? See:

Basics:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement