How do I execute/run a .sql file in PostgreSQL 9.2.6 + CentOs

20

8

I would like to know how to execute a .sql file in PostgreSQL. I'm using CentOs 6.4.

I have created a database and just need to run a script given to me to create tables.

Thanking you in advance.

Linux NewB

Posted 2014-01-14T09:24:54.970

Reputation: 572

Answers

32

Use psql:

psql -f thefile.sql targetdatabase

You may need to specify additional parameters, like username to connect as, host to connect to, etc.

Craig Ringer

Posted 2014-01-14T09:24:54.970

Reputation: 2 630

1Hi Craig, I was successful in running the script using the following command: psql -U username -d database -a -f directory/name of file Thanks, – Linux NewB – 2014-01-15T10:16:04.937

19

If you already logged in to database then you can use meta commands like

db=# \i or \include filename

For more info see doc

Shiva

Posted 2014-01-14T09:24:54.970

Reputation: 291

This answer was surprisingly hard to find on the Internet! – Joel Cross – 2018-05-30T11:17:01.740

5

I am adding this it might be useful who try to execute *.sql place where PostgreSQL server located in a difference place.

   psql -h localhost -d userstoreis -U admin -p 5432 -a -q -f /home/jobs/Desktop/resources/postgresql.sql

These are the usage of each parameter

-h PostgreSQL server IP address
-d database name
-U user name
-p port which PostgreSQL server is listening on
-f path to SQL script

then you are prompted to enter the password of the user.

GPrathap

Posted 2014-01-14T09:24:54.970

Reputation: 151

0

My solution on mac: I have to use "" with psql. I ran this with vscode terminal

I learned this from the postgreSQL's runpsql.sh

"/Library/PostgreSQL/11/bin/psql" -h "localhost" -p "9000" -U "username" "database" -f data.sql

Jixuan Cheng

Posted 2014-01-14T09:24:54.970

Reputation: 1