How to execute .sql file in PostgreSQL

In this tutorial, we will see how to execute .sql file in PostgreSQL. We can execute/run .sql or script file from following methods.

1. From the Linux shell
2. From the psql tool

Syntax to execute .sql file in PostgreSQL:

psql -h hostname -d database_name -U user_name -p 5432 -a -q -f filepath

Where:

-h PostgreSQL server IP address or hostname
-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. Execute .sql file in PostgreSQL from Linux shell

1. create a file using cat or another method.

cat > createtable.sql

2. Enter the sql commands in the file and save by pressing Ctrl+D

create table test123(name varchar(100));

3. Execute the script file .sql with following syntax.

psql -U james -d r2schools -h localhost -p 5432 -f createtable.sql

How to execute .sql file in PostgreSQL

4. Lets verify executions is successful or not.

psql \c r2schools \dt+ test123

2. Execute .sql file in PostgreSQL from psql

1. Make the script file

vi createtable.sql

2. Type the following lines

create table test321(name varchar(50));

3. Save the file.

4. connect to postgresql using psql

5. Then switch to the database where we want to execute the script.

\c r2schools

6. Now, execute the script file.

\i tablecreate.sql

7. Verify by typing \dt

Visual Representation of above steps: