15

How do call multiple sql files in a single sql file, in postgres

For example I have aaa.sql, bbb.sql, ccc.sql.

I want to execute this 3 files from xxx.sql.

Can anyone suggest me how to do this.

3 Answers 3

16

If you are running these files through psql you want the \i directive ("execute commands from file").

xxx.sql:

\i aaa.sql
\i bbb.sql
\i ccc.sql

If you are passing these through some other program you will need to combine the files yourself - I do not believe there is any SQL-standard way of executing external files.

6
  • Thank you for the reply. I will test and confirm if I was able to achieve it or not
    – Trip
    Feb 3, 2012 at 22:13
  • Doesn't look like working yet Not sure if I am missing something. do I need semi colon at the end??? -Not Really !!!
    – Trip
    Feb 4, 2012 at 0:04
  • 2
    You need to be more specific than "not working" - I assure you this does work -- Refer to the psql manual
    – voretaq7
    Feb 4, 2012 at 1:09
  • It worked. Finally :-) Thanku Problem was -- it was not able to recognize the file and O specifiled the relative path for the file and its working Thank you once again
    – Trip
    Feb 6, 2012 at 15:34
  • @Trip Trip, don't forget to give voretaq credit for his answer!
    – Richard T
    Apr 12, 2015 at 20:43
5

On a bash shell you can do it also with a simple find -exec

find sql/ -name *.sql -exec psql -U user -f {} \;
1
  • 1
    Requires that you use "*.sql" rather than *.sql
    – Jeel Shah
    Mar 12, 2020 at 14:35
4

Not exactly what you are asking for, but will serve your purpose: 1) Put all of your script files in a folder; and 2) use a bash script to iterate through your files and run psql. For example:

SCRIPTS_DIR=/home/myproject/scripts
DATABASE_NAME=database_name

for file in $SCRIPTS_DIR/*.sql
    do sudo -u postgres psql $DATABASE_NAME -f $file
done

This is in fact a little better because you won't have to type your files' names.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .