1

I would like to know how to rename a database with the current date

thanks for your help

1

1 Answer 1

4

You may use dynamic SQL in aDO block. Here I use a date suffix in YYYYMMDD format for the database name.

knayak=# CREATE DATABASE mydatabase;
CREATE DATABASE

DO $$
BEGIN

 EXECUTE format('ALTER DATABASE %I RENAME TO %I_%s', 'mydatabase','mydatabase',
                               to_char(current_date,'YYYYMMDD')::TEXT);
END
$$;

knayak=#
knayak=# \l mydatabase*
                                    List of databases
        Name         | Owner  | Encoding |   Collate   |    Ctype    | Access privileges
---------------------+--------+----------+-------------+-------------+-------------------
 mydatabase_20181214 | knayak | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
(1 row)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your help, I got this Error message: ERROR: syntax error at or near "_20181214" LINE 1: ALTER DATABASE "mydb" RENAME TO "mydb"_20181214 ^ QUERY: ALTER DATABASE "mydb" RENAME TO "mydb"_20181214 CONTEXT: PL/pgSQL function inline_code_block line 4 at EXECUTE SQL state: 42601 Am I missing something?
@DanielCampeão : Remove the double quotes, you don't need it
First I created a database and named it "mydb" This is how it looks my Query [DO $$ BEGIN EXECUTE format('ALTER DATABASE %I RENAME TO %I_%s', 'mydb','mydb', to_char(current_date,'YYYYMMDD')::TEXT); END $$;] Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.