How to Manage PostgreSQL Databases from the Command Line with psql

Gerard Hynes

Now is a great time to learn relational databases and SQL. From web development to data science, they are used everywhere.
In the Stack Overflow 2021 Survey, 4 out of the top 5 database technologies used by professional developers were relational database management systems.
PostgreSQL is an excellent choice as a first relational database management system to learn.
- It’s widely used in industry, including at Uber, Netflix, Instagram, Spotify, and Twitch.
- It’s open source, so you won’t be locked into a particular vendor.
- It’s more than 25 years old, and in that time it has earned a reputation for stability and reliability.
Whether you’re learning from the freeCodeCamp Relational Database Certification or trying out PostgreSQL on your own computer, you need a way to create and manage databases, insert data into them, and query data from them.
While there are several graphical applications for interacting with PostgreSQL, using psql and the command line is probably the most direct way to communicate with your database.
What is psql?
psql is a tool that lets you interact with PostgreSQL databases through a terminal interface. When you install PostgreSQL on a machine, psql is automatically included.
psql lets you write SQL queries, send them to PostgreSQL, and view the results. It also lets you use meta-commands (which start with a backslash) for administering the databases. You can even write scripts and automate tasks relating to your databases.
Now, running a database on your local computer and using the command line can seem intimidating at first. I’m here to tell you it’s really not so bad. This guide will teach you the basics of managing PostgreSQL databases from the command line, including how to create, manage, back up, and restore databases.
Prerequisite – Install PostgreSQL
If you haven’t already installed PostgreSQL on your computer, follow the instructions for your operating system on the official PostgreSQL documentation.
When you install PostgreSQL, you will be asked for a password. Keep this in a safe place as you’ll need it to connect to any databases you create.
How to Connect to a Database
You have two options when using psql to connect to a database: you can connect via the command line or by using the psql application. Both provide pretty much the same experience.
Option 1 – Connect to a database with the command line
Open a terminal. You can make sure psql is installed by typing psql —version . You should see psql (PostgreSQL) version_number , where version_number is the version of PostgreSQL that’s installed on your machine. In my case, it’s 14.1.

Checking psql version via the command line
The pattern for connecting to a database is:
The -d flag is shorter alternative for —dbname while -U is an alternative for —username .
When you installed PostgreSQL, a default database and user were created, both called postgres . So enter psql -d postgres -U postgres to connect to the postgres database as the postgres superuser.
You will be prompted for a password. Enter the password you chose when you installed PostgreSQL on your computer. Your terminal prompt will change to show that you’re now connected to the postgres database.

Connecting to a database from the command line with psql
If you want to directly connect to a database as yourself (rather than as the postgres superuser), enter your system username as the username value.
Option 2 – Connect to a database with the psql application
Launch the psql application – it’ll be called «SQL Shell (psql)». You will be prompted for a server, a database, a port and a username. You can just press enter to select the default values, which are localhost , postgres , 5432 , and postgres .
Next, you’ll be prompted for the password you chose when you installed PostgreSQL. Once you enter this, your terminal prompt will change to show that you’re connected to the postgres database.

Connecting to a database with the psql application
Note: If you’re on Windows you might see a warning like “Console code page (850) differs from Windows code page (1252) 8-bit characters might not work correctly. See psql reference page ‘Notes for Windows users’ for details.” You don’t need to worry about this at this stage. If you want to read more about it, see the psql documentation.
How to Get Help in psql
To see a list of all psql meta-commands, and a brief summary of what they do, use the \? command.

psql’s help command
If you want help with a PostgreSQL command, use \h or \help and the command.
This will give you a description of the command, its syntax (with optional parts in square brackets), and a URL for the relevant part of the PostgreSQL documentation.

psql describing the DROP TABLE statement
How to Quit a Command in psql
If you’ve run a command that’s taking a long time or printing too much information to the console, you can quit it by typing q .
How to Create a Database
Before you can manage any databases, you’ll need to create one.
Note: SQL commands should end with a semicolon, while meta-commands (which start with a backslash) don’t need to.
The SQL command to create a database is:
For this guide, we’re going to be working with book data, so let’s create a database called books_db .
How to List Databases
You can view a list of all available databases with the list command.

Listing all databases
You should see books_db , as well as postgres , template0 , and template1 . (The CREATE DATABASE command actually works by copying the standard database, called template1 . You can read more about this in the PostgreSQL documentation.)
Using \l+ will display additional information, such as the size of the databases and their tablespaces (the location in the filesystem where the files representing the database will be stored).

Listing all databases with additional information
How to Switch Databases
You’re currently still connected to the default postgres database. To connect to a database or to switch between databases, use the \c command.
So \c books_db will connect you to the books_db database. Note that your terminal prompt changes to reflect the database you’re currently connected to.

Switching databases
How to Delete a Database
If you want to delete a database, use the DROP DATABASE command.
You will only be allowed to delete a database if you are a superuser, such as postgres , or if you are the database’s owner.
If you try to delete a database that doesn’t exist, you will get an error. Use IF EXISTS to get a notice instead.

Deleting a database
You can’t delete a database that has active connections. So if you want to delete the database you are currently connected to, you’ll need to switch to another database.
How to Create Tables
Before we can manage tables, we need to create a few and populate them with some sample data.
The command to create a table is:
This will create an empty table. You can also pass column values into the parentheses to create a table with columns. At the very least, a basic table should have a Primary Key (a unique identifier to tell each row apart) and a column with some data in it.
For our books_db , we’ll create a table for authors and another for books. For authors, we’ll record their first name and last name. For books, we’ll record the title and the year they were published.
We’ll make sure that the authors’ first_name and last_name and the books’ title aren’t null, since this is pretty vital information to know about them. To do this we include the NOT NULL constraint.
You will see CREATE TABLE printed to the terminal if the table was created successfully.
Now let’s connect the two tables by adding a Foreign Key to books. Foreign Keys are unique identifiers that reference the Primary Key of another table. Books can, of course, have multiple authors but we’re not going to get into the complexities of many to many relationships right now.
Add a Foreign Key to books with the following command:
Next, let’s insert some sample data into the tables. We’ll start with authors .
Select everything from authors to make sure the insert command worked.

Querying all data from the authors table
Next, we’ll insert some books data into books .
If you run SELECT * FROM books; you’ll see the book data.

Querying all data from the books table
How to List All Tables
You can use the \dt command to list all the tables in a database.
For books_db you will see books and authors . You’ll also see books_book_id_seq and authors_author_id_seq . These keep track of the sequence of integers used as ids by the tables because we used SERIAL to generate their Primary Keys.

Listing all tables in a database
How to Describe a Table
To see more information about a particular table, you can use the describe table command: \d table_name . This will list the columns, indexes, and any references to other tables.

Describing the authors table
Using \dt+ table_name will provide more information, such as about storage and compression.
How to Rename a Table
If you ever need to change the name of a table, you can rename it with the ALTER TABLE command.
How to Delete a Table
If you want to delete a table, you can use the DROP TABLE command.
If you try to delete a table that doesn’t exist, you will get an error. You can avoid this by including the IF EXISTS option in the statement. This way you’ll get a notice instead.
How to Manage Longer Commands and Queries
If you’re writing longer SQL queries, the command line isn’t the most ergonomic way to do it. It’s probably better to write your SQL in a file and then have psql execute it.
If you are working with psql and think your next query will be long, you can open a text editor from psql and write it there. If you have an existing query, or maybe want to run several queries to load sample data, you can execute commands from a file that is already written.
Option 1 – Open a text editor from psql
If you enter the \e command, psql will open a text editor. When you save and close the editor, psql will run the command you just wrote.

Writing commands in a text editor
On Windows, the default text editor for psql is Notepad, while on MacOs and Linux it’s vi. You can change this to another editor by setting the EDITOR value in your computer’s environment variables.
Option 2 – Execute commands and queries from a file
If you have particularly long commands or multiple commands that you want to run, it would be better to write the SQL in a file ahead of time and have psql execute that file once you’re ready.
The \i command lets you read input from a file as if you had typed it into the terminal.
Note: If you’re executing this command on Windows, you still need to use forward slashes in the file path.
If you don’t specify a path, psql will look for the file in the last directory that you were in before you connected to PostgreSQL.

Executing SQL commands from a file
How to Time Queries
If you want to see how long your queries are taking, you can turn on query execution timing.
This will display in milliseconds the time that the query took to complete.
If you run the \timing command again, it will turn off query execution timing.

Using query execution timing
How to Import Data from a CSV File
If you have a CSV file with data and you want to load this into a PostgreSQL database, you can do this from the command line with psql.
First, create a CSV file called films.csv with the following structure (It doesn’t matter if you use Excel, Google Sheets, Numbers, or any other program).

A spreadsheet with Pixar film data
Open psql and create a films_db database, connect to it, and create a films table.
You can then use the \copy command to import the CSV file into films . You need to provide an absolute path to where the CSV file is on your computer.
The DELIMITER option specifies the character that separates the columns in each row of the file being imported, CSV specifies that it is a CSV file, and HEADER specifies that the file contains a header line with the names of the columns.
Note: The column names of the films table don’t need to match the column names of films.csv but they do need to be in the same order.
Use SELECT * FROM films; to see if the process was successful.

Importing data from a .csv file
How to Back Up a Database with pg_dump
If you need to backup a database, pg_dump is a utility that lets you extract a database into a SQL script file or other type of archive file.
First, on the command line (not in psql), navigate to the PostgreSQL bin folder.
Then run the following command, using postgres as the username, and filling in the database and output file that you want to use.
Use postgres for the username and you will be prompted for the postgres superuser’s password. pg_dump will then create a .sql file containing the SQL commands needed to recreate the database.

Backing up a database to a .sql file
If you don’t specify a path for the output file, pg_dump will save the file in the last directory that you were in before you connected to PostgreSQL.

Contents of films.sql backup file
You can pass the -v or —verbose flag to pg_dump to see what pg_dump is doing at each step.

Running pg_dump in verbose mode
You can also backup a database to other file formats, such as .tar (an archive format).
Here the -F flag tells pg_dump that you’re going to specify an output format, while t tells it it’s going to be in the .tar format.
How to Restore a Database
You can restore a database from a backup file using either psql or the pg_restore utility. Which one you choose depends on the type of file you are restoring the database from.
- If you backed up the database to a plaintext format, such as .sql , use psql.
- If you backed up the database to an archive format, such as .tar , use pg_restore .
Option 1 – Restore a database using psql
To restore a database from a .sql file, on the command line (so not in psql), use psql -U username -d database_name -f filename.sql .
You can use the films_db database and films.sql file you used earlier, or create a new backup file.
Create an empty database for the file to restore the data into. If you’re using films.sql to restore films_db , the easiest thing might be to delete films_db and recreate it.
In a separate terminal (not in psql), run the following command, passing in postgres as the username, and the names of the database and backup file you are using.
The -d flag points psql to a specific database, while the -f flag tells psql to read from the specified file.
If you don’t specify a path for the backup file, psql will look for the file in the last directory that you were in before you connected to PostgreSQL.
You will be prompted for the postgres superuser’s password and then will see a series of commands get printed to the command line while psql recreates the database.

Restoring a database using psql
This command ignores any errors that occur during the restore. If you want to stop restoring the database if an error occurs, pass in —set ON_ERROR_STOP=on .
Option 2 – Restore a database using pg_restore
To restore a database using pg_restore , use pg_restore -U username -d database_name path_to_file/filename.tar .
Create an empty database for the file to restore the data into. If you’re restoring films_db from a films.tar file, the easiest thing might be to delete films_db and recreate it.
On the command line (not in psql), run the following command, passing in postgres as the username, and the names of the database and backup file you are using.

Restoring a database using pg_restore
You can also pass in the -v or —verbose flag to see what pg_restore is doing at each step.

Using pg_restore in verbose mode
How to Quit psql
If you’ve finished with psql and want to exit from it, enter quit or \q .
This will close the psql application if you were using it, or return you to your regular command prompt if you were using psql from the command line.
Where to Take it from Here
There are lots more things you can do with psql, such as managing schemas, roles, and tablespaces. But this guide should be enough to get you started with managing PostgreSQL databases from the command line.
If you want to learn more about PostgreSQL and psql, you could try out freeCodeCamp’s Relational Database Certificate . The official PostgreSQL documentation is comprehensive, and PostgreSQL Tutorial offers several in-depth tutorials.
I hope you find this guide helpful as you continue to learn about PostgreSQL and relational databases.
Как создать демо базу данных для курса Основы SQL
В учебном курсе «Основы SQL» для демонстрации работы SQL используется PostgreSQL. Сейчас это самая популярная из бесплатных систем управления базами данных. Все SQL запросы в курсе проверены на работоспособность именно в PostgreSQL. Однако большая часть запросов использует синтаксис стандарта ANSI SQL, поэтому они будут работать и в других системах, включая MySQL, Microsoft SQL Server и Oracle. Вы можете использовать любую систему управления базами данных, которая вам нравится, но я рекомендую PostgreSQL.
1. Загрузите PostgreSQL для вашей операционной системы на странице Downloads официального сайта. Я устанавливал на Windows, если вы используете другую операционную систему, то выбирайте соответствующие ссылки для загрузки. Примеры в курсе проверены на PostgreSQL 13, поэтому рекомендую устанавливать именно эту версию. Однако на предыдущих версиях, начиная с PosgreSQL 10, также все должно работать.
Инсталлятор для Windows и Mac OS загружается с сайта компании EDB, которая предоставляет платную поддержку для PostgreSQL. Однако PostgreSQL, которую вы установите с помощью этого инсталлятора от EDB, будет полностью бесплатной.
2. Запустите скачанный инсталлятор PostgreSQL.


Не забудьте запомнить или записать пароль пользователя postgres, он вам понадобится для подключения к базе и выполнения запросов!
После завершения установки инсталлятор предложит вам запустить Stack Builder для установки дополнительных утилит и компонентов. Этого можно не делать, просто снимите галочку в пункте «Stack Builder…» и нажмите кнопку «Finish».
Intro to PostgreSQL
![]()
There’s a number of options available when it comes to choosing a database when starting on a new project. You could use JavaScript-based MongoDB which stores data as documents. While you can link related data to documents in MongoDB, using a relationship-based database could be a better option if you’re looking to run complex queries.
Postgres uses SQL which stands for Structured Query Language. This is a human-readable language that has the ability to get very specific results. Postgres, MySQL, SQLite, and Oracle are all SQL databases that store information in a table-like format.
One advantage of Postgres is that you can use JSON as a datatype. This is helpful when you want to be able to have a column that can store a variety of content types like videos, polls, images, etc. Another reason you may choose Postgres is for its scalability and compatibility with applications running on NodeJS.
Create Database and Tables
After following the steps to download and install the Postgres, you can enter the CLI by typing ‘psql’ in your terminal. Here’s a list of common commands that are used in the Postgres CLI that will allow you to view existing tables and changes made to the database.
As I mentioned earlier, SQL is very human-readable. Creating a database is as simple as typing ‘CREATE DATABASE’. Although you don’t have to capitalize all keywords, it is conventional to do so.
The code above will create a database and a table called users. Each user will have a unique id that is an integer. This id will act as a primary key that is automatically generated upon creation. If you have worked with MongoDB a primary key is equivalent to the _id. It’s used for creating relationships between separate tables of data. VARCHAR is a data type that refers to text that we can put a maximum value on. If we don’t need to limit this data, we can use the TEXT type instead. By including UNIQUE NOT NULL, we are explicitly saying that if a username is not unique an error will be thrown and it will not be saved.
To add a user to our newly created table, we can use the INSERT INTO keywords followed by the table name, columns, and values for those columns. The values should be in single-quotes — never double-quotes.
Select and Query Clauses
Every query that we run will begin with the keyword SELECT. If you want to select all of the data from a table, you can run something like this…
To get more specific data you can use clauses. Clauses are additional keywords like WHERE and ORDER BY that allow us to drill down into the table data further and reduce it to return only what we need at the moment. Here’s an example.
This will return the primary key and username of the first ten results from the users table sorted by username in descending order. The default order of results is ascending, so that’s what you’ll get if you don’t include the DESC clause.
The order of clauses is important. Although you’ll likely not need to use all of these clauses at once, here’s the acceptable order of operations when querying.
- FROM, including JOINs
- WHERE
- GROUP BY
- HAVING
- WINDOW functions
- SELECT
- DISTINCT
- UNION
- ORDER BY
- LIMIT and OFFSET
You can read more about each of these clauses and their use cases here.
Update and Delete
Changing the values within our tables is as simple as defining what we want to set as the new values and querying for the data we want to change.
Deleting is just as easy.
Foreign Keys
Remember that the beauty of SQL databases is that they are relational and we can build connections. In our users table example, we have a primary key that is always generated on the creation of a user and will always be unique. We can map that primary key to another table to refer to that user instance. This is called a foreign key.
In the new comments table, the user_id is defined as an INT REFERENCE data type that acts as a foreign key to link the user_id to a specific comment instance. ON DELETE CASCADE tells Postgres to delete all the comments that are associated with a specific user if that user has been deleted. This helps us from keeping data that is no longer useful.
Join Tables
Now that we have a foreign key on the comment table, we can implement a join table. Join tables allow us to display related data. They help us to follow the coding principle of a single source of truth by pulling data from one table into another, instead of adding it manually which could lead to conflicts.
The code above would create a table with a column for comment id, user id, and username. It’s pulling this information from the comments table and the users table. They are connected by the comment’s foreign key (comments.user_id) that matches the user’s primary key (users.user_id).
INNER JOIN is just one of several join tables. The most commonly used join tables are inner, left, and right. Choosing the right join table will depend on where the information you need is stored. Here’s a brief description of the types of join tables available to use.
I found this diagram to also be useful for understanding the differences between each type of join table.
Additional Resources
We’ve only dipped our toes into the basic functionality and features of Postgres. I hope that this has piqued your curiosity about SQL databases. Here are some helpful resources to help you get more acclimated to this fantastic tool.
PostgreSQL Tutorial — Basics (Windows)
In this tutorial, we will go over some PostgreSQL basics that new developers must be familiar with. You will learn to create users, databases, tables, and columns and add data (rows) to tables using pgAdmin and the psql shell.

