AW: Truncate data from whole cluster

From: "Dischner, Anton" <Anton(dot)Dischner(at)med(dot)uni-muenchen(dot)de>
To: "'depesz(at)depesz(dot)com'" <depesz(at)depesz(dot)com>, Rajesh Kumar <rajeshkumar(dot)dba09(at)gmail(dot)com>
Cc: Pgsql-admin <pgsql-admin(at)lists(dot)postgresql(dot)org>
Subject: AW: Truncate data from whole cluster
Date: 2023-12-20 11:39:40
Message-ID: e087df8b0c194a5fa64c625a9cf9cdee@med.uni-muenchen.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-admin

Hi all,

if you ask Bard LLM do do this you get:

#!/bin/bash

# List all databases in the PostgreSQL instance databases=$(psql -t -c "SELECT datname FROM pg_database;")

# Truncate table data for each database
for database in $databases; do
echo "Processing database '$database'..."
psql -d $database -c "SET FOREIGN_KEY_CHECKS=0;"
tables=$(psql -d $database -t -c "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = 'public';")
for table in $tables; do
echo "Truncating table '$table' in database '$database'..."
psql -d $database -c "TRUNCATE TABLE $table;"
done
psql -d $database -c "SET FOREIGN_KEY_CHECKS=1;"
done

This may be a good script to start.
You will definetly test this first on a test installation!

Best,

Anton

-----Ursprüngliche Nachricht-----
Von: depesz(at)depesz(dot)com <depesz(at)depesz(dot)com>
Gesendet: Mittwoch, 20. Dezember 2023 11:24
An: Rajesh Kumar <rajeshkumar(dot)dba09(at)gmail(dot)com>
Cc: Pgsql-admin <pgsql-admin(at)lists(dot)postgresql(dot)org>
Betreff: Re: Truncate data from whole cluster

On Wed, Dec 20, 2023 at 02:35:52PM +0530, Rajesh Kumar wrote:
> Hi all,
>
> I am using postgres 15.2. one leader and one replica. I have multiple
> dbs and multiple tables. I want to keep definitions and only want to
> delete 'data only' from all dbs and tables.
>
> Any command to do that instead of truncating all tables one by one?

No such command exists. For starters, no command in SQL can do stuff in other databases than the one you are connected to.

You can write a simple one-liner that will do it, in your shell.
shouldn't be really complex - get list of dbs, and in each db connect with psql and truncate all tables. basically: `psql | xargs psql`

depesz

In response to

Responses

Browse pgsql-admin by date

  From Date Subject
Next Message hubert depesz lubaczewski 2023-12-20 11:50:31 Re: AW: Truncate data from whole cluster
Previous Message hubert depesz lubaczewski 2023-12-20 10:23:41 Re: Truncate data from whole cluster