You are on page 1of 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
MSSQL 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 TOP N ...
Arithmetic operations SELECT column + value FROM table Retrieves first N percent SELECT TOP N PERCENT ..
SELECT TOP N Analysis SELECT TOP N .. ORDER BY ..
string_column + ' ' + string_column
String concatenation FROM table
Common String Related Functions
Column alias SELECT column AS 'alias'
RIGHT('hello' , 2)
Distinct values of a single SELECT DISTINCT column
FROM table Returns the right part of a string → 'lo'
column
Distinct values of multiple SELECT DISTINCT column, column LEFT('hello', 2)
Columns FROM table Returns the left side of a string → 'he'
Quote column name in case Returns the number of characters in
it contains spaces, a string LEN('hello') → 5
punctuation or conflicts Replaces all occurrences of a given REPLACE('hello world' ,'l', '*')
with a reserved keyword SELECT [column_name] substring → 'he**o wor*d'
Reverses a string REVERSE('hello') → 'olleh'
SUBSTRING('hello world' , 2, 3)
Filter the Dataset
Returns a substring of a string → 'ell'
Specify a numeric value 5
Returns a string in lower-case LOWER('HELLO') → 'hello'
Specify a string value 'string'
Returns a string in upper-case UPPER('hello') → 'HELLO'
Specify a date value '2019-05-28'
Returns the position of a substring in CHARINDEX('e', 'hello')
Basic operators WHERE column = value (or >, <, >=, <=, !=)
a string → 2
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 ISNULL(column,
Returns the specified value IF the expression
Rounds a number downwards the nearest value_to_return_if_null)
is NULL, otherwise return the expression
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
Returns the square root of a number SQRT(100) → 10 CASE
WHEN condition1 THEN result1
Goes through a series of conditions
Returns a number raised to the power of WHEN condition2 THEN result2
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()
Converting Values using CAST Returns the maximum MAX()
Convert a value to an int datatype CAST(5.25 as INT) → 5 Returns the sum SUM()
Convert a value to a varchar Counts the number of rows in a table COUNT(*)
datatype CAST(5.25 as VARCHAR) → '5.25' Counts the number of values in a column COUNT(column)
Convert a value to a date datatype CAST('2020-01-25' AS DATE) Counts the number of distinct values in a column COUNT(DISTINCT column)
Convert a value to a decimal Divides the query result into groups of rows GROUP BY column, column…
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 ()
Common Date Related Functions table
Returns the current database date GETDATE() Returns the aggregated results for each partition, agg_function()
DATEADD(YEAR, 1,'2020-01-24') in each row (of the same partition) OVER (PARTITION BY .. )
Adds a time/date interval to a date → 2021-01-24
DATEDIFF
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.. )
YEAR('2020-01-24')
Returns the year of a specified date → 1 agg_function()
Returns the month of a specified MONTH('2020-01-24') Returns the cumulative aggregated results in OVER (PARTITION BY..
date → 2020
DAY('2020-01-24') each partition ORDER BY..)
Returns the day of a specified date → 24

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
JOIN Operations Returns any distinct values from the query left
EXCEPT
FROM table1 t1 INNER JOIN table2 t2 of the EXCEPT operator
SELECT … FROM table_2
Inner ON <condition>
FROM table1 t1 FULL OUTER JOIN table2 t2
Full outer ON <condition>
Ranking Functions
FROM table1 t1 LEFT OUTER JOIN table2 t2
Returns the rank of each row RANK()
Outer Left ON <condition>
within the partition of a result OVER (PARTITION BY.. ORDER BY..)
FROM table1 t1 RIGHT OUTER JOIN table2 t2
Outer Right ON <condition> set. The rank of a row is one
plus the number of ranks that
come before the row in
Subqueries in the WHERE Clause
Single row Subqueries WHERE column = (INNER QUERY) question.
Returns the rank of each row DENSE_RANK()
Comparing against multiple values WHERE column IN (INNER QUERY)
within a result set partition. The OVER (PARTITION BY.. ORDER BY..)
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
scope of a single statement and that can be referred to later within that statement, specific row.
possibly multiple times Returns the sequential number ROW_NUMBER()
of a row within a partition of a OVER (PARTITION BY.. ORDER BY..)

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 /
row in the same result set MAX) A variable number of characters
Numeric Data Types Description
PIVOT TINYINT Integers between 0 and 255
PIVOT rotates a table-valued expression by turning the unique values from one column in SMALLINT Integers between (-32,768) and 32,767
the expression into multiple columns in the output INT Integers between (-2,147,483,648) and 2,147,483,647
SELECT .. Integers between (-9,223,372,036,854,775,808) and
FROM (SELECT query that produces the data for axis) AS alias BIGINT
9,223,372,036,854,775,807
PIVOT Numbers from (-10^38 +1) to (10^38 –1)
(aggregate_function (column) DECIMAL(p,s) p = total number of digits, s = number of decimal digits. I.e
FOR x_axis_column IN (list of values) 123.4567 → p=7, s=4
) AS alias
NUMERIC(p,s) numeric is functionally identical to decimal
BIT Holds either 0 ('false') of 1 ('true'). Can hold also NULL.
UNPIVOT
Date Data Types Description
UNPIVOT carries out the opposite operation to PIVOT by rotating columns of a table-
From 1753-Jan-01 to 9999-Dec-31 with an accuracy of 1/3
valued expression into column values DATETIME
millisecond (.000, .003, or .007 seconds)
SELECT ..
FROM (SELECT columns participating in the process) AS alias DATE
UNPIVOT From 1753-Jan-01 to 9999-Dec-31 with an accuracy of 1 day
(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