SoFunction
Updated on 2025-04-08

How to execute sql files in postgresql

Postgresql executes sql file

There are 3 ways to run sql scripts on postgresql

1. Connect to db and execute SQL scripts

psql -p 5432
postgres=# CREATE DATABASE testdb;
postgres=# \l
postgres=# \c testdb
#\i followed by the sql file path, such as /pathA/testdb=# \i 
testdb=# \d

2. Run SQL scripts through psql

# Switch to postgres usersudo -i -u postgres
psql -d testdb -U postgres -f /pathA/
or
sudo -u postgres psql -d testdb -U postgres -f /pathA/

3.pgadmin4 interface management tool

Paste it directly and run it

sudo -i -u postgres
psql -p 5432 postgresql 
sudo -u postgrs psql -p 5432 postgres
postgres=# CREATE DATABASE testdb;
# View all databasespostgres=# \l
# You can also use psql -p 5432 testdb to enter database testdbpostgres=# \c testdb
# View all tables \d+testdb=# \d
# View the test table structuretestdb=# \d test
# quitpostgres=# \q
NoticesqlAdd later;Number。testdb-# To wait for input status。 

Postgresql command line executes sql script file

# 1. SQL file import/executionpsql -d sdk -h 192.168.2.122 -p 5432 -U postgres -f /home/sql/
#-d Database name#-h ip address (it is best to state directly, do not use localhost)#-p Port number#-U User#-f sql file path# 2. SQL file exportpg_dump -h 192.168.2.122 -p 5432 -U postgres -f /home/sql/ sdk
#-h ip address (it is best to state directly, do not use localhost)#-p Port number#-U User#-f Save path#sdk  Database name

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.