SQL Cheat Sheet PDF - Hackr - Io
SQL Cheat Sheet PDF - Hackr - Io
database objects
numeric Numeric data type with a fixed precision and scale (exact numeric)
3. Managing Tables
After we’ve created a database, the next step is to create and subsequently manage a
database table using a range of our DDL commands.
Create a Table
A table can be created with the CREATE TABLE statement.
Example: Create a table named EmployeeLeave within the Human Resource schema
and with the following attributes.
Modifying a Table
We can use the ALTER TABLE statement to modify a table when:
1. Adding a column
The contents of a table can be deleted (without deleting the table) by using the
TRUNCATE TABLE statement:
4. Manipulating Data
Database tables are rarely static and we often need to add new data, change existing
data, or remove data using our DML commands.
Syntax for copying data from one table to another with the INSERT statement:
UPDATE table_name
SET col_name1 = value1, col_name2 = value2…
WHERE condition;
Example: Update the value in the Marks column to ‘85’ when FirstName equals ‘Andy’
UPDATE table_name
SET Marks = 85
WHERE FirstName = ‘Andy’;
Remove all rows (records) from a table without deleting the table with DELETE:
5. Retrieving Data
We can display one or more columns when we retrieve data from a table. For example,
we may want to view all of the details from the Employee table, or we may want to view
a selection of particular columns.
Data can be retrieved from a database table(s) by using the SELECT statement.
Consider the data and schema for the Student table below.
Note: We should use the HAVING clause instead of WHERE with aggregate functions.
Comparison Operators
Comparison operators test for the similarity between two expressions.
Logical Operators
Logical operators are used with SELECT statements to retrieve records based on one
or more logical conditions. You can combine multiple logical operators to apply multiple
search conditions.
Range Operations
We can use BETWEEN and NOT BETWEEN statements to retrieve data based on a
range.
6. SQL JOINS
Joins are used to retrieve data from more than one table where the results are ‘joined’
into a combined return data set. Two or more tables can be joined based on a common
attribute.
Consider two database tables, Employees and EmployeeSalary, which we’ll use to
demonstrate joins.
Types of JOIN
The two main types of join are an INNER JOIN and an OUTER JOIN.
Inner JOIN
An inner join retrieves records from multiple tables when a comparison operation
returns true for a common column. This can return all columns from both tables, or a set
of selected columns.
Outer JOIN
An outer join displays the following combined data set:
● Every row from one of the tables (depends on LEFT or RIGHT join)
● Rows from one table that meets a given condition
An outer join will display NULL for columns where it does not find a matching record.
RIGHT OUTER JOIN: every row from the ‘right’ table (right of the RIGHT OUTER JOIN
keyword) is returned, and matching rows from the ‘left’ table are returned.
FULL OUTER JOIN: returns all the matching and non-matching rows from both tables,
with each row being displayed no more than once.
Cross JOIN
Also known as the Cartesian Product, a CROSS JOIN between two tables (A and B)
‘joins’ each row from table A with each row in table B, forming ‘pairs’ of rows. The joined
dataset contains ‘combinations’ of row ‘pairs’ from tables A and B.
The row count in the joined data set is equal to the number of rows in table A multiplied
by the number of rows in table B.
Equi JOIN
An EQUI JOIN is one which uses an EQUALITY condition for the table keys in a JOIN
operation. This means that INNER and OUTER JOINS can be EQUI JOINS if the
conditional clause is an equality.
Self JOIN
A SELF JOIN is when you join a table with itself. This is useful when you want to query
and return correlatory information between rows in a single table. This is helpful when
there is a ‘parent’ and ‘child’ relationship between rows in the same table.
To prevent issues with ambiguity, it’s important to use aliases for each table reference
when performing a SELF JOIN.
7. SQL Subqueries
An SQL statement that is placed within another SQL statement is a subquery.
Subqueries are nested inside WHERE, HAVING or FROM clauses for SELECT,
INSERT, UPDATE, and DELETE statements.
Example: run a subquery with a condition to return a data set. The subquery results
then become part of the main query’s conditional clause. We can then use the IN
keyword to filter main query results against subquery results for a particular column(s).
We can also use EXISTS to filter subquery results based on any provided conditions.
You can think of it like a conditional ‘membership’ check for any data that is processed
by the subquery statement.
We use nested subqueries when the condition of one query is dependent on the result
of another, which in turn, may also be dependent on the result of another etc.
Correlated Subquery
A correlated subquery is a special type of subquery that uses data from the table
referenced in the outer query as part of its own evaluation.
dateadd (date part, number, Adds the ‘number’ of date parts to the date
date)
datediff (date part, date1, Calculates the ‘number’ of date parts between
date2) two dates
Datename (date part, date) Returns the date part from a given date as a
character value
datepart (date part, date) Returns the date part from a given date as an
integer value
acos, asin, atan (numeric_expression) Returns the arc cos, sin, or tan angle in
radians
cos, sin, tan, cot (numeric_expression) Returns the cos, sine, tan or cotangent
in radians
● dense_rank() : used when consecutive ranking values are needed for a given
Each ranking function uses the OVER clause to specify the ranking criteria. Within this,
we choose a column to use for assigning a rank along with the ORDER BY keyword to
determine whether ranks should be applied based on ascending or descending values.
Function Description
Name
avg Returns the average from a range of values in a given data set or
expression. Can include ALL values or DISTINCT values
sum Returns the sum of values in a given data set or expression. Can
include ALL values or DISTINCT values
9. Grouping Data
We have the option to group data in our result set based on a specific criteria. We do
this by using the optional GROUP BY, COMPUTE, COMPUTE BY, and PIVOT clauses
with a SELECT statement.
GROUP BY Clause
When used without additional criteria, GROUP BY places data from a result set into
unique groups. But when used with an aggregate function, we can summarize
(aggregate) data into individual rows per group.
Note: support for this keyword was dropped by MS SQL Server in 2012.
PIVOT Clause
The PIVOT operator is used to transform unique rows into column headings. You can
think of this as rotating or pivoting the data into a new ‘pivot table’ that contains the
summary (aggregate) values for each rotated column. With this table, you can examine
trends or summary values on a columnar basis.
The term ACID stands for Atomicity, Consistency, Isolation, and Durability. These
individual properties represent a standardized group that are required to ensure the
reliable processing of database transactions.
Atomicity
The concept that an entire transaction must be processed fully, or not at all.
Consistency
The requirement for a database to be consistent (valid data types, constraints, etc) both
before and after a transaction is completed.
Isolation
Transactions must be processed in isolation and they must not interfere with other
transactions.
Durability
After a transaction has been started, it must be processed successfully. This applies
even if there is a system failure soon after the transaction is started.
11. RDBMS
A Relational Database Management System (RDBMS) is a piece of software that
allows you to perform database administration tasks on a relational database, including
creating, reading, updating, and deleting data (CRUD).
Relational databases store collections of data via columns and rows in various tables.
Each table can be related to others via common attributes in the form of Primary and
Foreign Keys.