Data Analysis With SQL: Mysql Cheat Sheet
Data Analysis With SQL: Mysql Cheat Sheet
Data Analysis with SQL ORDER BY a single column ascending ORDER BY column
ORDER BY a single column descending ORDER BY column DESC
MySQL Cheat Sheet
Created By Ram Kedem, Shuki Molk, Dotan Entin, and Elad Peleg ORDER BY column1,
ORDER BY multiple columns column2 DESC ..
Common Date Related Functions Filter condition based on a group or aggregate HAVING <condition>
Returns the current database date CURDATE() Returns the aggregation result for each row in the agg_function() OVER ()
DATE_ADD table
("2020-01-24", INTERVAL 1 YEAR) Returns the aggregated results for each partition, agg_function()
Adds a time/date interval to a date → 2021-01-24 in each row (of the same partition) OVER (PARTITION BY .. )
TIMESTAMPDIFF
Return the difference between two (MONTH, '2020-01-24', '2020-04-24') agg_function()
date values → 3 Returns the cumulative aggregated results OVER (ORDER BY.. )
Returns the year of a specified date YEAR('2020-01-24') → 1
Returns the month of a specified MONTH('2020-01-24') agg_function()
date → 2020 Returns the cumulative aggregated results in OVER (PARTITION BY..
Returns the day of a specified date DAY('2020-01-24') → 24
each partition ORDER BY..)
Writing Execution A common table expression (CTE) is a named temporary result set that exists within the
SELECT FROM (Joins included) scope of a single statement and that can be referred to later within that statement,
FROM (JOINs included) WHERE possibly multiple times
WHERE GROUP BY
GROUP BY HAVING
WITH expression_name [ ( column_name [,...n] ) ]
HAVING SELECT
AS
ORDER BY ORDER BY
( CTE_query_definition )
LIMIT LIMIT
SET Operators
JOIN Operations
SELECT … FROM table_1
FROM table1 t1 INNER JOIN table2 t2 Combines the result set of two or more SELECT
UNION ALL
Inner ON <condition> statements (allows duplicate values)
SELECT … FROM table_2
FROM table1 t1 LEFT OUTER JOIN table2 t2
SELECT … FROM table_1
ON <condition> Combines the result set of two or more SELECT
UNION
UNION statements (only distinct values)
SELECT … FROM table_2
FROM table1 t1 RIGHT OUTER JOIN table2 t2
ON <condition> SELECT ..
Full outer Returns the intersection of two SELECT
FROM table1 t1 LEFT OUTER JOIN table2 t2 FROM table_1
statements
Outer Left ON <condition> WHERE col
(Emulates INTERSECT using IN and subquery)
FROM table1 t1 RIGHT OUTER JOIN table2 t2 IN (SELECT col FROM table_2)
Outer Right ON <condition>
SELECT ..
Returns any distinct values from the query left
FROM table_1
of the EXCEPT operator
Subqueries in the WHERE Clause WHERE col
(Emulates EXCEPT using NOT IN and subquery)
Single row Subqueries WHERE column = (INNER QUERY) NOT IN
(SELECT col FROM table_2)
Comparing against multiple values WHERE column IN (INNER QUERY)