Postgresql Cheat Sheet



You’ve installed PostgreSQL. Now what? I assume you’ve been given a task that uses psql and you want to learn the absolute minimum toget the job done.

Download this 2-page SQL Window Functions Cheat Sheet in PDF or PNG format, print it out, and stick to your desk. The SQL Window Functions Cheat Sheet provides you with the syntax of window functions, a list of window functions, and examples. PostgreSQL is an open-source, powerful and advanced version of SQL that supports different functions of SQL including, foreign keys, subqueries, functions, and user-defined types. In this quick reference cheat sheet, we will show Oracle SQL and PostgreSQL commands with examples. PostgreSQL Cheat Sheet; Building a workstation laptop from Scratch. Sensible Mail Handling; aspell; closurelikefunctions. Closures in Python; Using Sphinx and GitHub (gh-pages) Setting up python repos to use Sphinx and Github Pages; Todo. The PostgreSQL cheat sheet provides you with the common PostgreSQL commands and statements that enable you to work with PostgreSQL quickly and effectively.

This is both a brief tutorial and a quick reference for the absolute least you need to know about psql. I assume you’re familiar with the command line and have a rough idea aboutwhat database administration tasks, but aren’t familiar with how touse psql to do the basics.

View on GitHub Pages or directly on GitHub

The PostgreSQL documentation is incredibly well written and thorough, but frankly, I didn’t know where to start reading. Thisis my answer to that problem.

If you have any complaints or suggestions please let me know by sending your feedback to tomcampbell@gmail.com. Larousse french dictionary online, free.

It shows how to do the following at the psql prompt:

  • Reference pointing to the official PostgreSQL documentation

If you don’t have access to a live PostgreSQL installation at the moment we still have your back.You can follow through the examples and the output is shown as if youdid type everything out.

The psql command line utility

Many administrative tasks can or should be done on your local machine, even though if database lives on the cloud.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 them in a typical work session.

Starting and quitting the psql interactive terminal
Command-line prompts for psql
Quitting psql
Opening a connection locally
Opening a connection remotely
Using the psql prompt
Getting information about databases
h Help
l List databases
c Connect to a database
dt Display tables
d and d+ Display columns (field names) of a table
du Display user roles
Creating and using tables and records
Creating a database
Creating a table (CREATE TABLE)
Adding a record (INSERT INTO)
Inserting several records at once (INSERT INTO)
Adding only specific fields from a record
Doing a simple query–get a list of records (SELECT)
Maintenance and operations
Timing
Watch
Maintenance
Postgres command line

What you need to know

Before using this section, you’ll need:

  • The user name and password for your PostgreSQL database
  • The IP address of your remote instance

Command-line prompts on the operating system

The $ starting a command line in the examples below represents your operating system prompt. Prompts are configurable so it may well not look like this. On Windows it might look like C:Program FilesPostgreSQL> but Windows prompts are also configurable.

A line starting with # represents a comment. Explore programmingtricks. Same for everything to the right of a #. If you accidentally type it or copy and paste it in, don’t worry. Nothing will happen.

Using psql

You’ll use psql (aka the PostgreSQL interactive terminal) most of all because it’s used to create databases and tables, show information about tables, and even to enter information (records) into the database.

Quitting pqsql

Before we learn anything else, here’s how to quit psql and return to the operating system prompt.You type backslash, the letter q, and then you press the Enter or return key.

This takes you back out to the operating system prompt.

Opening a connection locally

A common case during development is opening a connection to a local database (one on your own machine).Run psql with -U (for user name) followed by the name of the database, postgres in this example:

Opening a connection remotely

To connect your remote PostgreSQL instance from your local machine, use psql at your operating system command line.Here’s a typical connection.

Here you’d enter the password. In case someone is peering over your shoulder, the characters are hidden. After you’ve entered your information properly you’ll get this message (truncated for clarity):

Looking at the psql prompt

A few things appear, then the psql prompt is displayed.The name of the current database appears before the prompt.

At this point you’re expected to type commands and parameters into the command line.

psql vs SQL commands

psql has two different kinds of commands. Those starting with a backslashare for psql itself, as illustrated by the use of q to quit.

Those starting with valid SQL are of course interactive SQL used tocreate and modify PostgreSQL databases.

Warning: SQL commands end with a semicolon!

One gotcha is that almost all SQL commands you enter into psql must end in a semicolon.

  • For example,suppose you want to remove a table named sample_property_5. You’d enter this command:

It’s easy to forget. If you do forget the semicolon, you’ll see this perplexing prompt.Note that a [ has been inserted before the username portion of the prompt, and anotherprompt appears below it:

When you do, just remember to finish it off with that semicolon:

Scrolling through the command history

  • Use the up and down arrow keys to move backwards and forwards through the command history.

Postgres Cheat Sheet Ubuntu

Getting information about databases

These aren’t SQL commands so just press Enter after them. Remember that:

  • When there’s more output than fits the screen, it pauses. Press space to continue
  • If you want to halt the output, press q.

h Help

You’ll get a long list of commands, then output is paused:

  • Press space to continue, or q to stop the output.

You can get help on a particular item by listing it after the h command.

  • For example, to get help on DROP TABLE:

You’ll get help on just that item:

l List databases

What most people think of as a database (say, a list of customers) is actually a table. A database is a set of tables, information about those tables, information about users and their permissions, and much more. Some of these databases (and the tables within) are updated automatically by PostgreSQL as you use them.

To get a list of all databases:

You can get info on a single database by following the l prompt with its name.

  • For example, to view information about the template0 database:

The output would be:

l+ List databases with size, tablespace, and description

To get additional information on the space consumed by database tablesand comments describing those tables, use l+:

x Expand/narrow table lists

Use x (X for eXpanded listing) to control whether table listings use a wide or narrow format.

CommandEffect
x offShow table listings in wide format
x onShow table listings in narrow format
xReverse the previous state
x autoUse terminal to determine format

Example: Here’s an expanded listing:

Use x on for narrower listings:

Postgresql syntax cheat sheet

c Connect to a database

To see what’s inside a database, connect to it using c followed by the database name. The prompt changes to match the name of the database you’re connecting to.(The one named postgres is always interesting.) Here we’re connecting to the one namedmarkets:

dt Display tables

  • Use dt to list all the tables (technically, relations) in the database:
  • If you choose a database such as postgres there could be many tables.Remember you can pause output by pressing space or halt it by pressing q.

d and d+ Display columns (field names) of a table

To view the schema of a table, use d followed by the name of the table.

  • To view the schema of a table named customerpaymentsummary, enter

To view more detailed information on a table, use d+:

du Display user roles

  • To view all users and their roles, use du:
Postgresql Cheat Sheet
  • To view the role of a specific user, pass it after the du command.For example, to see the only tom role:

Creating a database

Before you add tables, you need to create a database to contain those tables.That’s not done with psql, but instead it’s done with createdb(a separate external command; see the PostgreSQL createdb documentation) at the operating system command line:

On success, there is no visual feedback. Thanks, PostgreSQL.

Adding tables and records

Creating a table (CREATE TABLE)

To add a table schema to the database:

And psql responds with:

For more see CREATE TABLE in the PostgreSQL official docs.

Adding a record (INSERT INTO)

  • Here’s how to add a record, populating every field:
Postgresql Cheat Sheet

PostgreSQL responds with:

  • Try it again and you get a simliar response.

Adding (inserting) several records at once

  • You can enter a list of records using this syntax:

Adding only specific (columns) fields from a record

Gamesunblocked games ftw. You can add records but specify only selected fields (also known as columns). MySQL will use common sense default values for the rest.

In this example, only the name field will be populated. The sku column is left blank, and the id column is incremented and inserted.

Two records are added:

Postgresql Commands Cheat Sheet

PostgreSQL responds with the number of records inserted:

For more on INSERT, see INSERT in the PostgreSQL official docs

Doing a simple query–get a list of records (SELECT)

Probably the most common thing you’ll do with a table is to obtain information about itwith the SELECT statement. It’s a huge topic

  • Let’s list all the records in the product table:

The response:

Note

If your table has mixed case objects such as column names or indexes, you’ll need to enclose them in double quotes. For example, If a column name were Product instead of product your query would need to look like this:

For more on SELECT, see the SELECT in the PostgreSQL official docs.

Maintenance and operations issues

Timing

t Timing SQL operations

Use t to show timing for all SQL operations performed.

CommandEffect
timing offDisable timing of SQL operations
timing onShow timing after all SQL operations
timingToggle (reverse) the setting

Example of t Timing command

Watch

The watch command repeats the previous command at the specified interval.To use it, enter the SQL command you want repeated, thenuse watch followed by the number of seconds you want forthe interval between repeats, for rexample, watch 1to repeat it every second.

Example of the Watch command

Here’s an example of using watch to see if any records have beeninserted within the last 5 seconds.

Locate the pg_hba.conf file

Postgres configuration is stored in a file named pg_hba.confsomewhere in the file system, butthat location varies widely. The way to find it is to use show hba_file like this:

Postgresql Cheat Sheet Github

See below for hot reloading this file while Postgres is running.

Reload the configuration file while Postgres is running

If you make changes to the pg_hba.conf Postgres configuration sometimes you need to restart.But you may just choose to reload the pg_hba.conf configuration file like this:

Reference

Postgresql Json Cheat Sheet

  • PostgreSQL offical docs: Server Administration
  • psql , a.k.a the PostgreSQL interactive terminal
  • createdb in the PostgreSQL offical docs
  • CREATE TABLE in the PostgreSQL official docs
  • INSERT in the PostgreSQL official docs