How to execute SQL commands from a file in PostgreSQL

2 Comments

In my case I had a .sql file with hundreds of insert statements and I wanted to run all of them, I was left with two options namely manually entering every command via copy and paste or executing the file. I went for the second option and it worked. I used Postgres 8.4 on the command line on a Ubuntu machine.

Answer:

Follow these steps

  • Connect to the relevant database eg.
    sudo -u postgres psql MYDB
  • Then run
    \i MYFILEWITHCOMMANDS.sql

    \i means execute commands from file

  • All commands will be executed.

Image Credits: Photo by Isis França on Unsplash.

Related Articles

No results found.

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
zachMeghashyam Chirravoori Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Meghashyam Chirravoori
Guest
Meghashyam Chirravoori

Thanks, this really did help me!

zach
Guest
zach

you can also use

pg -U <user> <db> -f <filename>

if you don’t need to stay in the pg command line

Menu