- Combine Two Tables
select p.firstName, p.lastName, a.city, a.state from Person p
left join Address a on a.personId = p.personId
- Second Highest Salary
select MAX(e.salary) as SecondHighestSalary from employee e
where e.salary not in (select max(e.salary) from employee e)
or
select
ifnull(
(select distinct e.salary from employee e
order by e.salary desc
limit 1 offset 1), null
) as SecondHighestSalary
- Nth Highest Salary
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET N = N-1;
RETURN (
select
ifnull(
(select distinct e.salary from Employee e
order by e.salary desc
limit 1 offset N), null
) as SecondHighestSalary
);
END
- Rank Scores
select score, DENSE_RANK() over(order by score DESC) as 'rank'
from Scores;
- Consecutive Numbers
select distinct l.num AS ConsecutiveNums
from logs l
inner join logs AS l_next on l.id + 1 = l_next.id
inner join logs AS l_next2 on l_next.id + 1 = l_next2.id
where l.num = l_next.num and l_next.num = l_next2.num