0% found this document useful (0 votes)
2 views

sql

The document is a comprehensive guide to SQL, covering various concepts such as Data Definition Language (DDL) and Data Manipulation Language (DML) with detailed examples. It includes sections on creating, altering, and dropping tables, as well as functions for querying and manipulating data. Additionally, it discusses advanced topics like windowing functions, subqueries, and JSON handling in SQL.

Uploaded by

sisitps0605
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

sql

The document is a comprehensive guide to SQL, covering various concepts such as Data Definition Language (DDL) and Data Manipulation Language (DML) with detailed examples. It includes sections on creating, altering, and dropping tables, as well as functions for querying and manipulating data. Additionally, it discusses advanced topics like windowing functions, subqueries, and JSON handling in SQL.

Uploaded by

sisitps0605
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

1

SQL - Table of Contents

SQL - Table of Contents 1


Concepts/Facts 3
DDL 3
Create 3
Alter 3
Drop 3
Check 3
Insert 3
Update 3
Primary Key/ Foreign Key 4
Not null 4
Unique 4
DML (Part 1) 4
Like 4
REGEXP_LIKE 4
Fetch 5
OFFSET 5
SQL String Function 5
SQL Numeric Function 6
SQL Date Function 6
DML (Part 2) 6
SQL Aggregate Function 6
Group By / Having 7
Nested Subquery 7
IN 7
Some 8
All 8
Exist 9
SUBQUERY 9
With 10
DML (Part 3) 10
Partition by 10
Order by 10
Rank 10
Rank + Partition by 11
Rank + Top/Bottom N tuples 11
Dense_Rank 11
ntile 12
Listagg 12
2

Listagg + Partition by + Order by 12


Windowing 12
DDL 13
Complex Insertion 13
Complex Delete 13
Complex Update 14
View 14
View Update 14
Aassertion 14
Trigger 15
Data Analytics - Cross Tab 16
Pivot - Cross Tab 16
Cube 16
Rollup + Grouping Set 16
Rollup + Grouping Function 16
Cube + Grouping Function 17
Order by 17
JSON 17
json_object 17
json_object + array 18
json_object + arragg 18
json_object + arrayagg + object 18
Absent on null 18
Absent on null 19
3

Concepts/Facts

DDL

Create
● create table Client (
clientId int,
name varchar2(15),
hkid char(10),
address varchar2(20),
district varchar2(20));

● Create table Account (


accountNo char(5),
balance number(8,2) default 0,
branchName varchar2(15));

Alter
alter table Client
add postalCode int;

alter table Client


drop column postalCode;

Drop
drop table Client;

Check
Create table Loan (
loanNo char(5) primary key,
amount number(8,2) check (amount>=1000 and amount<=100000),
year char(4),
branchName varchar2(15) not null);

Insert
Insert into Account (accountNo, branchName, balance) values ('A-734', 'Pacific Place',
1200);

Update
update
4

Account
set
balance=50000
where
accountNo= ‘A-733';

Primary Key/ Foreign Key

