Forrest logo
back to the psql tool

sql:warp:2944c

Execute a .sql file against a PostgreSQL database
$ psql -U ${user_name} -d ${database_name} -a -f ${file_name}
try on your machine

This command is used to execute a SQL script in a PostgreSQL database using the psql command-line tool. Here is the breakdown of its components:

  • psql: It is the command-line interface for PostgreSQL, allowing you to interact with databases, run SQL queries, and execute scripts.

  • -U ${user_name}: This option specifies the username to connect to the database. ${user_name} is a placeholder that needs to be replaced with an actual username.

  • -d ${database_name}: This option specifies the name of the database to connect to. ${database_name} is a placeholder that needs to be replaced with the desired database name.

  • -a: This option tells psql to echo all input from the script, as well as the result of each query. It can be helpful to see what is being executed and the output generated.

  • -f ${file_name}: This option specifies the name of the file containing the SQL script that will be executed. ${file_name} is a placeholder that needs to be replaced with the actual file name.

Taking all these components together, this command connects to a PostgreSQL database with the given username (${user_name}) and executes the SQL script contained in the file (${file_name}), printing the script's content and the query results onto the console.

This explanation was created by an AI. In most cases those are correct. But please always be careful and never run a command you are not sure if it is safe.
back to the psql tool