How To Manage PostgreSQL Databases From The Command Line With PSQL
How To Manage PostgreSQL Databases From The Command Line With PSQL
3. It's more than 25 years old, and in that time it has earned a
reputation for stability and reliability.
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 rst. 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.
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.
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.
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.
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.
\?
If you want help with a PostgreSQL command, use \h or \help and the
command.
\h 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.
For this guide, we’re going to be working with book data, so let’s create a
database called books_db .
\l
Using \l+ will display additional information, such as the size of the
databases and their tablespaces (the location in the lesystem where the
les representing the database will be stored).
\l+
\c database_name
So \c books_db will connect you to the books_db database. Note that your
terminal prompt changes to re ect the database you’re currently
connected to.
Switching databases
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.
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 identi er 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 rst 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 identi ers 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.
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.
If you run SELECT * FROM books; you’ll see the book data.
\dt
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
\d table_name
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.
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 le that is already written.
\e
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.
The \i command lets you read input from a le as if you had typed it into
the terminal.
\i path_to_file/file_name.sql
Note: If you're executing this command on Windows, you still need to use
forward slashes in the le path.
If you don’t specify a path, psql will look for the le in the last directory that
you were in before you connected to PostgreSQL.
\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.
First, create a CSV le called films.csv with the following structure (It
doesn’t matter if you use Excel, Google Sheets, Numbers, or any other
program).
Open psql and create a films_db database, connect to it, and create a
films table.
\c films_db
You can then use the \copy command to import the CSV le into films .
\copy films(title, year, running_time) FROM 'path_to_file' DELIMITER ‘,’ CSV HEADER
The DELIMITER option speci es the character that separates the columns in
each row of the le being imported, CSV speci es that it is a CSV le, and
HEADER speci es that the le 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.
First, on the command line (not in psql), navigate to the PostgreSQL bin
folder.
cd "C:\Program Files\PostgreSQL\14\bin"
Then run the following command, using postgres as the username, and
lling in the database and output le that you want to use.
Use postgres for the username and you will be prompted for the postgres
If you don’t specify a path for the output le, pg_dump will save the le in
the last directory that you were in before you connected to PostgreSQL.
You can also backup a database to other le formats, such as .tar (an
archive format).
You can use the films_db database and films.sql le you used earlier, or
create a new backup le.
Create an empty database for the le 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.
If you don’t specify a path for the backup le, psql will look for the le 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.
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 .
database_name path_to_file/filename.tar .
Create an empty database for the le to restore the data into. If you're
restoring films_db from a films.tar le, 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 le
you are using.
\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.
If you want to learn more about PostgreSQL and psql, you could try out
freeCodeCamp’s Relational Database Certi cate . The of cial PostgreSQL
documentation is comprehensive, and PostgreSQL Tutorial offers several
in-depth tutorials.
I hope you nd this guide helpful as you continue to learn about PostgreSQL
and relational databases.
Gerard Hynes
Teacher turned software developer. JavaScript is my rst love. Currently working on real-time data reporting with Scala, Kafka, and Kubernetes.
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs
as developers. Get started
What is a String in JS? Python Sorted List What's a Git Remote Branch?
You can make a tax-deductible donation here.
What's Ethical Hacking? Force Pull in GitHub Insert into JavaScript Array
Get Current URL with JS Check Python Version Filter an Array in JavaScript
About Alumni Network Open Source Shop Support Sponsors Academic Honesty Code of Conduct Privacy Policy Terms of Service Copyright Policy