SQL Query Techniques and Functions Guide
SQL Query Techniques and Functions Guide
To joins or where classes more efficients make sure you cast the variables into the same varialbes. For example, A join B on cast([Link] as nvarchar2(40)) = cast([Link] as nvarchar2(40))
rownum: it is a where clause so it cannot be used like limit after groupby or order functions.
select .. from..where rownum <2 order by .. is not the same as select ..from..order by..limit. The rownum is first applied and then order by is applied. Rownum comes straight after where not and, or etc.
You cannot reference variable created in query . For example, the following won't work
Select months*salary as total_earnings
Where total_earnings > 2000;
Instead
Select months*salary as total_earnings
Where months*salary > 2000;
GROUP BY: Whichever variables are in the select they also need to be in the GROUP BY statement as well
JOINING tables through select from: When no common id exist to join tables use where to join table based on some comparison
select case when grade < 8 then NULL else name end name, grade, marks
from students, grades
where marks between min_mark and max_mark
order by grade desc, name, marks asc;
Column with spaces i.e last name you can use bracket. For example, select table.[last name] now if there is no space it won't work i.e table.[sex] will fail.
INNER JOIN
FULL OUTER JOIN
LEFT JOIN
RIGHT JOIN
CASE WHEN x>y THEN 'myvalue' ELSE 'othervalue' END name_it
x BETWEEN a AND b : this means greater than a and small than b, excluding a and b
You can add further when's and they will function as ifelse
round
floor
ceil
Avg
Distinct / unique
SUBSTR : ex. SUBSTR('manger', 2, 3) the 2 indicates the position 'a' and 3 the total length of the output
string. The output is 'ang'.
concat('a', 'b') = 'ab', only take two arguments
replace(feature, '|' , '1')
to_char()
to_number()
cast(num AS nvarchar2(40))
cast(string AS NUMBER)
max(feature) : used with groupby, unlike pytKihon you cannot compare two values in it
Min(feature) : used with groupby, unlike python you cannot compare two values in it
greatest(feature1, feature1) : this returns the max value between the two
least(feature1, feature1) : this returns the min value between the two
Group by
Order by
In
Not in
And
Or
Write a query calculating the amount of error (i.e.: average monthly salaries), and round it up to the next integer.
[Link] SELECT * EASY
FROM (SELECT (months*salary), COUNT(*)
FROM EMPLOYEE
GROUP BY (months*salary)
ORDER BY (months*salary) DESC)
WHERE ROWNUM = 1;
Or
[Link] SELECT CASE WHEN [Link] > 7 THEN [Link] ELSE NULL END NAME, MED
Ketty gives Eve a task to generate a report containing three columns: Name, Grade and Mark. Ketty doesn't want the [Link], [Link]
NAMES of those students who received a grade lower than 8. The report must be in descending order by grade -- i.e. FROM GRADES, STUDENTS
higher grades are entered first. If there is more than one student with the same grade (8-10) assigned to them, order WHERE [Link] BETWEEN GRADES.Min_Mark and GRADES.Max_Mark
those particular students by their name alphabetically. Finally, if the grade is lower than 8, use "NULL" as their name and ORDER BY [Link] DESC, Name ASC, [Link] ASC;
list them by their grades in descending order. If there is more than one student with the same grade (1-7) assigned to
them, order those particular students by their marks in ascending order.
[Link] SELECT H.hacker_id, [Link] MED
Four tabel merge - new technicque FROM Submissions S INNER JOIN Hackers H ON S.hacker_id = H.hacker_id
Julia just finished conducting a coding contest, and she needs your help assembling the leaderboard! Write a query to INNER JOIN Challenges C ON S.challenge_id = C.challenge_id
print the respective hacker_id and name of hackers who achieved full scores for more than one challenge. Order your INNER JOIN Difficulty D ON C.difficulty_level=D.difficulty_level
output in descending order by the total number of challenges in which the hacker earned a full score. If more than one WHERE [Link] = [Link]
hacker received full scores in same number of challenges, then sort them by ascending hacker_id. GROUP BY H.hacker_id, [Link]
HAVING COUNT(C.challenge_id)>1
Aways start with the large table that has more details. For example, submissions and then join the smaller tables that ORDER BY COUNT(C.challenge_id) DESC, H.hacker_id ASC;
contains properties to it.
[Link] Med
New technique
Harry Potter and his friends are at Ollivander's with Ron, finally replacing Charlie's old broken wand.
Hermione decides the best way to choose is by determining the minimum number of gold galleons needed to buy each
non-evil wand of high power and age. Write a query to print the id, age, coins_needed, and power of the wands that
Ron's interested in, sorted in order of descending power. If more than one wand has same power, sort the result in order
of descending age.
Leetcode
Write a SQL query to get the second highest salary from the Employee table. select ( easy
select Salary
+----+--------+ from (select Salary, rownum as rnum
| Id | Salary | from (select distinct Salary
+----+--------+ from Employee order by Salary desc))
| 1 | 100 | where rnum > 1 and rnum < 3) as "SecondHighestSalary"
| 2 | 200 | from dual;
| 3 | 300 |
+----+--------+ Or the following but group function was not allowed
For example, given the above Employee table, the query should return 200 as the second highest salary. If
there is no second highest salary, then the query should return null. Select max(salary) SecondHighestSalary
From (select * from employee where salary < max(salary));
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
Department table:
+------+---------+-------+
| id | revenue | month |
+------+---------+-------+
| 1 | 8000 | Jan |
| 2 | 9000 | Jan |
| 3 | 10000 | Feb |
| 1 | 7000 | Feb |
| 1 | 6000 | Mar |
+------+---------+-------+
Result table:
+------+-------------+-------------+-------------+-----+-------------+
| id | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |
+------+-------------+-------------+-------------+-----+-------------+
| 1 | 8000 | 7000 | 6000 | ... | null |
| 2 | 9000 | null | null | ... | null |
| 3 | null | 10000 | null | ... | null |
+------+-------------+-------------+-------------+-----+-------------+
Note that the result table has 13 columns (1 for the department id + 12 for the months).
Create table If Not Exists Department (id int, revenue int, month varchar(5))
Truncate table Department
insert into Department (id, revenue, month) values ('1', '8000', 'Jan')
insert into Department (id, revenue, month) values ('2', '9000', 'Jan')
insert into Department (id, revenue, month) values ('3', '10000', 'Feb')
insert into Department (id, revenue, month) values ('1', '7000', 'Feb')
insert into Department (id, revenue, month) values ('1', '6000', 'Mar')
627. Swap salary -- UPDATE, SET, WHERE: where conditions is optional and doesn't always need to be included. The Easy
Table: Salary case condition can work for where.
Write an SQL query to swap all 'f' and 'm' values (i.e., change all 'f' values to 'm' and vice versa) with a
single update statement and no intermediate temp table(s).
Note that you must write a single update statement, DO NOT write any select statement for this
problem.
Salary table:
+----+------+-----+--------+
| id | name | sex | salary |
+----+------+-----+--------+
| 1 | A | m | 2500 |
| 2 | B | f | 1500 |
| 3 | C | m | 5500 |
| 4 | D | f | 500 |
+----+------+-----+--------+
Result table:
+----+------+-----+--------+
| id | name | sex | salary |
+----+------+-----+--------+
| 1 | A | f | 2500 |
| 2 | B | m | 1500 |
| 3 | C | f | 5500 |
| 4 | D | m | 500 |
+----+------+-----+--------+
(1, A) and (2, C) were changed from 'm' to 'f'.
(2, B) and (4, D) were changed from 'f' to 'm'.
create table if not exists salary(id int, name varchar(100), sex char(1), salary int)
Truncate table salary
insert into salary (id, name, sex, salary) values ('1', 'A', 'm', '2500')
insert into salary (id, name, sex, salary) values ('2', 'B', 'f', '1500')
insert into salary (id, name, sex, salary) values ('3', 'C', 'm', '5500')
insert into salary (id, name, sex, salary) values ('4', 'D', 'f', '500')
+---------+-----------+--------------+-----------+
| id | movie | description | rating |
+---------+-----------+--------------+-----------+
| 1 | War | great 3D | 8.9 |
| 2 | Science | fiction | 8.5 |
| 3 | irish | boring | 6.2 |
| 4 | Ice song | Fantacy | 8.6 |
| 5 | House card| Interesting| 9.1 |
+---------+-----------+--------------+-----------+
For the example above, the output should be:
+---------+-----------+--------------+-----------+
| id | movie | description | rating |
+---------+-----------+--------------+-----------+
| 5 | House card| Interesting| 9.1 |
| 1 | War | great 3D | 8.9 |
+---------+-----------+--------------+-----------+
Create table If Not Exists cinema (id int, movie varchar(255), description varchar(255), rating float(2, 1))
Truncate table cinema
insert into cinema (id, movie, description, rating) values ('1', 'War', 'great 3D', '8.9')
insert into cinema (id, movie, description, rating) values ('2', 'Science', 'fiction', '8.5')
insert into cinema (id, movie, description, rating) values ('3', 'irish', 'boring', '6.2')
insert into cinema (id, movie, description, rating) values ('4', 'Ice song', 'Fantacy', '8.6')
insert into cinema (id, movie, description, rating) values ('5', 'House card', 'Interesting', '9.1')
197. Rising Temperature -- good use of date instead of LAG function. Easy
Table: Weather
select [Link]
+---------------+---------+ from weather a, weather b
| Column Name | Type | where [Link] = [Link] -1
+---------------+---------+ and [Link] > [Link];
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id is the primary key for this table.
This table contains information about the temperature in a certain day.
Write an SQL query to find all dates' id with higher temperature compared to its previous dates
(yesterday).
Weather
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+----+------------+-------------+
Result table:
+----+
| id |
+----+
|2 |
|4 |
+----+
In 2015-01-02, temperature was higher than the previous day (10 -> 25).
In 2015-01-04, temperature was higher than the previous day (20 -> 30).
Create table If Not Exists Weather (Id int, RecordDate date, Temperature int)
Truncate table Weather
insert into Weather (Id, RecordDate, Temperature) values ('1', '2015-01-01', '10')
insert into Weather (Id, RecordDate, Temperature) values ('2', '2015-01-02', '25')
insert into Weather (Id, RecordDate, Temperature) values ('3', '2015-01-03', '20')
insert into Weather (Id, RecordDate, Temperature) values ('4', '2015-01-04', '30')
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@[Link] |
| 2 | bob@[Link] |
| 3 | john@[Link] |
+----+------------------+
Id is the primary key column for this table.
For example, after running your query, the above Person table should have the following rows:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@[Link] |
| 2 | bob@[Link] |
+----+------------------+
Note:
Your output is the whole Person table after executing your sql. Use delete statement.
Truncate table Person
insert into Person (Id, Email) values ('1', 'john@[Link]')
insert into Person (Id, Email) values ('2', 'bob@[Link]')
insert into Person (Id, Email) values ('3', 'john@[Link]')
182. Duplicate Emails select email from person group by email having count(email) >1; Easy
Write a SQL query to find all duplicate emails in a table named Person.
+----+---------+
| Id | Email |
+----+---------+
| 1 | a@[Link] |
| 2 | c@[Link] |
| 3 | a@[Link] |
+----+---------+
For example, your query should return the following for the above table:
+---------+
| Email |
+---------+
| a@[Link] |
+---------+
Note: All emails are in lowercase.
184. Department Highest Salary with maxx as (select departmentid, max(salary) maxsalary from employee group by departmentid) Medium
The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for select [Link] Department, [Link] employee, [Link]
the department Id. from employee e, department d, maxx m
where [Link] = [Link]
+----+-------+--------+--------------+ and [Link] = [Link]
| Id | Name | Salary | DepartmentId | and [Link] = [Link];
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Jim | 90000 | 1 |
| 3 | Henry | 80000 | 2 |
| 4 | Sam | 60000 | 2 |
| 5 | Max | 90000 | 1 |
+----+-------+--------+--------------+
The Department table holds all departments of the company.
+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+
Write a SQL query to find employees who have the highest salary in each of the departments. For the
above tables, your SQL query should return the following rows (order of rows does not matter).
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| IT | Jim | 90000 |
| Sales | Henry | 80000 |
+------------+----------+--------+
Explanation:
Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the
Sales department.
Create table If Not Exists Employee (Id int, Name varchar(255), Salary int, DepartmentId int)
Create table If Not Exists Department (Id int, Name varchar(255))
Truncate table Employee
insert into Employee (Id, Name, Salary, DepartmentId) values ('1', 'Joe', '70000', '1')
insert into Employee (Id, Name, Salary, DepartmentId) values ('2', 'Jim', '90000', '1')
insert into Employee (Id, Name, Salary, DepartmentId) values ('3', 'Henry', '80000', '2')
insert into Employee (Id, Name, Salary, DepartmentId) values ('4', 'Sam', '60000', '2')
insert into Employee (Id, Name, Salary, DepartmentId) values ('5', 'Max', '90000', '1')
Truncate table Department
insert into Department (Id, Name) values ('1', 'IT')
insert into Department (Id, Name) values ('2', 'Sales')
Can you write a SQL query to output the result for Mary?
+---------+---------+
| id | student |
+---------+---------+
| 1 | Abbot |
| 2 | Doris |
| 3 | Emerson |
| 4 | Green |
| 5 | Jeames |
+---------+---------+
For the sample input, the output is:
+---------+---------+
| id | student |
+---------+---------+
| 1 | Doris |
| 2 | Abbot |
| 3 | Green |
| 4 | Emerson |
| 5 | Jeames |
+---------+---------+
Note:
If the number of students is odd, there is no need to change the last one's seat.
Create table If Not Exists seat(id int, student varchar(255))
Truncate table seat
insert into seat (id, student) values ('1', 'Abbot')
insert into seat (id, student) values ('2', 'Doris')
insert into seat (id, student) values ('3', 'Emerson')
insert into seat (id, student) values ('4', 'Green')
insert into seat (id, student) values ('5', 'Jeames')
Logs table:
+----+-----+
| Id | Num |
+----+-----+
|1 |1 |
|2 |1 |
|3 |1 |
|4 |2 |
|5 |1 |
|6 |2 |
|7 |2 |
+----+-----+
Result table:
+-----------------+
| ConsecutiveNums |
+-----------------+
|1 |
+-----------------+
1 is the only number that appears consecutively for at least three times.
Create table If Not Exists Logs (Id int, Num int)
Truncate table Logs
insert into Logs (Id, Num) values ('1', '1')
insert into Logs (Id, Num) values ('2', '1')
insert into Logs (Id, Num) values ('3', '1')
insert into Logs (Id, Num) values ('4', '2')
insert into Logs (Id, Num) values ('5', '1')
insert into Logs (Id, Num) values ('6', '2')
insert into Logs (Id, Num) values ('7', '2')
178. Rank Scores with rnk as (select score, row_number() over (order by score desc) rank Medium
Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. from (select distinct score from scores))
Note that after a tie, the next ranking number should be the next consecutive integer value. In other select [Link], [Link]
words, there should be no "holes" between ranks. from scores s left join rnk r on [Link] = [Link]
order by [Link];
+----+-------+
| Id | Score | Or alternatively
+----+-------+
| 1 | 3.50 | select score,
| 2 | 3.65 | dense_rank() over (order by score desc) Rank
| 3 | 4.00 | from scores;
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+
For example, given the above Scores table, your query should generate the following report (order by
highest score):
+-------+---------+
| score | Rank |
+-------+---------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+---------+
Important Note: For MySQL solutions, to escape reserved words used as column names, you can use an
apostrophe before and after the keyword. For example `Rank`.
Create table If Not Exists Scores (Id int, Score DECIMAL(3,2))
Truncate table Scores
insert into Scores (Id, Score) values ('1', '3.5')
insert into Scores (Id, Score) values ('2', '3.65')
insert into Scores (Id, Score) values ('3', '4.0')
insert into Scores (Id, Score) values ('4', '3.85')
insert into Scores (Id, Score) values ('5', '4.0')
insert into Scores (Id, Score) values ('6', '3.65')
177. Nth Highest Salary CREATE FUNCTION getNthHighestSalary(N IN NUMBER) RETURN NUMBER IS Medium
Write a SQL query to get the nth highest salary from the Employee table. result NUMBER;
BEGIN
+----+--------+ /* Write your PL/SQL query statement below */
| Id | Salary | select max(salary) into result
+----+--------+ from
| 1 | 100 | (select salary, dense_rank() over (order by salary desc) rank from employee)
| 2 | 200 | where rank = N;
| 3 | 300 |
+----+--------+ RETURN result;
For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth END;
highest salary, then the query should return null.
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200 |
+------------------------+