Master SQL in 16 Pages PDF
Master SQL in 16 Pages PDF
SQL in
16 PAGES
By Telugu Gyaan
Structured Query language (SQL)
SQL Commands
ALTER DELETE
DDL : Data Definition Language DML: Data Manipulation Language
TRUNCATE DCL : Data Control Language TCL : Transaction Control Language
DQL : Data Query Language
1
1. Create database create database SaleOrder
2. Use the database use SaleOrder
3. Create tables create table dbo.customer (
CustomerID int NOT null primary key,
CustomerFirstName varchar(50) NOT null,
CustomerLastName varchar(50) NOT null,
CustomerAddress varchar(50) NOT null,
CustomerSuburb varchar(50) null,
CustomerCity varchar(50) NOT null,
CustomerPostCode char(4) null,
CustomerPhoneNumber char(12) null,
);
2
7. Save table to another table --into file_name: save result in another table (BASE TABLE)
select distinct customerlastname into temp
from customer
order by customerlastname
select * from temp --see the table (data type will remain)
8. Like (search something) -- (underscore sign) _ is only specific for one character only
-- (percent sign) % represents zero, one, or multiple characters
select * from customer
where customerlastname like '_r%'
-- search multiple items
9. In (search something)
select * from customer
where customerlastname in ('Brown', ‘Michael’, ’Jim’)
--
SELECT FirstName, LastName, JobTitle, Salary,
CASE
WHEN JobTitle = 'Salesman' THEN Salary + (Salary *.10)
WHEN JobTitle = 'Accountant' THEN Salary + (Salary *.05)
WHEN JobTitle = 'HR' THEN Salary + (Salary *.000001)
ELSE Salary + (Salary *.03)
END AS SalaryAfterRaise
FROM EmployeeDemographics ED
JOIN EmployeeSalary ES
ON ED.EmployeeID = ES.EmployeeID
4
25. String Functions -- Remove space
Select EmployeeID, TRIM(EmployeeID) AS IDTRIM
FROM EmployeeErrors
Select EmployeeID, RTRIM(EmployeeID) as IDRTRIM
FROM EmployeeErrors
Select EmployeeID, LTRIM(EmployeeID) as IDLTRIM
FROM EmployeeErrors
-- Replace
Select LastName, REPLACE(LastName, '- Fired', '') as
LastNameFixed
FROM EmployeeErrors
-- Substring
Select Substring(err.FirstName,1,3),
Substring(dem.FirstName,1,3), Substring(err.LastName,1,3),
Substring(dem.LastName,1,3)
FROM EmployeeErrors err
JOIN EmployeeDemographics dem
on Substring(err.FirstName,1,3) =
Substring(dem.FirstName,1,3)
and Substring(err.LastName,1,3) =
Substring(dem.LastName,1,3)
-- UPPER and LOWER CASE
Select firstname, LOWER(firstname)
from EmployeeErrors
5
--- only need to run this on next time
EXEC Temp_Employee @JobTitle = 'Salesman'
-- Subquery in From
SELECT a.EmployeeID, AllAvgSalary
FROM (SELECT EmployeeID, Salary, AVG(Salary) OVER () AS
AllAvgSalary
FROM EmployeeSalary) a
ORDER BY a.EmployeeID
-- Subquery in Where
SELECT EmployeeID, JobTitle, Salary
FROM EmployeeSalary
WHERE EmployeeID in (SELECT EmployeeID FROM
EmployeeDemographics
WHERE Age > 30)
SELECT EmployeeID, JobTitle, Salary
FROM EmployeeSalary
WHERE Salary in (SELECT Max(Salary) FROM EmployeeSalary)
6
SQL JOINS
inventory sales
inventory sales
7
--left join (might have NULL value, since some inventory might not have sales)
select inventory.inventoryid,inventoryname
from inventory left join sale on
sale.inventoryid=inventory.inventoryid
inventory sales
--left join
select inventory.inventoryid,inventoryname
from inventory left join sale on
sale.inventoryid=inventory.inventoryid
where sale.inventoryid is NULL
inventory sales
--right join
select sale.inventoryid,inventoryname
from inventory right join sale on
sale.inventoryid=inventory.inventoryid
inventory sales
8
Output:
employeeID Full Name managerID managerName
1002 Kelvin Koh 1001 Tan Mei Ling
1003 Amin Wong 1002 Kelvin Koh
Output:
employeeID Full Name managerID managerName
1001 Tan Mei Ling
1002 Kelvin Koh 1001 Tan Mei Ling
1003 Amin Wong 1002 Kelvin Koh
9
SQL UNIONS
1. Union
--allow you to combine two tables select cust_lname,cust_fname from customer
together (but the no. of columns & union
each column’s data types for 2 tables select cust_lname,cust_fname from customer_2
must be match)
--don't need common key, only need
common attributes
--merge, not showing duplicate record
2. Union all
select cust_lname,cust_fname from customer
--merge, but show you everything, even union all
the duplicate record select cust_lname,cust_fname from customer_2
customer customer_2
customer customer_2
customer customer_2
--use subquery
select cust_lname,cust_fname from customer
where(cust_lname) not in
(select cust_lname from customer_2) and
(cust_fname) not in
(select cust_fname from customer_2)
10
Table & View
1. view table create view CustomerView as
(view will be updated when select customerfirstname+' '+customerlastname as [Customer Name] ,
update base) customerphonenumber,
--view is a result set of SQL inventoryname,saledate,salequantity,saleunitprice,salequantity*saleunitprice
statements, exists only for a as [Total Amount]
single query from customer inner join sale on customer.customerid=sale.customerid inner
join inventory
on sale.inventoryid=inventory.inventoryid
customer
inventory sales
WITH CTE_Employee AS
CTE (Common Table (
3. SELECT FirstName, LastName, Gender, Salary,
Expression)
COUNT(Gender) OVER (PARTITION BY Gender) AS TotalGender
--create temporary result set FROM EmployeeDemographics ED
which is used to manipulate JOIN EmployeeSalary ES
the complex sub-queries data ON ED.EmployeeID = ES.EmployeeID
--created in memory rather WHERE Salary > '45000'
)
than Tempdb database, so
cannot create any index on SELECT FirstName, LastName, Gender, TotalGender
CTE. FROM CTE_Employee
WHERE TotalGender = (SELECT MIN(TotalGender) FROM CTE_Employee)
11
SQL RANKS
1. ROW_NUMBER() --get a unique sequential number for each row
--get different ranks for the row having similar values
SELECT *,
ROW_NUMBER() OVER(ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary
USING PARTITION BY
SELECT *,
RANK() OVER(PARTITION BY JobTitle ORDER BY Salary DESC)
SalaryRank
FROM EmployeeSalary
ORDER BY JobTitle, SalaryRank
12
3. DENSE_RANK()
-- if have duplicate values, SQL assigns different ranks to those rows.
-- will get the same rank for duplicate or similar values
SELECT *,
DENSE_RANK() OVER(ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary
ORDER BY SalaryRank
RANK() DENSE_RANK()
SELECT *, SELECT *,
RANK() OVER(PARTITION BY JobTitle ORDER DENSE_RANK() OVER(PARTITION BY JobTitle
BY Salary DESC) SalaryRank ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary FROM EmployeeSalary
ORDER BY JobTitle, SalaryRank ORDER BY JobTitle, SalaryRank
-- skip a rank if have similar values -- maintains the rank and does not give any gap
for the values
13
4. NTILE() -- can specify required how many group of result, and it will rank accordingly
SELECT *,
NTILE(3) OVER(ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary
ORDER BY SalaryRank;
Group 1
Group 2
Group 3
USING PARTITION BY
SELECT *,
NTILE(3) OVER(PARTITION BY JobTitle ORDER BY Salary DESC)
SalaryRank
FROM EmployeeSalary
ORDER BY JobTitle, SalaryRank;
Group 1
Group 2
Group 3
14
1. Write the query to show the select
invoice number, the customer invoice_num,c.cust_num,c.cust_lname,c.cust_fname,inv_date,inv_amount
number, the customer from customer c, invoice
name, the invoice date, and the where c.cust_num=invoice.cust_num and cust_balance>=1000
invoice amount for all
customers with a customer select invoice_num,c.cust_num,cust_lname+' '+cust_fname as
balance
[Name],inv_date,inv_amount
of $1,000 or more.
from customer c join invoice i
on c.cust_num=i.cust_num
where cust_balance>=1000
2. ISNULL(expression, value) --ParcelID is same, but UniqueID is different; can assume that if the ParcelID is
--expression: to test whether is same, the Property Address will be same
NULL, value: to return if Select a.ParcelID, a.PropertyAddress, b.ParcelID,
expression is NULL b.PropertyAddress,
ISNULL(a.PropertyAddress,b.PropertyAddress)
From NashvilleHousing a
JOIN NashvilleHousing b
on a.ParcelID = b.ParcelID
AND a.[UniqueID] <> b.[UniqueID]
Where a.PropertyAddress is null
-- Update record
Update a
SET PropertyAddress =
ISNULL(a.PropertyAddress,b.PropertyAddress)
From NashvilleHousing a
JOIN NashvilleHousing b
on a.ParcelID = b.ParcelID
AND a.[UniqueID] <> b.[UniqueID]
Where a.PropertyAddress is null
❖
SUBSTRING(PropertyAddress, 1, CHARINDEX(',',
PropertyAddress) -1 ) as Address
SUBSTRING(string, start, , SUBSTRING(PropertyAddress, CHARINDEX(',',
length) PropertyAddress) + 1 , LEN(PropertyAddress)) as City
From NashvilleHousing
❖
CHARINDEX(substring,
string, start)
❖
LEN(string)
ALTER TABLE NashvilleHousing
Add PropertySplitAddress Nvarchar(255);
15
Update NashvilleHousing
SET PropertySplitAddress = SUBSTRING(PropertyAddress, 1,
CHARINDEX(',', PropertyAddress) -1 )
Update NashvilleHousing
SET PropertySplitCity = SUBSTRING(PropertyAddress,
CHARINDEX(',', PropertyAddress) + 1 , LEN(PropertyAddress))
Select OwnerAddress,
PARSENAME(REPLACE(OwnerAddress, ',', '.') , 3)
❖ PARSENAME('object_name' ,PARSENAME(REPLACE(OwnerAddress, ',', '.') , 2)
,PARSENAME(REPLACE(OwnerAddress, ',', '.') , 1)
, object_piece) From NashvilleHousing
--numbering works from
right to left
❖ REPLACE(string, old_string,
new_string)
Update NashvilleHousing
SET OwnerSplitCity = PARSENAME(REPLACE(OwnerAddress, ',',
'.') , 2)
Update NashvilleHousing
SET OwnerSplitState = PARSENAME(REPLACE(OwnerAddress, ',',
'.') , 1)
16