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

Data Analysis With SQL: Postgresql Cheat Sheet

This document provides a summary of common SQL statements and functions for sorting, filtering, and manipulating data in PostgreSQL. It covers basic statements like SELECT, WHERE, ORDER BY, LIMIT, and DISTINCT. It also summarizes string, numeric, and date functions as well as aggregate functions, conditional expressions, and type conversions.

Uploaded by

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

Data Analysis With SQL: Postgresql Cheat Sheet

This document provides a summary of common SQL statements and functions for sorting, filtering, and manipulating data in PostgreSQL. It covers basic statements like SELECT, WHERE, ORDER BY, LIMIT, and DISTINCT. It also summarizes string, numeric, and date functions as well as aggregate functions, conditional expressions, and type conversions.

Uploaded by

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

Sort the Result Set

Data Analysis with SQL ORDER BY a single column ascending ORDER BY column
ORDER BY a single column descending ORDER BY column DESC
PostgreSQL Cheat Sheet
Created By Ram Kedem, Shuki Molk, Dotan Entin, and Elad Peleg ORDER BY column1,
ORDER BY multiple columns column2 DESC ..

Basic SQL Statements


Select all SELECT * FROM table Limit the Result Set
Select specific columns SELECT column1, column2 FROM table Retrieves first N rows SELECT ... LIMIT N
Arithmetic operations SELECT column + value FROM table TOP N Analysis SELECT .. ORDER BY .. LIMIT N
SELECT
string_column || ' ' || string_column
String concatenation FROM table
Common String Related Functions
RIGHT('hello' , 2)
Column alias SELECT column AS “alias”
Returns the right part of a string → 'lo'
Distinct values of a single SELECT DISTINCT column
LEFT('hello', 2)
column FROM table
Returns the left side of a string → 'he'
Distinct values of multiple SELECT DISTINCT column, column
Columns FROM table Returns the number of characters in
Quote column name in case a string LENGTH('hello') → 5
it contains spaces, Replaces all occurrences of a given REPLACE('hello world' ,'l', '*')
punctuation or conflicts substring → 'he**o wor*d'
with a reserved keyword SELECT “column” Reverses a string REVERSE('hello') → 'olleh'
SUBSTRING('hello world' , 2, 3)
Returns a substring of a string → 'ell'
Filter the Dataset
Returns a string in lower-case LOWER('HELLO') → 'hello'
Specify a numeric value 5
Returns a string in upper-case UPPER('hello') → 'HELLO'
Specify a string value 'string'
Returns the position of a substring in POSITION('e' IN 'hello')
Specify a date value '2019-05-28'
a string → 2
Basic operators WHERE column = value (or >, <, >=, <=, !=)
IN WHERE column IN (value1, value2, value3)
BETWEEN WHERE column BETWEEN value1 AND value2
LIKE WHERE column LIKE 'pattern'
IS NULL WHERE column IS NULL
IS NOT NULL WHERE column IS NOT NULL
AND WHERE condition1 AND condition2
OR WHERE condition1 OR condition2

RamKedem.com | Learn SQL by Doing!


Common Numeric Functions & Operations Common Null Handling Functions
Rounds the number ROUND(92.56, 1) → 92.6 Returns the specified value IF the expression COALESCE(column,
Rounds a number downwards the nearest is NULL, otherwise return the expression value_to_return_if_null)
integer FLOOR(92.56) → 92
Rounds a number upwards the nearest
integer CEILING(92.56) → 93 Conditional Expressions
Returns the absolute value of a number ABS(-28) → 28 CASE
Returns the square root of a number SQRT(100) → 10 WHEN condition1 THEN result1
Goes through a series of conditions
WHEN condition2 THEN result2
Returns a number raised to the power of and returns a value when the first
WHEN conditionN THEN resultN
another POWER(10, 2) → 100 condition is met ELSE result
If an integer dividend is divided by an END;
integer divisor, the result is an integer 5/2 → 2
Return a Decimal output from dividing Common Group Operations
two integers 5/(CAST 2 AS DECIMAL) → 2.5 Returns the average AVG()
Returns the minimum MIN()
Returns the maximum MAX()
Converting Values using CAST
Returns the sum SUM()
Convert a value to an int datatype CAST(5.25 as INT) → 5
Counts the number of rows in a table COUNT(*)
Convert a value to a varchar
Counts the number of values in a column COUNT(column)
datatype: CAST(5.25 as VARCHAR) → '5.25'
Counts the number of distinct values in a column COUNT(DISTINCT column)
Convert a value to a date datatype CAST('2020-01-25' AS DATE)
Divides the query result into groups of rows GROUP BY column, column…
Convert a value to a decimal
datatype CAST(5 AS DECIMAL) Filter condition based on a group or aggregate HAVING <condition>
Returns the aggregation result for each row in the agg_function() OVER ()
table
Common Date Related Functions Returns the aggregated results for each partition, agg_function()
Returns the current database date CURRENT_DATE in each row (of the same partition) OVER (PARTITION BY .. )
Adds a time/date interval to a date CURRENT_DATE + INTERVAL '1 DAY'
Return the difference between two Depends on the exact diff calculation, you can agg_function()
date values use various expressions or UDFs Returns the cumulative aggregated results OVER (ORDER BY.. )
Returns the year of a specified date DATE_PART('year', CURRENT_DATE)
Returns the month of a specified agg_function()
date DATE_PART('month', CURRENT_DATE) Returns the cumulative aggregated results in OVER (PARTITION BY..
Returns the day of a specified date DATE_PART('day', CURRENT_DATE)
each partition ORDER BY..)

RamKedem.com | Learn SQL by Doing!


Syntax vs Execution Order SET Operators
SELECT … FROM table_1
Combines the result set of two or more SELECT
Writing Execution UNION ALL
statements (allows duplicate values)
SELECT FROM (Joins included) SELECT … FROM table_2
FROM (JOINs included) WHERE SELECT … FROM table_1
Combines the result set of two or more SELECT
WHERE GROUP BY UNION
statements (only distinct values)
GROUP BY HAVING SELECT … FROM table_2
HAVING SELECT SELECT … FROM table_1
Returns the intersection of two SELECT
ORDER BY ORDER BY INTERSECT
statements
SELECT … FROM table_2
SELECT … FROM table_1
Returns any distinct values from the query left
Subqueries in the WHERE Clause EXCEPT
of the EXCEPT operator
Single row Subqueries WHERE column = (INNER QUERY) SELECT … FROM table_2
Comparing against multiple values WHERE column IN (INNER QUERY)

Ranking Functions
JOIN Operations Returns the rank of each row RANK()
FROM table1 t1 INNER JOIN table2 t2 OVER (PARTITION BY.. ORDER BY..)
within the partition of a result
Inner ON <condition>
FROM table1 t1 FULL OUTER JOIN table2 t2 set. The rank of a row is one
Full outer ON <condition> plus the number of ranks that
FROM table1 t1 LEFT OUTER JOIN table2 t2 come before the row in
Outer Left ON <condition> question.
FROM table1 t1 RIGHT OUTER JOIN table2 t2 DENSE_RANK()
Returns the rank of each row
Outer Right ON <condition> OVER (PARTITION BY.. ORDER BY..)
within a result set partition. The
rank of a specific row is one
CTE plus the number of distinct rank
values that come before that
A common table expression (CTE) is a named temporary result set that exists within the
specific row.
scope of a single statement and that can be referred to later within that statement,
Returns the sequential number ROW_NUMBER()
possibly multiple times OVER (PARTITION BY.. ORDER BY..)
of a row within a partition of a
result set, starting at 1
WITH expression_name [ ( column_name [,...n] ) ] Divides the result set produced NTILE(n)
AS by the FROM clause into OVER (PARTITION BY.. ORDER BY..)
( CTE_query_definition ) partitions

RamKedem.com | Learn SQL by Doing!


Analytic Functions Essential Data Types
LAG(column) OVER (PARTITION BY..
Accesses data from a previous row ORDER BY..) String Data Types Description
in the same result CHAR(number) A fixed number of characters
LEAD(column) OVER (PARTITION BY..
Accesses data from a subsequent ORDER BY..) VARCHAR(number) A variable number of characters
row in the same result set
Numeric Data
Types Description
PIVOT SMALLINT -32768 to +32767
PIVOT rotates a table-valued expression by turning the unique values from one column in INTEGER -2147483648 to +2147483647
the expression into multiple columns in the output
Integers between (-9,223,372,036,854,775,808) and
BIGINT
SELECT .. 9,223,372,036,854,775,807
FROM (SELECT query that produces the data for axis) AS alias Numbers from (-10^38 +1) to (10^38 –1)
PIVOT DECIMAL(p,s) p = total number of digits, s = number of decimal digits. I.e
(aggregate_function (column) 123.4567 → p=7, s=4
FOR x_axis_column IN (list of values)
NUMERIC(p,s) numeric is functionally identical to decimal
) AS alias
Date Data Types Description
TIMESTAMP With / without time zone, accuracy of 1 microsecond
UNPIVOT
UNPIVOT carries out the opposite operation to PIVOT by rotating columns of a table-valued DATE
Accuracy of 1 day
expression into column values
SELECT ..
FROM (SELECT columns participating in the process) AS alias
UNPIVOT
(column_representing_z_values
FOR
column_representing_x_values IN (list of values..
) AS alias

RamKedem.com | Learn SQL by Doing!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy