SQL
Table of content
##A brief overview of important SQL statements
select statement
- pay attention to
distinctandlikeinwherestatement. %can be used as wild card inlikestatement.- An example code is given as the following:
select distinct name
from empinfo
where age > 40 and firstname like 'bob%'
###Aggregation functions
- Aggregation functions include
distinct,min,max,sum,avg,count, andcount(*)where return the number of rows. - An example code is given as the following:
select max(salary), firstname, lastname
from empinfo
###group by statement
group bystatement will group rows with same attribute. It is usually followed with aggregation function.- An example code is given as the following:
select max(salary), department
from empinfo
group by department
###having statement
havingstatement usually followsgroup bystatement.- The difference between
havingandwherestatements are the followings:- Aggregation functions, e.g.,
avg(), cannot be used inwherestatement, but can be used inhavingstatement. wherecan be used ininsert,delete,selectstatements, buthavingcan only be used inselectstatement.havingcan only use withgroup bystatement.
- Aggregation functions, e.g.,
- An example code is given as the following:
select max(salary),department
from empinfo
where department like 'elec%'
group by department
having avg(salary) > 5000
###order by statement
order bystatement can be used with two optionsASCorDESC.- An example code is given as the following:
select employee_id, department, firstname, lastname
from empinfor
where department like 'core%'
order by salary DESC, name ASC
###in and between statements
inandbetweenstatements can be combined to make more powerful boolean clauses.- Two example codes are given as the following:
select employee_id, salary, department, firstname, lastname
from empinfor
where firstname in ('John', 'Bob', 'William')
and (salary between 2000 and 5000)
select title from movie
where id in ('11768','11955','21191')
###join statement
joinstatement makes ralational database ralational.joinstatement can make the database operation easier. For example, one can usejoinstatement instead of writing a complicated code usingselectandwherestatements.- For example, we have a database table of custom information and other table about purchaes. An example code of operating on there two tables is given as followings:
select customers.firstname, customers.lastname, purchases.id, purchases.name, purchases.price
from customer, purchases
where customer.id == purchases.customerid
select customers.firstname, customers.lastname, purchases.id, purchases.name, purchases.price
from customer inner join purchases
on customer.id == purchases.customerid
###Arithmetic operation
- Arithmetic operation can be used to generate new column of the data table
- An example code is given as the following:
select name, gdp/population
from world
where area > 500000
###Check the difference in date
- Function
datediff()can be used to check the difference in date variables. - An example code is given as the following:
select w2.Id
from Weather w1 join Weather w2
on datediff(w2.Date,w1.Date) = 1
where w1.Temperature < w2.Temperature
###coalesce statement
coalescestatement will replace thenullentries with0.- Two example codes are given as the following, which is the answer to the 13th question from the exerciese.
select name,coalesce(mobile,'07986 444 2266')
from teacher
select c.m1,team1,COALESCE(s1,0),team2,COALESCE(s2,0)
from
(
select id id1,mdate m1,team1,s1
from game
left join
(
select id tmpid,m1,team1 tmpteam1,sum(score1) s1
from
(
SELECT id,mdate m1,team1,
CASE WHEN teamid=team1 THEN 1 ELSE 0 END score1
FROM game JOIN goal ON matchid = id
)a
group by tmpid
)b
on id = tmpid
)c
join
(
select id id2,mdate m2,team2,s2
from game
left join
(
select id tmpid,m2,team2 tmpteam2,sum(score2) s2
from
(
SELECT id,mdate m2,team2,
CASE WHEN teamid=team2 THEN 1 ELSE 0 END score2
FROM game JOIN goal ON matchid = id
)d
group by tmpid
)e
on id = tmpid
)f
on c.id1 = f.id2
order by m1
###isnull() function
isnull()function is usually worked withwhereto form boolean claus.- An example code is given as the followings which is the solution to the first exercise.
select name from teacher where isnull(dept)
Different join statements
- There are several join statements include
inner join,left outer join, andfull outer join. - The following illustration is based on a post from stackoverflow.
-
Suppose there are two tables
a b 1 3 2 4 3 5 4 6 -
inner joinis the intersection of two tables. For example, the queryselect * from a INNER JOIN b on a.a = b.bwill generate the following tablea b 3 3 4 4 -
left outer joinwill also be the intersection of two tables. In addition, it keeps the elements from the first table and keepnullvalues from the second one. For example, the queryselect * from a left outer join b on a.a = b.bwill generate the following tablea b 1 null 2 null 3 3 4 4 -
full outer joinis the union of two tables. For example, the queryselect * from a FULL OUTER JOIN b on a.a = b.bwill generate the following tablea b 1 null 2 null 3 3 4 4 null 5 null 6
-
- In addition,
left joinis the same asleft outer join, andright joinis the same asright outer join. - A nice image illustration is given as the following 
###case statement
-
caseallows SQL query returns different values under different conditions. -
If there is no conditions match then
Nullis returned. -
casestatement takes the following formCASE WHEN condition1 THEN value1 WHEN condition2 THEN value2
ELSE def_value END -
Example codes are given as the following where the third code is from the sqlzoo.
select name,
case when dept=1 or dept=2 then 'Sci' else 'Art' end
from teacher
SELECT id,mdate m2,team2,
CASE WHEN teamid=team2 THEN 1 ELSE 0 END score2
FROM game JOIN goal ON matchid = id
SELECT name, population
,CASE WHEN population<1000000
THEN 'small'
WHEN population<10000000
THEN 'medium'
ELSE 'large'
END
FROM bbc
###cast() function
- Use
cast()function to transfer, e.g.,chartoint. - An example code is
ORDER BY CAST(thecolumn AS int).
###concat() function
concat()function is used to combine, e.g., two strings.- An example code of using
concat()function is given as the following which is the solution to the fifth exercise in sqlzoo.
select name, concat(round(population/(select population from world where name = 'Germany')*100),'%')
from world
where continent = 'Europe'
###all statement
allstatement allows boolean operators>,<,>=,<=act on a set of numbers.- One can also apply
max()ormin()operators first on the set of numbers. - An example code is given as the following
select name from world
where gdp >= all(select coalesce(gdp,0) from world where continent = 'Europe') and continent != 'Europe'
###Nested select statements
- Variables in the outer
selectstatement can be used in the innerselectstatement. - An example code is given as following which is the solution to the 7th exercises in sqlzoo.
select continent, name,area
from world x
where area >= all
(select area from world y
where x.continent = y.continent and y.area > 0)
###not exist statement
- The solution to the 9th exercises in sqlzoo.
select name,continent,population
from world x
where not exists (
select *
from world y
where y.continent = x.continent and y.population> 25000000
)
###More about in statement
- The expression
incan be used as a value - it will be 0 or 1. - An example code is given as the following
SELECT winner, subject, subject IN ('Physics','Chemistry') ord
FROM nobel
WHERE yr=1984
ORDER BY ord,subject,winner
###‘limit n offset m’ statement
- It is used to get n rows starting from the mth row.
- An example code is given as the following
select distinct Salary
from Employee
order by Salary DESC
limit 1 offset N
###Order and get the rank of some attribute
- Sometime we need to do the following operations:
- Get the greatest value
- Get the smallest value
- Get top N best values
- Get the rank of all values
- This can be, e.g., to select top N largest country from each continent, to select top N high salary from all employees.
- In principle, these operations can be done by join the table with itself.
- Use
count()andgroup bystatement to obtain the number of items that has value smaller/greater than the current value. - Use
count(distinct )statement to allow ranking same value twice. - An example code is given as the following which is the solution to the SQL exercise: Department Top Three Salaries from LeetCode.
select Department.Name,mytable.Name,mytable.Salary
from
(select e1.DepartmentId as DepartmentId, e1.Name as Name, e1.Salary as Salary, count(distinct e2.Salary) as Counter
from
Employee as e1 join Employee as e2 on e1.DepartmentId = e2.DepartmentId and e1.Salary<=e2.Salary
group by e1.Name) as mytable
join Department on mytable.DepartmentId = Department.Id
where mytable.Counter<=3
###delete statement
deletestatement is used to delete one item from the database table following the formdelete from table where [clause].- The table to be modified cannot appear in the
whereclause.