SQL Commands and Database Management Guide
SQL Commands and Database Management Guide
SQL Commands
ALTER DELETE
DDL : Data Definition Language DML: Data Manipulation Language
DCL : Data Control Language TCL : Transaction Control Language
TRUNCATE
DQL : Data Query Language
1
1. Create database create database SaleOrder use SaleOrder
2. Use the database create table [Link] (
3. Create tables 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%'
3
21. having SELECT JobTitle, COUNT(JobTitle)
FROM EmployeeDemographics ED
JOIN EmployeeSalary ES
ON [Link] = [Link]
GROUP BY JobTitle HAVING
COUNT(JobTitle) > 1
SELECT JobTitle, AVG(Salary)
FROM EmployeeDemographics ED
JOIN EmployeeSalary ES
ON [Link] = [Link]
GROUP BY JobTitle
HAVING AVG(Salary) > 45000
ORDER BY AVG(Salary)
22. Change data type -- CAST(expression AS datatype(length))
temporary for use SELECT CAST('2017-08-25 [Link].000' AS date)
--
SELECT FirstName,LastName,JobTitle, Salary,
CASE
WHEN JobTitle ='Salesman'THENSalary + (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 [Link] = [Link]
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([Link],1,3),
Substring([Link],1,3), Substring([Link],1,3),
Substring([Link],1,3)
FROM EmployeeErrors err
JOIN EmployeeDemographics dem
on Substring([Link],1,3) =
Substring([Link],1,3)
and Substring([Link],1,3) =
Substring([Link],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 [Link],AllAvgSalary
FROM(SELECT EmployeeID,Salary, AVG(Salary) OVER () AS
AllAvgSalary
FROM EmployeeSalary) a
ORDER [Link]
-- Subquery in Where
SELECT EmployeeID,JobTitle, Salary
FROM EmployeeSalary
WHERE EmployeeID in(SELECT EmployeeID FROM
EmployeeDemographics
WHERE Age > 30)
6
SQL JOINS
select
inventoryname,saledate,saleunitprice,salequantity,saleunitprice*salequantity
as [Total Amount]
from inventory inner join sale
on [Link]=[Link]
order by inventoryname
inventory sales
inventory sales
7
--left join (might have NULL value, since some inventory might not have sales)
select [Link],inventoryname
from inventory left join sale on
[Link]=[Link]
inventory sales
--left join
select [Link],inventoryname
from inventory left join sale on
[Link]=[Link]
where [Link] is NULL
inventory sales
--right join
select [Link],inventoryname
from inventory right join sale on
[Link]=[Link]
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
--merge, but show you everything, even select cust_lname,cust_fname from customer
the duplicate record union all
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 [Link]=[Link] inner
join inventory
on [Link]=[Link]
customer
inventory sales
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
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 *,
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 *,
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
of $1,000 or more. [Name],inv_date,inv_amount
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 [Link], [Link], [Link],
expression is NULL [Link],
ISNULL([Link],[Link])
From NashvilleHousing a JOIN
NashvilleHousing b
on [Link] = [Link]
AND a.[UniqueID] <> b.[UniqueID]
Where [Link] is null
-- Update record
Update a SET PropertyAddress =
ISNULL([Link],[Link])
From NashvilleHousing a JOIN
NashvilleHousing b
on [Link] = [Link]
AND a.[UniqueID] <> b.[UniqueID]
Where [Link] is null
15
Update NashvilleHousing
SET PropertySplitAddress = SUBSTRING(PropertyAddress, 1,
CHARINDEX(',', PropertyAddress) -1 )
Update NashvilleHousing
SET PropertySplitCity = SUBSTRING(PropertyAddress,
CHARINDEX(',', PropertyAddress) + 1 , LEN(PropertyAddress))
Select OwnerAddress,
❖ REPLACE(string, old_string,
new_string)
Update NashvilleHousing
SET OwnerSplitCity = PARSENAME(REPLACE(OwnerAddress, ',',
'.') , 2)
Update NashvilleHousing
SET OwnerSplitState = PARSENAME(REPLACE(OwnerAddress, ',',
'.') , 1)
16