Postgresql Queries Cheat Sheet



Structured Query Language (SQL) is a set-based language as opposed to a procedural language. It is the defacto language of relational databases.

The difference between a set-based language vs. a procedural language is that in a set-based language you define what set of data you want or want to operate on and the atomic operation to apply to each element of the set. You leave it up to the Database process to decide how best to collect that data and apply your operations. In a procedural language, you basically map out step by step loop by loop how you collect and update that data.
There are two main reasons why SQL is often better to use than procedural code.

  • It is often much shorter to write - you can do an update or summary procedure in one line of code that would take you several lines of procedural.
  • For set-based problems - SQL is much faster processor-wise and IO wise too because all the underlining looping iteration is delegated to a database server process that does it in a very low level way and uses IO/processor more efficiently and knows the current state of the data - e.g. what other processes are asking for the data.

Example SQL vs. Procedural

Postgres Cheatsheet created by your friends at Timescale. Importing Data from CSV in PostgreSQL Insert multiple rows List the tables in SQLite opened with ATTACH Meta commands in PSQL Outputting Query Results to Files with o Random Sequences Show Tables in Postgres SQL Cheat Sheet.

If you were to update say a sales person of all customers in a particular region - your procedural way would look something like this

The SQL way would be:
UPDATE customers SET salesperson = 'Mike' WHERE state = 'NH'
If you had say 2 or 3 tables you need to check, your procedural quickly becomes difficult to manage as you pile on nested loop after loop.
In this article we will provide some common data questions and processes that SQL is well suited for and SQL solutions to these tasks. Most of these examples are fairly standard ANSI-SQL so should work on most relational databases such as IBM DBII, PostGreSQL, MySQL, Microsoft SQL Server, Oracle, Microsoft Access, SQLite with little change. Some examples involving subselects or complex joins or the more complex updates involving 2 or more tables may not work in less advanced relational databases such as MySQL, MSAccess or SQLite. These examples are most useful for people already familiar with SQL. We will not go into any detail about how these work and why they work, but leave it up to the reader as an intellectual exercise. What customers have bought from us?

Example: What customers have never ordered anything from us?
SELECT customers.* FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id WHERE orders.customer_id IS NULL
More advanced example using a complex join: What customers have not ordered anything from us in the year 2004 - this one may not work in some lower relational databases (may have to use an IN clause)Postgresql Queries Cheat SheetPostgresql queries cheat sheet pdf
SELECT customers.* FROM customers LEFT JOIN orders ON (customers.customer_id = orders.customer_id AND year(orders.order_date) = 2004) WHERE orders.order_id IS NULL
Please note that year is not an ANSI-SQL function and that many databases do not support it, but have alternative ways of doing the same thing.
  • SQL Server, MS Access, MySQL support year().
  • PostGreSQL you do date_part('year', orders.order_date)
  • SQLite - substr(orders.order_date,1,4) - If you store the date in form YYYY-MM-DD
  • Oracle - EXTRACT(YEAR FROM order_date) or to_char(order_date,'YYYY')
Note: You can also do the above with an IN clause, but an IN tends to be slower
Same question with an IN clause
SELECT customers.* FROM customers WHERE customers.customer_id NOT IN(SELECT customer_id FROM orders WHERE year(orders.order_date) = 2004)
How many customers do we have in Massachusetts and California?
SELECT customer_state As state, COUNT(customer_id) As total FROM customers WHERE customer_state IN('MA', 'CA') GROUP BY customer_state
What states do we have more than 5 customers?

How many states do we have customers in?

Note the above does not work in Microsoft Access or SQLite - they do not support COUNT(DISTINCT .)Postgresql cheat sheet pdf
Alternative but slower approach for the above - for databases that don't support COUNT(DISTINCT .), but support derived tablesList in descending order of orders placed customers that have placed more than 5 orders
Value Insert

Copy data from one table to another table

