1

I have a folder in a directory in my PC which contains multiple SQL files. Each of the file is a Postgres function. I want to execute every SQL file situated in the folder at a time in PostgreSQL server using PgAdmin or in other way. How can I accomplish this?

2
  • Have you considered merging these files into a single one, which is fairly straightforward, and then executing it? ;) Commented Dec 21, 2022 at 11:12
  • I thought about it but don't know how to do. I want a process by which I can execute all SQL files in PostgreSQL server. There are 500+ sql files. Currently I have to execute each sql file individually. This is too time consuming. Commented Dec 21, 2022 at 11:17

1 Answer 1

1

I apologize if I'm oversimplifying your question, but if the main issue is how to execute all SQL files without having to call them one by one, you just need to put them in a loop, e.g. in bash calling psql

#!/bin/bash

for f in *.sql
do
  psql -h dbhost -d db -U dbuser -f $f
done

Or cat them and pipe the result to psql stdin:

$ cat /path/to/files/*.sql | psql -h dbhost -d db -U dbuser

And if you need them to run in a single transaction, consider merging the SQL files, e.g. using cat - this assumes all statements in your sql file are properly terminated:

$ cat /path/to/files/*.sql > merged.sql
Sign up to request clarification or add additional context in comments.

17 Comments

where to execute the command? Is this solution for windows? My OS is windows..
@Alien those are linux commands. Look for the equivalent on Windows (cat -> type?). I haven't touched Windows in ~20 years.
where to execute the command? In CMD?
@Alien yes, in the command line terminal of Windows. There is certainly a way to emulate bash commands using windows though: geeksforgeeks.org/use-bash-shell-natively-windows-10
and the CMD should be opened under the bin folder where PostgreSQL is installed? like C:\Program Files\PostgreSQL\15\bin?
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.