0% found this document useful (0 votes)
6 views

SQL cheat sheet

This document is a PostgreSQL cheat sheet that provides essential commands and syntax for database operations, including creating tables, inserting data, and performing queries. It covers topics such as joins, window functions, data types, and logical operators, along with examples for clarity. Additionally, it includes command line options and internal commands for using PostgreSQL effectively.

Uploaded by

Ambar Majumdar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

SQL cheat sheet

This document is a PostgreSQL cheat sheet that provides essential commands and syntax for database operations, including creating tables, inserting data, and performing queries. It covers topics such as joins, window functions, data types, and logical operators, along with examples for clarity. Additionally, it includes command line options and internal commands for using PostgreSQL effectively.

Uploaded by

Ambar Majumdar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

.....

PostgreSQL cheat sheet columnN datatype


);
Our practice databases
• Host: imperial-2021.ckp3dl3vzxoh.eu-west- Deleting a table
2.rds.amazonaws.com DROP TABLE table_name;
• Username: imperial
• Password: imperial-fdt-online-2019- Inserting into a new table
colossal-shelf insert into items_ver (item_id, name, item_group)
• Port: 5432 select item_id, name, item_group from items where
• Database: dvdrental or northwind or movies item_id=2;
or world
Joins: shortcut syntax
In Postgres
SELECT *
• Single quotes only - no double quotes FROM weather w, cities c
• This is a Postgres cheat sheet. MySQL or WHERE w.city = c.name;
other versions of SQL may operate slightly
differently. SELECT *
Standard query structure FROM weather, cities
• SELECT (including window functions) WHERE city = name;
• FROM
• JOINs, each with an ON SELECT *
• WHERE FROM weather INNER JOIN cities
ON weather.city = cities.name;
• ORDER BY
• LIMIT Window functions
OVER indicates a window function
Query tips
• Build up your query slowly, running it as expression OVER (PARTITION BY attribute)
you go; start with a simple SELECT
• Capitalise all SQL keywords expression OVER (ORDER BY attribute)
• Use newlines clearly to break up the query
SELECT depname, empno, salary, avg(salary)
SELECT * FROM table_name OVER (PARTITION BY depname)
SELECT col_name FROM table_name FROM empsalary;
SELECT DISTINCT col_name FROM table_name
Use LAG(column) to lag one column and LAG(column,
GROUP BY: n) to lag n columns. For example,
SELECT department, COUNT(employee_id)
FROM employees LAG(price, 2) OVER (ORDER BY date) will create a
GROUP BY department new column with price values lagged by 2.
Every GROUP BY needs an aggregate function: one of LEAD is the opposite of LAG.
COUNT, AVG, MAX, MIN, SUM
Subqueries
Joins SELECT *
SELECT col1, col2 FROM film
FROM some_table WHERE rental_rate >
INNER JOIN some_other_table (SELECT AVG(rental_rate) FROM film)
ON some_table.key = some_other_table.key
SELECT * FROM
A sample query (SELECT * FROM film) AS film_table
SELECT col1, col2
FROM some_table CTEs
INNER JOIN some_other_table WITH my_cte AS ( CTE query ),
ON some_table.key = some_other_table.key my_second_cte AS ( second CTE query ),
WHERE col1>4 main query
ORDER BY col1 DESC
LIMIT 100 Views
CREATE VIEW my_view AS
Updating view query
UPDATE table_name
SET column1 = value1, column2 = value2, ... You can also use CREATE OR REPLACE VIEW
WHERE condition; or DROP VIEW
Creating a new table Loading data from a CSV
CREATE TABLE table_name( COPY movie
column1 datatype, FROM '/path/to/data.csv'
column2 datatype, DELIMITER ','
column3 datatype, WITH CSV HEADER
(The postgres regexp is similar to standard
\copy table_name FROM full_path WITH CSV HEADER; regexps, see the documentation)

Standard data types Dates and times


varchar(size) length-limited string time
text string of any length time with timezone
integer 4-byte signed -
2147483648 to +2147483647 date
bigint 8-byte signed timestamp (both date and time)
serial 4-byte autoincrementing timestamp with timezone
real 4-byte floating point
double precision 8-byte floating point
money currency date '2001-09-28' + time '03:00'
bool or boolean true/false date '2001-09-28' + integer '7'
date '2001-09-28' + interval '1 hour'
Date/time types timestamp '2001-09-28 01:00' + interval '23 hours'
date timestamp '2001-09-29 03:00' - timestamp '2001-09-
timestamp 27 12:00'
timestamp with timezone time '05:00' - interval '2 hours'
time
time with timezone DATE(col) converts to date
CURRENT_DATE
Logical operators CURRENT_TIME
AND, OR, NOT CURRENT_TIMESTAMP
NOW() returns timestamp with timezone
Comparison operators date_trunc('hour', date) zeros all more granular parts
>, <, >=, <=, =, != or <> date_part('hour', date) extracts this particular part
(start1, end1) OVERLAPS (start2, end2)
a BETWEEN x AND y (start1, length1) OVERLAPS (start2, length2)
a IS DISTINCT FROM b
a IS NOT DISTINCT FROM b Advanced aggregate functions
a IS NULL
a IS NOT NULL VARIANCE(col)
STDDEV(col)
expression = NULL will not work because nothing is EVERY(col) bool to bool
equal to null (an unknown value)
Subquery operators
Boolean expressions
expression IS TRUE EXISTS (subquery)
expression IS NOT TRUE expression IN (subquery)
expression IS FALSE expression NOT IN (subquery)
expression IS NOT FALSE
expression IS UNKNOWN
expression IS NOT UNKNOWN expression operator ANY (subquery)
expression IS NULL expression operator SOME (subquery)
expression operator ALL (subquery)
Set union: table_1 UNION table_2
Set intersection: table_1 INTERSECT table_2
Set difference: table_2 EXCEPT table_2 psql: command line options
Check two queries for equality: (SELECT ...) = (SELECT ...)
-h host set the host (such as localhost or
Operators the AWS server)
+ - * / -p port set the port (default 5432)
% (modulo)

You can use various mathematical functions like -U user connect to Postgres with a
floor(), ceil(), round(). See the Postgres particular Postgres username
documentation for more. -f file run an SQL file (do queries or
load data)
|| string concatenation -E show extra information about psql
operations
String matching
string LIKE pattern -d database connect to a particular database

_ matches a single character


% matches a string of zero or more characters psql: internal commands
Examples: help show help
'abc' LIKE 'abc' true \q quit
'abc' LIKE 'a%' true \l list databases
'abc' LIKE '_b_' true
'abc' LIKE 'c' false \c database connect to a particular database
\dt list tables in current database
string SIMILAR TO postgres_regexp \lv list views
\du list database users

You might also like