755

I have some .sql files with thousands of INSERT statements in them and need to run these inserts on my PostgreSQL database in order to add them to a table. The files are that large that it is impossible to open them and copy the INSERT statements into an editor window and run them there. I found on the Internet that you can use the following by navigating to the bin folder of your PostgreSQL install:

psql -d myDataBase -a -f myInsertFile

In my case:

psql -d HIGHWAYS -a -f CLUSTER_1000M.sql

I am then asked for a password for my user, but I cannot enter anything and when I hit enter I get this error:

psql: FATAL: password authentication failed for user "myUsername"

Why won't it let me enter a password. Is there a way round this as it is critical that I can run these scripts?

I got around this issue by adding a new entry in my pg_hba.conf file with the following structure:

# IPv6 local connections:
host    myDbName    myUserName ::1/128    trust

The pg_hba.conf file can usually be found in the 'data' folder of your PostgreSQL install.

3
  • 9
    You've already had your answer but just in case... "I cannot enter anything", might you be talking about the fact that typing your password doesn't show anything? That's normal in this case, normally typing the password and hitting Enter should work... Aug 24, 2014 at 20:12
  • I had a similar problem installing a copy of ITIS (itis.gov). The database didn't exist, so I couldn't use its name. Because of the way PostgreSQL works, I could do this: psql --port=5554 --username=root --file=ITIS.sql template1 Jan 16, 2015 at 15:40
  • Does this answer your question? How do I specify a password to 'psql' non-interactively?
    – rogerdpack
    Mar 12, 2021 at 18:30

18 Answers 18

716

Of course, you will get a fatal error for authenticating, because you do not include a user name...

Try this one, it is OK for me :)

psql -U username -d myDataBase -a -f myInsertFile

If the database is remote, use the same command with host

psql -h host -U username -d myDataBase -a -f myInsertFile
4
  • 4
    Note that the provided username has to be a valid postgres role. The default is the currently logged in user. Oct 5, 2012 at 17:29
  • 27
    Why the -a param? Feb 6, 2018 at 9:19
  • 18
    @AlikElzin-kilaka -a is not needed here. It's "Print all nonempty input lines to standard output as they are read"
    – mjspier
    Feb 26, 2018 at 21:16
  • Is it possible to specify an sql file that is stored at a url? For instance in an s3 bucket @ my-bucket.s3.eu-west-2.amazonaws.com/import.sql ? Jul 6 at 9:24
453

You should do it like this:

\i path_to_sql_file

See:

Enter image description here

5
  • 4
    I get Permission denied
    – Zac
    Mar 23, 2017 at 15:11
  • 6
    after doing chmod 777 myfile error Permission denied was fixed
    – Ulug'bek
    Apr 10, 2017 at 12:39
  • 16
    @Zac if your Permission denied happened on a windows machine, you might be using the wrong slashes. Jun 13, 2018 at 9:00
  • 6
    I had this error on windows and it turned out to be the slashes, as @pgsandstrom mentioned. Wrong slashes = use forward slashes instead, and no quote on path. \i c:/dev/script.sql
    – Dave
    Oct 28, 2019 at 1:01
  • I am getting No such file or directory although the file path has been specified correctly.Any idea? Jun 16 at 5:29
193

You have four choices to supply a password:

  1. Set the PGPASSWORD environment variable. For details see the manual:
    http://www.postgresql.org/docs/current/static/libpq-envars.html
  2. Use a .pgpass file to store the password. For details see the manual:
    http://www.postgresql.org/docs/current/static/libpq-pgpass.html
  3. Use "trust authentication" for that specific user: http://www.postgresql.org/docs/current/static/auth-methods.html#AUTH-TRUST
  4. Since PostgreSQL 9.1 you can also use a connection string:
    https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
3
  • Hi. I have now set the settings to trust but I notice that the software is trying to use my windows username in order to login. I want to use a role that I have setup in my Postgresql database. Is there a way of telling it which role to use to run the command?
    – CSharpened
    Mar 16, 2012 at 11:17
  • 2
    @CSharpened: use the -u parameter as documented in the manual
    – user330315
    Mar 16, 2012 at 11:18
  • 1
    #2 is extremely simple. Just add one line containing host:port:db:user:pass to a file and you're done. Nice work.
    – Kriil
    Jun 17, 2016 at 14:23
85

If you are logged in into psql on the Linux shell the command is:

\i fileName.sql

for an absolute path and

\ir filename.sql

for the relative path from where you have called psql.

2
  • As @Florian says, once logged in you can execute a file. Remember to mark any comment lines in your SQL as either of two ways ...-- comment to end of line a) -- one line comment OR b) /* multiple line comments */
    – Sumit S
    Mar 19, 2020 at 0:45
  • 1
    Wow, thank you very much, it ran very well. Jun 27, 2022 at 23:25
81

Use this to execute *.sql files when the PostgreSQL server is located in a difference place:

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

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

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

EDIT: updated based on the comment provided by @zwacky

2
  • 8
    @ChickenWing24 -a: all echo, -q: quiet, -f: file Nov 2, 2016 at 23:25
  • 1
    does this work without database? I'm trying to create new database using this tool into existing server. Nov 10, 2021 at 8:16
