DEV Community

John Akindipe
John Akindipe

Posted on

How to Execute SQL Commands In Another File from the PostgreSQl psql shell in Windows

The Problem

Suppose you download an sql file containing some sql instructuions (such as dummy data from mockaroo), the options you have to run these commands in postgres include copying the commands in the file over to the psql shell manually and running them. This approach is workable if the file contains only a few commands, however, say the file contains hundreds of lines of sql commands, you realize this option doesn't scale with size.

The Solution

Thankfully, you can execute SQL commands located in another file on your pc straight from the psql shell. The command to do this is \i filepath to sql file

To get the filepath.

  1. Open the file in a code editor such as VSCode
  2. Right click on the file.
  3. Select the copy path option from the dropdown menu.
    Copy path

  4. Then, open your psql shell and run this command \i filepath to sql file, and it’s more than likely you’ll get the following output:
    Permission denied

The solution to the above is quite simple really, very simple infact.

Let’s troubleshoot

It may be this file was downloaded onto your pc and needs to have necessary permissions.

  1. Open the file location
  2. Right-click on the file and click on properties in the drop down menu Right click on sql file

  3. Click on unblock just near the lower right edge of the properties dialogue box and select the apply option (it will become clickable) Unblock sql file to allow changes to the PC

Now that we’ve unblocked the file, we can run the command again in our psql shell and see what happens.

Permission denied
Seems like we're still getting the same error as before. What could be the issue?

The Solution

I did mention that the solution is simple, and it is quite simple, to the initiated. The uninitiated might spend hours or days of debugging trying to figure out what the problem is. You may even give up at some point and just manually copy the sql commands and run them directly in the psql shell. Well, let's save ourselves any ache:

The simplicity of the solution is quite interesting. All we need to do is simply change the direction of our slashes from “\” to “/” and the command works as shown below.

Change slash direction from backwards to forwards

The solution to this problem stems from how the file paths in windows differs from what the psql shell expects and all we need to do is conform to what psql wants, and that my folks is the solution.


This article does assume that:

The user on the psql shell has access to the sql file we are trying to execute code from. Otherwise, all of the above might not apply and it may be necessary to get permission to access the file in the first place.


Kindly share this article if you found it useful. Cheers 😊

Top comments (1)

Collapse
 
aesther profile image
Akindipe Esther Iyinoluwa

Very insightful information 🤝