This tutorial can be used as a reference or followed in order after first installing PostgreSQL on windows. If you don't have PostgreSQL installed check out our PostgreSQL installation tutorial for windows.
Part 1 — SQL Shell (psql)
If you're new to Postgres, it's a good idea to get familiar with the psql shell as you may find yourself needing it from time to time. Start the shell from the start menu and hit enter when asked for Server, Database, Port, Username and enter the password you chose when you first installed postgres.

You are now connected to your server through the shell using the default username and password (postgres).
1. Create a user
A good first step after installing PostgreSQL is to create a new user and leave the default 'postgres' user alone. Enter the following SQL to create a new user:
If successful, you should see the message 'CREATE ROLE' and if you type:
you will see a list of all the users on your postgreSQL server (including your new one)

2. Create a database
Let's create a database for that awesome project your working on and give your new user privileges to access it. Enter the following to create a new database:
Now grant your user privileges to use this database:
You should see the following if everything went well:

3. Test the new user and database
Exit out of the shell using:
and reopen the shell from the start menu. This time login using your new user and database:

You can see in the image above that I am logged in and connected to the simpleapp database. Type the following to see if there are any tables in this database:
And of course you will get a message telling you there is nothing in this database because you just created it:

4. Create a Table
Let's add a table to our database. Enter the following, replacing datatype with one appropriate for the data you expect to keep in that column:
and type the following again to see that your table exists:

So far the shell has been useful for running some basic SQL and to get an idea of how our database is structured. But you can imagine if it contained millions of rows of data across multiple tables how hard it would be to manipulate it all in a shell based environment. That's where pgAdmin comes in.
Part 2 — pgAdmin
pgAdmin is a browser based GUI that connects to your PostgreSQL server. It allows you to better visualise what is going on in your databases and manage them in almost any way you need. Launch pgAdmin now from the windows Start Menu.
1. Connect to a Server

On the left hand side of the window, right click on your postgreSQL server, select properties and then the connection tab on the pop up window. Enter the database and username you setup through the shell earlier. Click Save.

Back in the main pgAdmin window, this time left click on your server name and enter your users password in the following popup. Click OK.

You should now see the pgAdmin dashboard showing some stats for your server. On the left hand side should be 3 new drop downs. Click on 'Databases' to see a list of databases on your server. An 'x' over a database name simply means you aren't connected to that database right now.

Click on your database to connect to it and select Schemas > public > Tables. You should see the table you created through the shell earlier. Click on the table and select Columns to see those columns you set up at the same time. Pretty cool huh? \

2. Use the Query Tool
Now to finish off let's add some data to our table using the pgAdmin query tool. At the top of pgAdmin, right under the main menu on the left click the lightning bolt icon. This will bring up the query tool where you can run the same SQL you ran through the shell (and any SQL for that matter). Enter the following to add some data to your table:
And click the lightning bolt at the top of the query editor to execute it.

Now clear out the query editor and execute the following:
to see the values that you just entered in your table

Conclusion
Working with PostgreSQL isn't much more complicated than what you have gone over in this tutorial. With pgAdmin and some basic SQL, you can see how easy it is to manipulate your databases and the data they contain. Your next step would be to brush up on your SQL, learn how to properly structure a relational database and secure your PostgreSQL server.
Stay tuned for more tutorials where we will help you become a PostgreSQL master and share this tutorial on social media if it helped you out 🙂