Postgresql Command Line Cheat Sheet
Psql command line tutorial and cheat sheet. Posted by 2 hours ago. Psql command line tutorial and cheat sheet. Log in or sign up to leave a comment Log In Sign Up. View discussions in 2 other communities.
- Introduction to the PostgreSQL cheat sheet Prerequisites to using PostgreSQL SQL commands in psql Accessing PostgreSQL using the ‘psql’ command line interface PostgreSQL cheat sheet of useful SQL queries and commands Use ‘SELECT’ to get a Postgres table’s column names PostgreSQL cheat sheet commands for modifying tables PostgreSQL cheat sheet for managing databases Use the a.
- Change database. Use c to change database names: mary= c marydb.
- You can do some of them through a visual user interface, but that's not covered here. Knowing how to perform these operations on the command line means you can script them, and scripting means you can automate tests, check errors, and do data entry on the command line. This section isn't a full cheat sheet for psql. It covers the most common operations and shows them roughly in sequence, as you'd use.
Introduction to the PostgreSQL cheat sheet
The PostgreSQL offers scaling, storage flexibility, and ease of database management for developers, DBAs, and other technical professionals. Because of PostgreSQL’s ability to offer architecture stability along with an extensive coding capability, the plethora of commands and statements are endless. That’s a good thing. What’s even better is having a handy list of the SQL commands you’re likely to use regularly. Well, some of the most popular ones are featured here in Part 2 of The PostgreSQL Cheat Sheet, so take a few moments to review it now.
Prerequisites to using PostgreSQL SQL commands in psql
Be sure that the object-relational database management systemPostgreSQL installed on your OS.
At the command line psql, check the PostgreSQL version with the command
psql -V.You’ll also need PostgreSQL database accessibility to try out the samples shown in this PostgreSQL cheat sheet.
NOTE: Here are some useful tips regarding commands. When writing code in psql, always end your SQL statement with a semicolon (;). If you don’t and push Return, your code will extend to the next line of code without breaking at the place where you wanted it to end.
Another tip for writing SQL statements is to remember to enclose your strings in PostgreSQL with singular quotes, not doubles. This one is correct: 'string here' for example. A syntax error will happen if you use doubles.
Finally, to quickly get away from a long results list or a command you started or completed, push CTRL+C.
Accessing PostgreSQL using the ‘psql’ command line interface
- From your server on your localhost, connect to your database in PostgreSQL with the command
psql.
psql postgres |
- Alternatively to the above command, input your username, host, and then database name to make a Postgres database connection.
psql -U some_username -h 127.0.0.1 -d some_database |
NOTE: See the flags in the above code.
- Your username in Postgres comes after the flag
-U - The IP address or host domain goes after the flag
-h - The database PostgreSQL name is inputted after the flag
-d
PostgreSQL cheat sheet of useful SQL queries and commands
This PostgreSQL cheat sheet contains some of the most frequently-used commands to perform basic computing software programming functions so that you can code with efficiency.
Use ‘SELECT’ to get a Postgres table’s column names
- Obtain the names of a table’s columns with the
information_schemacommand:
SELECT*FROM information_schema.columns WHERE some_table ='some_table'; |
- You can also access the names of a public table’s column with the
table_schemacommand:
SELECT*FROM information_schema.columns WHERE table_schema ='public' AND some_table ='some_table'; |
PostgreSQL cheat sheet commands for modifying tables
- Use the
INSERT INTOstatement to add a value to a table:
INSERTINTO some_table(col1, col2)VALUES(value1,value2); |
NOTE: The above command adds two columns and two values. See (col1, col2) and (value1, value2) in the SQL statement. Place a comma after each indicated column or value within the parenthesis when you have more than one to add to a table.
- Use the
INSERT INTOandSELECTstatement to add a table’s column data to a different table:
INSERTINTO table1(column_list)SELECT column_list FROM table2; |
- Save table updates with the
UPDATEstatement:
- Use the
UPDATEstatement for condition matching in a table:
UPDATE some_table SET col1 = new_val, col2 = new_val WHERE condition; |
- Use the
DELETE FROMstatement to remove all records from a table in Postgres:
NOTE: An option to remove all records from a table in Postgres is to use the command TRUNCATE followed by naming the table you want to delete.
- Use the
DELETE FROMstatement to remove data pertaining to a condition:
DELETEFROM some_table WHERE condition; |
PostgreSQL cheat sheet for managing databases
- Make a database with the
CREATE DATABASEstatement:
NOTE: A database may already exist, so to avoid raising an exception, use the IF NOT EXISTS clause after the CREATE DATABASE statement.
- Use
DROP DATABASEto delete a database forever:
DROPDATABASE[IFNOTEXISTS] db_name; |
NOTE: You won’t get an error message prompt if you add the IF NOT EXISTS clause.
Use the a PostgreSQL ‘SELECT’ statement to query data
Query data in a table with these various SELECT statement command.
- Add the wildcard asterisk
*symbol to have every record in a PostgreSQL table return in the results page.
- Indicate which columns to query:
SELECT col1, col2 FROM some_table; |
- Query a filtered table:
- Include the clause
WHEREto specify the columns you want to query:
SELECT some_col, another_col FROM some_table WHERE some_int >50; |
- Perform a column query and give the column an alias with this statement:
Here are some commands to query in PostgreSQL using operators.
Psql Commands
- Use the operator
LIKEto query a character string pattern match:

To query a set of operations in PostgreSQL:
Using the LIKE operator:
SELECT*FROM some_table WHERECOLUMNLIKE'%value'; |
- Use the operator
BETWEENto query a table range:
SELECT*FROM some_table WHERECOLUMNBETWEEN low AND high; |
- Use the operator
INto add more than one condition or value to yourWHEREclause in your statement:
SELECT*FROM some_table WHERECOLUMNIN(value1, value2); |
- Use the operator
UNIONto merge at least twoSELECTstatement results sets.
- Use the operator
EXCEPTto put together twoSELECTstatements that will only return rows that are not in the second statement.
SELECT*FROM table1 EXCEPTSELECT*FROM table2; |
- Use the operator
INTERSECTto have the results set to reflect every record picked by at least two statements. If a record fails to match each query, it won’t appear in the results set:
- Use the clause
LIMITto return a limited amount of rows. In the statement below,OFFSETrows are skipped:
SELECT*FROM some_table LIMITLIMIT OFFSET offset ORDERBY column_name; |
Here are a few SQL statements for querying multiple tables.
- Make a multiple Postgres table query with the
INNER JOINstatement:
SELECT*FROM table1 INNERJOIN table2 ON conditions |
- Make a multiple Postgres table query with the
LEFT JOINstatement:
- Make a multiple Postgres table query with the
FULL OUTER JOINstatement:
SELECT*FROM table1 FULLOUTERJOIN table2 ON conditions |
- Make a multiple Postgres table query with the
CROSSJOINstatement:
SELECT*FROM table1 CROSSJOIN table2 ON conditions |
- Make a multiple Postgres table query with the
NATURAL JOINstatement:
SELECT*FROM table1 NATURALJOIN table2 ON conditions |
Here are a few common SELECT statements for displaying table rows.
- Use the wildcard
(*)to show all table rows:
- Use the
ORDER BYclause to sort the order of table rows in the results:
SELECT column_name FROM some_table ORDERBY column_name [ASC|DESC]; |
- To group table data, use the clause
GROUP BY:

- Use both clauses
HAVINGandGROUP BYto specify the criteria for grouping the data results:
SELECT*FROM some_table GROUPBY col1 HAVING condition; |
Conclusion on the PostgreSQL cheat sheet
A helpful PostgreSQL cheat sheet is meant to help you reduce the time you spend on your daily coding projects. Make it an accessible reference of common SQL statements and other commands are at your fingertips. This way, you won’t have to wonder if the syntax is off the mark. The most beneficial result is that you’ll likely cut down on unnecessarily raised exceptions every day.
PostgreSQL Commond Line Cheat Sheet
##General Postgres Command
change to postgres user and open psql prompt
>sudo -u postgres psql postgres
Postgresql Command Line Cheat Sheet Free
password “test”
show postgres versoin
>postgres=# SELECT version();
list databases
>postgres=# l
connect to database
>postgres=# c <databasename>
switch to different database with role <role-name>
>postgres=# c <databasename> <role-name>
list tables in connected database
>postgres=# dt
list columns on table
>postgres=# d <tablename>
exit console
>postgres=# Ctrl-D or q
##Performance tuning
turn on query timing
>postgres=# timing
analyze query
>postgres=# EXPLAIN ANALYZE SELECT COUNT(*) FROM hm_client_session;
look at locks
fast count estimate rows in a table
>reportingdb_1=# SELECT reltuples::bigint AS estimate FROM pg_class where relname=’hm_client_session’;
estimate
———-
7375553
(1 row)
Time: 0.710 ms
##configdb check
connect to database
>postgres=# c configdb_1
copy query output as CSV to file
>configdb_1=# Copy (SELECT * FROM hm_device WHERE is_connected=false) To ‘/tmp/hm_device.csv’ with CSV HEADER;
drop database
>postgres=# DROP DATABASE demodb1;
## Backup and restore database
> pg_dump -i-h localhost -p5432-U postgres -F t -b-v-f“~/backups/backup-file.backup” database_name_to_backup
–i, –ignore-version proceed even when server version mismatches. Usefulwhile migrating data between servers. –h localhost, host to connect, can be IP address –p 5432, default port used by PostgreSQL–U postgres, this is default username, make sure user has rights to backup database –F t, -format used for backup, I suggest always using “t” (tar), other options are listed below –b, –blobs include large objects in dump –v, –verbose –f “~/backups/test-database.backup”, file where backup will be stored database_name_to_backup, database name which we want to backup
>pg_restore -i-h localhost -p5432-U postgres -d old_db -v“~/backups/backup-file.backup”
–p, –port=PORT database server port number –i, –ignore-version proceed even when server version mismatches –h, –host=HOSTNAME database server host or socket directory –U, –username=NAME connect as specified database user –W, –password force password prompt (should happen automatically) –d, –dbname=NAME connect to database name –v, –verbose verbose mode

## Privilege and Roles
list roles
>postgres=# du
create role
>postgres=# CREATE ROLE demorole1 WITH LOGIN ENCRYPTED PASSWORD ‘password1’ CREATEDB;
create role with multiple privileges
>postgres=# CREATE ROLE demorole1 WITH LOGIN ENCRYPTED PASSWORD
>postgres=# ‘password1’ CREATEDB CREATEROLE REPLICATION SUPERUSER;
alter role
>postgres=# ALTER ROLE demorole1 CREATEROLE CREATEDB REPLICATION SUPERUSER;
drop role
>postgres=# DROP ROLE demorole1;
create database
>postgres=# CREATE DATABASE demodb1 WITH OWNER demorole1 ENCODING ‘UTF8’;
grant privileges to new user
>postgres=# GRANT ALL PRIVILEGES ON DATABASE demodb1 TO demorole1;