create table Depositor (


clientId int,
accountNo char(5),
primary key (clientId, accountNo),
foreign key (clientId) references Client(clientId)
on delete cascade,
on update cascade;

Not null
create table Client (
clientId int primary key,
name varchar2(15) not null,
hkid char(10) not null,
address varchar2(20) not null,
district varchar2(20) not null,
unique (hkid));

Unique
create table Client (
clientId int primary key,
name varchar2(15) not null,
hkid char(10) not null,
address varchar2(20) not null,
district varchar2(20) not null,
unique (hkid));

DML (Part 1)

Like

The percent sign % represents zero, one, or multiple characters

The underscore sign _ represents one, single character

select name, address


from Client
where address like '%Main%';
5

REGEXP_LIKE

Character Description

. Any character except newline


● Example. . - Matches any character

* Matches 0 or more preceding character


● Example. b* - bbbeee

+ Matches 1 or more preceding character


● Example. b+ - bbbeee, beee

? Matches either 0 or 1 preceding character, effectively


matches is optional
● Example. Goog?le - Goole , Google

| Represent like a boolean OR for alternative matches


● Example. AB|CD - match ab or cd

[] Matches any character in the set


Example. [ABC] - matches any of a, b, or c

() Capture groups of sequence character together


Example. (name) - matches sequence of group character

select name
from Client
where regexp_like (name, '^Ste(v|ph)en');

=> Steven or Stephen (i.e., the name begins with ‘Ste’ followed by either ‘v’ or ‘ph’ followed by ‘en’

select name
from Client
where regexp_like (name, '([aeiou])\1', 'i');

=>a double vowel (i.e.,double a, e, i, o or u) in their name, regardless of case.


6

Fetch
select name, rating
from Client
order by rating, name
fetch first 3 rows only;
=>Find the name and credit rating of the three clients

OFFSET
select distinct rating
from Client
order by rating desc nulls last
offset 2 rows
fetch next 1 row only;
=>Find the third highest credit rating

SQL String Function

● Lower(string) converts string to lowercase


● upper(string) converts string to uppercase
● initcap(string) sets first character of each word to uppercase
● substr(string, position, length) returns a length substring of string starting at position
● concat(string1, string2) concatenates string1 and string2
● instr(string1, string2) returns location of string2 in string1
● length(string) returns length of string
● lpad(string1, length, string2) pads string1 with string2 to the left to length
● rpad(string1, length, string2) pads string1 with string2 to the right to length
● ltrim(string) removes all spaces from the left of string
● rtrim(string) removes all spaces from the right of string
● trim(string) removes all leading and trailing spaces from string

SQL Numeric Function

● mod(number1, number2) returns number1 mod number2


● power(number1, number2) returns (number1)number2
● round(number1, integer_number2) returns number1 rounded tointeger_number2
places
● trunc(number1, integer_number2) truncates number1 to integer_number2 decimal
7

places

SQL Date Function

● add_months(date, number) adds number of months to date


● next_day(date, weekday) returns the date of the first weekday that is later than date
● last_day(date) returns the date of the last day in the month of date
● current_date returns the current date
● to_date(string, date_format_string) convert string to the corresponding date
according to date_format_string
● to_char(date, format_mask) convert date to a string according to format_mask (e.g.,
'YYYY' for year only)

DML (Part 2)

SQL Aggregate Function

● count: number of tuples / values


● avg: average value
● stdev: standard deviation of values
● max: maximum value
● min: minimum value
● sum: sum of values (total)

Example:

Select min(rating) as minRating,


max(rating) as maxRating,
avg(rating) as avgRating
from Client;

select branchName, sum(balance), count(*)


from Account
group by branchName;

Group By / Having
select clientId
from Depositor D, Account A
8

where D.accountNo=A.accountNo
and branchName='Star House'
group by clientId
having count(*)=1;
=>Find the id of clients who have only one account at the Star House branch.

Nested Subquery

select clientId, name, rating


from Client
where rating=(select distinct rating
from Client
order by rating desc nulls last
offset 2 rows
fetch next 1 row only)
order by name;

=>Find the client id, name and credit rating of all clients with
the third highest credit rating. Order the result by client
name ascending.

IN

Select distinct clientId


from Borrower
where clientId in (select clientId
from Depositor);

=>Find the id of clients who have both an account and a loan.

select distinct clientId


from Borrower
where clientId not in (select clientId
from Depositor);

=>Find the id of clients who have a loan, but do not have an


account.

select branchName, clientId, name, balance


from Client natural join Depositor natural join Account
where (branchName, balance) in (select branchName, max(balance)
from account
9

group by branchName);

=> Find, for each branch, the branch name, client id, client name, and client account
balance of the clients with the largest account balance.

Some

Select branchName
from Branch
where assets >some (select assets
from Branch
where district='Yau Tsim Mong);

=>Find the name of the branches that have greater assets than
some (i.e., at least one) branch located in Yau Tsim Mong
district.

All

select branchName
from Branch
where assets >all (select assets
from Branch
where district='Yau Tsim Mong ');

=>Find the name of the branches that have greater assets


than all branches located in Yau Tsim Mong district.

Exist

select clientId
from Depositor D
where exists (select *
from Borrower B
where D.clientId=B.clientId);

=>Find the id of the clients who have both a loan and an


account.

Select distinct clientId


10

from Depositor D
where not exists (select *
from Borrower B
where D.clientId=B.clientId);

=> Find the id of clients who have an account, but do not have
a loan

SUBQUERY

select branchName, avgBalance


from (select branchName, avg(balance) as avgBalance
from Account
group by branchName) result
where avgBalance>(select avg(balance)
from Account);

=> Find the name and average balance of the branches whose
average balance is greater than the average account balance

select branchName, avgBalance


from (select branchName, avg(balance) as avgBalance
from Account
group by branchName) result
where avgBalance=(select max(avgBalance)
from result)
=> Find the name and average balance of branches with the
maximum average account balance.

With

with result (branchName, avgBalance) as


(select branchName, avg(balance)
from Account
group by branchName)
select branchName, avgBalance
from result
where avgBalance = (select max(avgBalance)
from result);

=> Find the name and average balance of branches with the maximum average account
balance.
11

DML (Part 3)

Partition by
Select accountNo, balance, branchName,
sum(balance) over (partition by branchName) as totalBranchBalance
from Account;

=>Find the account information for each account as well as the total balance for the
account's branch.

Order by

Select accountNo, balance, branchName,


sum(balance) over (order by accountNo) as totalBalance
from Account;

Rank

select branchName, assets,


rank() over (order by assets desc) as branchRank
from Branch;

=>For each bank branch find the branch name, its assets and
its rank among all bank branches based on its assets.

Rank + Partition by

select branchName, accountNo, balance,


rank() over (partition by branchName
order by balance desc) as branchAccountRank
from Account
order by branchName, branchAccountRank;

=>Find the branch name, account number, balance and rank of the accounts in each
branch based on the account's balance. Order the result by branch name and rank

Rank + Top/Bottom N tuples

select branchName, assets


from (select branchName, assets,
12

rank() over (order by assets desc) as branchRank


from Branch)
where branchRank<=3;

=>Find the name and assets of the top three ranking


branches based on their assets;

Dense_Rank

The rank function gives the same rank to all tuples that have
equal value on the order by attributes.
– E.g., if two branches have the same highest asset value, both would
get rank 1.
This results in "gaps" in the ranking
– E.g., if two branches have the top rank of 1, then the next rank
would be 3, not 2.
The dense_rank function eliminates gaps in the ordering; ties still
get the same rank.

select branchName, assets


dense_rank() over (order by assets desc) as branchRank
from Branch
order by branchRank;

=>Find the branch name, assets and rank, without gaps, of


the branches based on their assets.

ntile

select branchName, assets,


ntile(4) over (order by assets desc) as branchQuartile
from Branch;

=>Find the branch name, assets and the quartile into which
each branch falls based on its assets.

Listagg

select district, listagg(name, ', ') within group (order by name) clients
from Client
13

group by district
order by district;

=>Find, for each district, the name of the clients in the district.
Order the result first by district ascending and and then by
names ascending.

Listagg + Partition by + Order by

select loanNo, amount, branchName, listagg(amount, ', ')


within group (order by amount)
over (partition by branchName) as "ALL LOAN AMOUNTS"
from Loan
where year='2023'
order by amount;

=>Find, for each loan in 2023, the loan number, loan amount,
branch name and the amount of each of the loans given in
the same year at the same branch. Order the result by the
loan amount.

Windowing

A windowing_clause allows an analytic function to be computed


over a moving partition called a window.
☞ Useful to compute an aggregate of a fixed range of time

select year,
avg(yearLoanTotal) over (order by year rows 2 preceding)
as movingAverageYearLoanTotal
from (select year, sum(amount) as yearLoanTotal
from Loan
group by year);

=>For each year, find the average total loan amounts for the year and the previous two-
year period. (Calculate 3 yr for each yr)

select year,
avg(yearLoanTotal) over (order by year rows
between unbounded preceding and 1 following)
as movingAverageYearLoanTotal
from (select year, sum(amount) as yearLoanTotal
14

from Loan
group by year);

=>For each year, find the average total loan amounts for the
year, for all previous years and for the following year.

DDL

Complex Insertion

insert into Account


select loanNo, 200, branchName
from Loan
where branchName='Pacific Place';

=>Create a $200 savings account for all loan clients of the


Pacific Place branch. Let the loan number serve as the
account number for the new savings account.

Complex Delete

delete from Depositor


where accountNo in (select accountNo
from Depositor natural join Account
where branchName= 'Mongkok');

=>Delete all accounts at the Mongkok branch.

Complex Update

update Account
set balance = case
when balance<=10000 then balance*1.05
else balance*1.06
end;

=>increase all accounts with balance over $10,000 by 6%;


15

all other accounts receive 5%.

View

create view BranchLoan as


select loanNo, year, branchName
from Loan

=> Create a view of the Loan relation that hides the amount.

View Update

insert into Borrower (clientId, loanNo) values (7, null);


insert into Loan (loanNo, amount, year, branchName)
values (null, null, null, 'Diamond Hill');

Aassertion

assertion is an arbitrary SQL predicate that the database


must always satisfy

create assertion loanSumConstraint as check


(not exists (select *
from Branch
where (select sum(amount)
from Loan natural join Branch)
>=
(select sum(balance)
from Account natural join Branch)));

=> The sum of all loan amounts for each branch must be less
than the sum of all account balances at the branch.

Trigger

create [or replace] trigger trigger-name


{before | after} {delete | insert | update [of column-name ...]} or ... on table-name
[referencing {old as old | new as new} ...]
16

[for each row]


[when (condition)]

create or replace trigger overdraft


before update of balance on Account
for each row
when (new.balance<0)
declare
currentYear Loan.year%type;
begin
select to_char(sysdate, 'YYYY') into currentYear from dual;
insert into Loan values (:old.accountNo, - :new.balance,
currentYear, :old.branchName);
insert into Borrower (select clientName, accountNo
from Depositor
where accountNo=:old.accountNo);
:new.balance:=0);
end;

Data Analytics - Cross Tab

Pivot - Cross Tab

=> Generate a cross-tab of the SaleOrder relation for the


subjects Art, Business and Travel showing, for all formats
and languages, how many books were sold for each subject.
Order the result first by format ascending and then by
language ascending.

select *
from SaleOrder
pivot (sum(quantity)
for subject in ('Art', 'Business', 'Travel'))
order by format, language;

Cube

=> Generate the data cube of the SaleOrder relation


17

on dimension format, language and subject.

select format, language, subject, sum(quantity) as total


from SaleOrder
group by cube (format, language, subject);

Rollup + Grouping Set

=> Rollup the SaleOrder relation by format only and by both subject and language.
Order the result first by format, then by subject and finally by language.

select format, subject, language, sum(quantity) as total


from SaleOrder
group by grouping sets ((format), (subject, language))
order by format, subject, language;

Rollup + Grouping Function

=> Rollup the SaleOrder relation by format, subject


and language. Replace null values with 'all'.

select (case when grouping(format)=1 then 'all' else format end) as format,
(case when grouping(subject)=1 then 'all' else subject end) as subject,
(case when grouping(language)=1 then 'all' else language end) as language,
sum(quantity) as total
from SaleOrder
group by rollup(format, subject, language);

Cube + Grouping Function

Generate a cross-tab for the SaleOrder relation, that


shows, for each language and for each subject, the total
number of books sold. Replace null values with 'all'.

select (case when grouping(format)=1 then 'all' else format end) as format,
(case when grouping(subject)=1 then 'all' else subject end) as subject,
(case when grouping(language)=1 then 'all' else language end ) as language,
sum(quantity) as total
from SaleOrder
group by cube(format, subject, language);
18

JSON

json_object

Construct an SQL query to create a JSON object for each sailor in the
Sailor relation containing as fields all attributes of the Sailor relation

select json_object(
'sailorId' value sailorId,
'sName' value sName,
'hkid' value hkid,
'rating' value rating,
'age' value age)
from Sailor;

json_object + array
Construct an SQL query to create a JSON object for each sailor
who has reserved a boat containing as fields the sailor id, name
and an array named 'reservations' where the array elements are
the id, name and color of each boat that the sailor reserved.

select json_object(
'sailorId' value sailorId,
'sName' value sName,
'reservations' value json_array(boatId, bName, color))
from Sailor natural join Reserves natural join Boat;

json_object + arragg
Construct an SQL query to create a JSON object for each
sailor who has reserved a boat containing as fields the sailor
id, name and an array named 'reservations’ where the array
elements are the ids of the boats that the sailor reserved.

select json_object(
'sailorId' value sailorId,
'sName' value sName,
'reservations' value json_arrayagg(boatId))
from Sailor natural join Reserves
group by sailorId, sName;
19

json_object + arrayagg + object


Construct an SQL query to create a JSON object for each sailor who
has reserved a boat containing as fields the sailor id, name and an
array of objects named 'reservations' where each object contains as
fields the id and name of the boats that the sailor reserved.

select json_object(
'sailorId' value sailorId,
'sName' value sName,
'reservations' value json_arrayagg(json_object('boatId' value boatId,
'bName' value bName)))
from Sailor natural join Reserves natural join Boat
group by sailorId, sName;

Absent on null
Construct an SQL query to create a JSON object for each sailor in the
Sailor relation containing as fields all the attributes of Sailor and an
object named 'reservations' where each object contains as fields the
id, name and color of the boats that the sailor reserved. If a sailor has
not reserved any boats, then the 'reservations' field should be absent.

[ Method 1 ]
select json_object(
'sailorId' value sailorId,
'sName' value sName,
'hkid' value hkid,
'rating' value rating,
'age' value age,
'reservations' value json_arrayagg(json_object('boatId' value boatId,
'bName' value bName,
'color' value color
absent on null)))
from Sailor natural left outer join (Reserves natural join Boat)
group by sailorId, sName, hkid, rating, age;

[ Method 2 ]
select json_object(
'sailorId' value sailorId,
'sName' value sName,
'hkid' value hkid,
'rating' value rating,
'age' value age,
'reservations' value (select json_arrayagg(json_object('boatId' value B.boatId,
'bName' value bName,
'color' value color))
20

from Boat B, Reserves R


where B.boatId=R.boatId and R.sailorId=S.sailorId)
absent on null)
from Sailor S
group by sailorId, sName, hkid, rating, age;

Absent on null
Construct an SQL query to create a JSON object for each student
containing as fields the student id, name (as a single field shown as 'last
name, first name') and an array named 'courses' where the array elements
are the course ids of the courses in which the student is enrolled. The
'courses' array should be absent if a student is not enrolled in any course.
Order the students by last name ascending.

select json_object(
'studentId' value studentId,
'name' value lastName || ', ' || firstName,
'courses' value json_arrayagg(courseId absent on null)) as students
from Student natural left outer join EnrollsIn
group by studentId, firstName, lastName
order by lastName;

You might also like