56
export PGPASSWORD=<password>
psql -h <host> -d <database> -U <user_name> -p <port> -a -w -f <file>.sql
3
  • 1
    how can I do that without output
    – Lu32
    Feb 8, 2016 at 19:42
  • 2
    psql -h <host> -d <database> -U <user_name> -p <port> -a -q -w -f <file>.sql
    – vishu9219
    Feb 10, 2016 at 7:43
  • 3
    @Lu32 You could also leave out the flag -a (which means "Print all nonempty input lines to standard output as they are read"). EDIT tested, without -a it prints out less, but still too much information. So the -q flag is correct, as vishu9219 said. Feb 17, 2016 at 12:14
30

Via the terminal log on to your database and try this:

database-# >@pathof_mysqlfile.sql

or

database-#>-i pathof_mysqlfile.sql

or

database-#>-c pathof_mysqlfile.sql
2
  • this solution is more solid as for me; not the one marked as answe
    – AlexHalkin
    Dec 14, 2014 at 15:25
  • Is there any difference between @, -i and -c ?
    – Chris
    Dec 22, 2022 at 5:22
28

You can give both user name and PASSSWORD on the command line itself with the "-d" parameter

   psql -d "dbname='urDbName' user='yourUserName' password='yourPasswd' host='yourHost'" -f yourFileName.sql
3
  • This works if you don't want to set environment variables or use strange pass files. =)
    – martin
    Oct 27, 2017 at 11:16
  • 2
    this should have been the accepted answer, thank you
    – grepit
    Jun 9, 2020 at 20:58
  • This is the right answer. thank you so much.
    – Rajeshwar
    Nov 15 at 8:10
16

you could even do it in this way:

sudo -u postgres psql -d myDataBase -a -f myInsertFile

If you have sudo access on machine and it's not recommended for production scripts just for test on your own machine it's the easiest way.

15

2021 Solution

if your PostgreSQL database is on your system locally.

psql dbname < sqldump.sql username

If its hosted online

psql -h hostname dbname < sqldump.sql username

If you have any doubts or questions, please ask them in the comments.

4
  • is it OS dependent?
    – BingLi224
    Feb 23, 2021 at 7:11
  • 1
    @BingLi224 I use a Windows System and I'm pretty sure that it's not OS dependent.
    – wingman__7
    Feb 24, 2021 at 9:10
  • 1
    Best answer. Applicable to Ubuntu/Debian systems. If you run it from a user with the permission to alter the database, you can even omit the username part, so it's just psql dbname < sqldump.sql. Dec 27, 2021 at 13:04
  • @Neurotransmitter true, that will work as well.
    – wingman__7
    Dec 27, 2021 at 16:54
13
psql -h localhost -d userstoreis -U admin -p 5432 -a -q -f /home/jobs/Desktop/resources/postgresql.sql

Parameter explanations:

-h PostgreSQL server IP address
-d database name
-U user name
-p port which PostgreSQL server is listening on
-f path to SQL script
-a all echo
-q quiet
1
  • Thanks spent some time searching for a "-a" option
    – Molochnik
    Oct 18 at 12:54
11

Walk through on how to run an SQL on the command line for PostgreSQL in Linux:

Open a terminal and make sure you can run the psql command:

psql --version
which psql

Mine is version 9.1.6 located in /bin/psql.

Create a plain textfile called mysqlfile.sql

Edit that file, put a single line in there:

select * from mytable;

Run this command on commandline (substituting your username and the name of your database for pgadmin and kurz_prod):

psql -U pgadmin -d kurz_prod -a -f mysqlfile.sql

The following is the result I get on the terminal (I am not prompted for a password):

select * from mytable;

test1
--------
hi
me too

(2 rows)
1
  • How do you set up a user? It's my first time installing and running -f on a new .sql file. Always says wrong password
    – mKane
    May 3, 2018 at 1:00
4

You can open a command prompt and run as administrator. Then type

../bin>psql -f c:/...-h localhost -p 5432 -d databasename -U "postgres"

Password for user postgres: will show up.

Type your password and enter. I couldn't see the password what I was typing, but this time when I press enter it worked. Actually I was loading data into the database.

2
  • 1
    I think you mean -d "postgres" Aug 22, 2014 at 14:21
  • @amphetamachine -d for database name , check psql --help
    – Yaz
    Jun 30, 2016 at 12:40
2

A small improvement in @wingman__7 's 2021 answer: if your username contains certain characters (an underscore in my case), you need to pass it with the -U flag.
This worked for me:

$ psql -h db.host -d db_name -U my_user < query.sql 
1

I achived that wrote (located in the directory where my script is)

::someguy@host::$sudo -u user psql -d my_database -a -f file.sql 

where -u user is the role who owns the database where I want to execute the script then the psql connects to the psql console after that -d my_database loads me in mydatabase finally -a -f file.sql where -a echo all input from the script and -f execute commands from file.sql into mydatabase, then exit.

I'm using: psql (PostgreSQL) 10.12 on (Ubuntu 10.12-0ubuntu0.18.04.1)

1

Try using the following command in the command line console:

psql -h localhost -U postgres -f restore.sql 
1
sudo -u postgres -i .

postgres is username who you use to install postgres

psql -d demo -a -f demo.sql 

demo -is name db

demo.sql file sql backup

0

The following is my preferred method as well as how to save the results to a txt file:

export PGPASSWORD='your_password'
psql -U postgres -h localhost -d mydatabase -a -f /path/to/your/sqlfile.sql -o /path/to/your/output.txt

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.