Creating a new table with a bulk insert from another table
Update from values
UPDATE customers SET customer_salesperson = 'Billy' WHERE customer_state = 'TX'
Update based on information from another table
UPDATE customers SET rating = 'Good' FROM orders WHERE orderdate > '2005-01-01' and orders.customer_id = customers.customer_id
Please note the date format varies depending on the database you are using and what date format you have it set to.
Update based on information from a derived table
Please note the update examples involving additional tables do not work in MySQL, MSAccess, SQLite.
MS Access Specific syntax for doing multi-table UPDATE joins
UPDATE customers INNER JOIN orders ON customers.customer_id = orders.customer_id SET customers.rating = 'Good'
MySQL 5 Specific syntax for doing multi-table UPDATE joins
UPDATE customers, orders SET customers.rating = 'Good' WHERE orders.customer_id = customers.customer_id
Articles of Interest
PostgreSQL 8.3 Cheat SheetSummary of new and old PostgreSQL functions and SQL constructs complete xml query and export, and other new 8.3 features, with examples.
SQLiteIf you are looking for a free and lite fairly SQL-92 compliant relational database, look no further. SQLite has ODBC drivers, PHP 5 already comes with an embedded SQLite driver, there are .NET drivers, freely available GUIs , and this will run on most Oses. All the data is stored in a single .db file so if you have a writeable folder and the drivers, that’s all you need. So when you want something lite and don't want to go thru a database server install as you would have to with MySQL, MSSSQL, Oracle, PostgreSQL, or don't have admin access to your webserver and you don't need database group user permissions infrastructure, this is very useful. It also makes a nice transport mechanism for relational data as the size the db file is pretty much only limited to what your OS will allow for a file (or 2 terabytes which ever is lower).
PostgreSQL Date FunctionsSummary of PostGresql Date functions in 8.0 version
The Future of SQL by Craig MullinsProvides a very good definition of what set-based operations are and why SQL is superior for these tasks over procedural, as well as a brief history of the language.
Summarizing data with SQL (Structured Query Language)Article that defines all the components of an SQL statement for grouping data. We wrote it a couple of years ago, but it is still very applicable today.
Procedural Versus Declarative LanguagesProvides some useful anlaogies for thinking about the differences between procedural languages and a declarative language such as SQL
PostgreSQL Cheat SheetCheat sheet for common PostgreSQL tasks such as granting user rights, backing up databases, table maintenance, DDL commands (create, alter etc.), limit queries
MySQL Cheat SheetCovers MySQL datatypes, standard queries, functions
Comparison of different SQL implementationsThis is a great summary of the different offerings of Standard SQL, PostGreSQL, DB2, MSSQL, MySQL, and Oracle. It demonstrates by clear example how each conforms or deviates from the ANSI SQL Standards with join syntax, limit syntaxx, views, inserts, boolean, handling of NULLS

Introduction to the PostgreSQL cheat sheet

If you’re using PostgreSQL to store and query your data, you might find yourself needing to look up the syntax of some common statements and queries. There’s no need to go searching for this information– we’ve rounded up some of the most common SQL statements and queries and created a PostgreSQL cheat sheet for you. This handy reference guide will help you perform many common PostgreSQL tasks using the psql command-line interface.

Note that SQL statements in psql must terminate with a semicolon. This syntax lets Postgres knows where a statement ends; otherwise, PostgreSQL will interpret the next line as an extension of that same command.

Another thing to keep in mind when constructing SQL statements is that PostgreSQL strings must always be enclosed using single quotation marks (e.g. 'string here'). Using double quotes will result in a syntax error.

You can press CTRL+C if you’d like to escape a command or exit from the results of a command.

Prerequisites to using PostgreSQL SQL commands in psql

Before we proceed with our PostgreSQL cheat sheet, let’s review a few prerequisites that are necessary to get the most out of this article. You should have PostgreSQL installed, and you’ll need to have a PostgreSQL role with access to a database in order to execute the SQL statement examples found in this article. You’ll also need to use psql, the command-line interface for PostgreSQL. Use the psql -V command to find out which version of the interface is installed on your machine.

Accessing PostgreSQL using the ‘psql’ command line interface

We can use the following syntax to access a PostgreSQL database on a localhost server. The command should be executed using the psql command-line interface:

psql postgres

The command shown above will try to connect to the PostgreSQL database named postgres.

You can also use the alternative syntax shown below to connect to PostgreSQL using a username, host and database name:

psql -U some_username -h 127.0.0.1 -d some_database

NOTE: Notice that a few different flags are used in this command syntax. The -U flag represents the Postgres username, and the -h flag indicates the host domain or IP address. The -d flag is used to provide the database name. If only one parameter is supplied, psql will assume it is the database name.

PostgreSQL cheat sheet of useful SQL queries and commands

The following section provides an overview of some of the most common SQL commands used to manage and alter Postgres roles, indexes and tables.

PostgreSQL cheat sheet to manage the roles and users

In Postgres, a role is the entity that is granted privileges to access and modify database and table data. A role can be either a user or a group. You can create a new role using the following syntax:

To add a username and password to the new role, simply use the command:

CREATEROLE new_role NOINHERIT
LOGIN PASSWORD 'mYpAsSwOrDyO!';

Router app for mac. We can assign a new role to our current psql session:

The last command we’ll review in this section is used to create a user with an encrypted password:

CREATEUSER new_user
WITH ENCRYPTED PASSWORD 'mYpAsSwOrDyO!';

Grant privileges to a Postgres user or role

Now that we know how to create a user or role, let’s discuss how to grant a user privileges. The following command uses the GRANT CONNECT keyword to grant a Postgres user access to a specific database:

Postgresql Query Example

Here’s how we can grant all privileges for public tables to the same user:

GRANTALL PRIVILEGES ONALLTABLES
IN SCHEMA public TO new_user;

Revoke all privileges for a PostgreSQL user or role

Not only can you grant privileges to a user, but you can also take them away. The following command will reverse the one shown above and REVOKEall of a role’s privileges for all tables:

REVOKEALL PRIVILEGES ONALLTABLES
IN SCHEMA public FROM new_user;

The same can be done for database privileges:

REVOKEALL PRIVILEGES ONDATABASE
some_db FROM new_user;

Last but not least, let’s look at an example of how to revoke database ownership for the user:

PostgreSQL cheat sheet commands for table views

In this section, we’ll look at some commands related to views. A PostgreSQL VIEW is a way of logically organizing data that’s meant to represent the column data of tables.

The following example uses the CREATE VIEW SQL keywords. It also uses the AS keyword to give the view database object a name:

CREATEVIEW some_view AS col_data;

The next example creates a view object that consists of the column names col1 and col2:

CREATEVIEW some_view(col1, col2)
ASSELECT col1, col2 FROM some_table;

If you need to DROP, or delete, a view from your database, here’s how to do it:

PostgreSQL cheat sheet commands for indices

Cheat

In this section, we’ll look at some common commands used to manage indexes. To create an index, we use the following command:

CREATEINDEX some_index ON some_table(col_name, second_col);

The DROP INDEX command is used to remove a specified index from a table: Smarthru 4 samsung for mac.

PostgreSQL cheat sheet commands for Triggers

In SQL, a TRIGGER is a callback or function that will automatically execute a SQL statement when a certain event occurs. The basic structure of a PostgreSQL trigger is shown below:

CREATETRIGGER some_trigger
[WHEN EVENT]ON some_table
[TRIGGERTYPE]EXECUTE stored_procedure;

NOTE: The WHEN EVENT and TRIGGER TYPE keywords are optional.

PostgreSQL cheat sheet commands for tables

The syntax for the SQL command used to create a new table looks like the following:

CREATETABLE some_table
(some_column +DATATYPE+ CONSTRAINTS [OPTIONAL]);

Let’s look at an example of how you can use the CREATE TABLE keyword to create a Postgres table comprised of a string column and an integer column:

CREATETABLE some_table (
id INTPRIMARYKEY,
some_str VARCHAR(30),
some_int INT
);

NOTE: Our example contains the PRIMARY KEY constraint, which tells Postgres to make the value of that particular column the main identifying information for the record.

If you need to rename a Postgres table, you can use the ALTER TABLE and RENAME commands:

To drop a table and all of its dependent objects:

DROPTABLE[IFEXISTS] some_table CASCADE;

To add a new column to an existing table, use the following command: Waves plugins for mac os x.

ALTERTABLE some_table ADDCOLUMN some_column DATATYPE;

To rename a specific column in an existing table, use the command shown below:

Postgresql Cheat Sheet Pdf

ALTERTABLE some_table RENAME some_column TO some_column;

To drop a column from a table, use the following command:

To remove the SQL primary key constraint from a table, we use the ALTER TABLE and DROP CONSTRAINT commands:

Postgresql Queries Cheat Sheet Pdf

ALTERTABLE some_table
DROPCONSTRAINT primary_key_constraint_name;

NOTE: Some common examples of a PRIMARY KEY constraint would be NOT NULL or UNIQUE.

Conclusion to the PostgreSQL cheat sheet

Postgresql Queries Cheat Sheet Example

If you’re just getting started with PostgreSQL, it may seem like there’s a lot to learn; however, having a PostgreSQL cheat sheet handy can make it easier to perform everyday database tasks. In this article, we covered many of the common commands and queries used in PostgreSQL. In the next installment of this two-part series, we’ll pick up where we left off and look at some more examples of PostgreSQL syntax.