SQL CHEAT SHEET:
- By Yash Shirodkar.
I was able to create this cheet sheat with the help of W3 School and other online available
resources. (Link- https://www.w3schools.com/sql/)
Create Database-
CREATE DATABASE databasename;
Drop Database-
DROP DATABASE databasename;
Backup Database-
BACKUP DATABASE databasename
TO DISK = 'filepath';
Create table-
CREATE TABLE Persons (
PersonID int NOT NULL UNIQUE,
Age int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY Firstname,
Check (age>=21 and city = ‘NY’)
);
Drop Table-
DROP TABLE table_name;
Alter Table-
The ALTER TABLE statement is used to add, drop, or alter columns in an existing
table.
1. ALTER TABLE Customers
ADD Email varchar(255);
2. ALTER TABLE Customers
DROP COLUMN Email;
3. ALTER TABLE table_name
ALTER COLUMN column_name datatype; // to change the datatype of the
table
SQL Constraints-
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
• FOREIGN KEY - Prevents actions that would destroy links between tables
• CHECK - Ensures that the values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very
quickly
Check-
The CHECK constraint is used to limit the value range that can be placed in a
column.
SQL Default-
Used to set a default value for a column
E.g.-
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT ‘New York’
);
The DEFAULT constraint can also be used to insert system values, by using
functions like GETDATE():
E.g. -
CREATE TABLE Orders (
ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);
Index-
Duplicate values allowed
CREATE INDEX index_name
ON table_name (column1, column2, ...);
Duplicate values not allowed
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
SQL QUERYING STATEMENTS-
Select Query-
SELECT column1, column2, ...
FROM table_name;
SELECT * FROM table_name;
SELECT DISTINCT column1, column2, ...
FROM table_name;
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Operators-
=, >, <, >=, <=, <>
BETWEEN- for range: use ‘between’
SELECT * FROM Products
WHERE Price BETWEEN 50 AND 60;
LIKE-
SELECT * FROM Customers
WHERE City LIKE 's%';
IN- city either paris or London, not for range.
SELECT * FROM Customers
WHERE City IN ('Paris','London');
AND, OR, NOT clause;
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
SELECT * FROM Customers
WHERE NOT Country='Germany';
INSERT-
INSERT INTO table_name
VALUES (value1, value2, value3, ...); //MAINTAIN ORDER OF COLUMNS
OR
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
NULL-
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
UPDATE-
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
DELETE-
DELETE FROM table_name WHERE condition;
LIMIT, TOP-
SELECT * FROM Customers LIMIT 3;
SELECT TOP 3 * FROM Customers;
MIN & MAX-
SELECT MIN(Price) AS SmallestPrice
FROM Products;
AGGREGATIONS –
COUNT(), SUM(), AVG()
SELECT COUNT(ProductID) AS COUNT
FROM Products;
ALIASES-
Column alias
SELECT column_name AS alias_name
FROM table_name;
Table Alias
SELECT column_name(s)
FROM table_name AS alias_name;
Advanced SQL Concepts:
JOINS-
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
UNION-
The UNION operator is used to combine the result-set of two or
more SELECT statements.
• Every SELECT statement within UNION must have the same number of
columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order
The UNION operator selects only distinct values by default.
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
To allow duplicate values, use UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
GROUP BY-
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more
columns.
HAVING-
The HAVING clause was added to SQL because the WHERE keyword cannot be used
with aggregate functions.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
CASE-
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
The following SQL goes through conditions and returns a value when the first
condition is met:
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;
The following SQL will order the customers by City. However, if City is NULL,
then order by Country:
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
SQL FUNCTIONS-
IFNULL(), COALESCE()- function lets you return an alternative value if an
expression is NULL
SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))
FROM Products;
###ISNULL() – THIS IS USED IN ORACLE SERVER
SQL Comments-
-- is used comment sql queries.
HAVING Clause:
It is used to apply condition on aggregation, where is used to apply condition on a column.
SELECT (DISTINCT)
FROM
WHERE
GROUP BY
ORDER BY
HAVING
WINDOW FUNCTIONS-
Lead & Lag
SELECT start_terminal,
duration_seconds,
LAG(duration_seconds, 1) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds) AS lag,
LEAD(duration_seconds, 1) OVER
(PARTITION BY start_terminal ORDER BY duration_seconds) AS lead
Handy functions that usually are used in
advance questions:
JOINS, UNION, HAVING, GROUP BY, CASE statements seem easy while looking
at independent examples. But the complexity increases when these statements
are used in combination with each other.
Select concat(name, lastname) as full_name from students
LIKE is case sensitive, ILIKE is case insensitive.
COUNT will ignore all null values
In window functions partition by acts similar to a group by
Cast- cast (‘2020-20-10’ as date)
DATE MANIPULATION:
(‘2020-01-10’:: date -30* interval ‘1 day’)
:: is used for casting purposes
eg- total::float/100
select ifnull(customer_name,'N/A')customer_name,\