0% found this document useful (0 votes)
334 views31 pages

SQL Query Practice Guide

The document contains SQL queries and descriptions of tables. The queries select, filter, aggregate and perform calculations on data from tables like CITY, STATION, and OCCUPATIONS. The tables contain information like city names and populations, latitude/longitude coordinates, and occupations with counts. The queries use functions, operators and clauses like SELECT, FROM, WHERE, GROUP BY, ORDER BY, SUM, AVG, COUNT, MAX, MIN and more.

Uploaded by

kokushal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
334 views31 pages

SQL Query Practice Guide

The document contains SQL queries and descriptions of tables. The queries select, filter, aggregate and perform calculations on data from tables like CITY, STATION, and OCCUPATIONS. The tables contain information like city names and populations, latitude/longitude coordinates, and occupations with counts. The queries use functions, operators and clauses like SELECT, FROM, WHERE, GROUP BY, ORDER BY, SUM, AVG, COUNT, MAX, MIN and more.

Uploaded by

kokushal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Query the 

NAME field for all American cities in the CITY table with populations larger than 120000. The CountryCode for

America is USA.

The CITY table is described as follows:

SELECT * FROM CITY WHERE COUNTRYCODE = "USA" AND POPULATION > 100000;

Query all columns (attributes) for every row in the CITY table.

The CITY table is described as follows:

Select * from City


Query all columns for a city in CITY with the ID 1661.

The CITY table is described as follows:

Select * from City where ID = 1661

Query all attributes of every Japanese city in the CITY table. The COUNTRYCODE for Japan is JPN.

The CITY table is described as follows:

Select * from City where COUNTRYCODE = "JPN"


Query the names of all the Japanese cities in the CITY table. The COUNTRYCODE for Japan is JPN.
The CITY table is described as follows:

Select Name from City where COUNTRYCODE = "JPN"

Query a list of CITY and STATE from the STATION table.

The STATION table is described as follows:

where LAT_N is the northern latitude and LONG_W is the western longitude.

Select City, State From Station

Query a list of CITY names from STATION for cities that have an even ID number. Print the results in any order, but

exclude duplicates from the answer.

The STATION table is described as follows:


where LAT_N is the northern latitude and LONG_W is the western longitude.

Select Distinct City from Station Where mod(ID,2) = 0

Find the difference between the total number of CITY entries in the table and the number of distinct CITY entries in the

table.

The STATION table is described as follows:

where LAT_N is the northern latitude and LONG_W is the western longitude.

For example, if there are three records in the table with CITY values 'New York', 'New York', 'Bengalaru', there are 2

different city names: 'New York' and 'Bengalaru'. The query returns 1 , because

Select Count(City) - Count(Distinct City) from Station


Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of

characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically.

The STATION table is described as follows:

where LAT_N is the northern latitude and LONG_W is the western longitude.

Sample Input

For example, CITY has four entries: DEF, ABC, PQRS and WXY.

Sample Output

ABC 3
PQRS 4

select CITY,LENGTH(CITY) from STATION order by Length(CITY) asc, CITY limit 1;


select CITY,LENGTH(CITY) from STATION order by Length(CITY) desc, CITY limit 1;
Query the list of CITY names starting with vowels (i.e., a, e, i, o, or u) from STATION. Your result cannot contain duplicates.

Input Format

The STATION table is described as follows:

where LAT_N is the northern latitude and LONG_W is the western longitude.

Select City From Station Where


City Like "a%"
Or
City Like "e%"
Or
City Like "i%"
Or
City Like "o%"
Or
City Like "u%"

Query the list of CITY names ending with vowels (a, e, i, o, u) from STATION. Your result cannot contain duplicates.

Input Format

The STATION table is described as follows:


where LAT_N is the northern latitude and LONG_W is the western longitude.

Select Distinct City From Station Where


City Like "%a" Or City Like "%e" Or City Like "%i" Or City Like "%o" Or City Like "%u" ;

Query the list of CITY names from STATION which have vowels (i.e., a, e, i, o, and u) as both their first and last characters. Your

result cannot contain duplicates.

Select City From Station Where


(City Like "a%" Or City Like "e%" Or City Like "i%" Or City Like "o%"
Or City Like "u%")
AND
(City Like "%a" Or City Like "%e" Or City Like "%i" Or City Like "%o"
Or City Like "%u")

Query the list of CITY names from STATION that do not start with vowels. Your result cannot contain duplicates.

Select Distinct City From Station Where NOT


(City Like "a%" Or City Like "e%" Or City Like "i%" Or City Like "o%"
Or City Like "u%")

Query the list of CITY names from STATION that do not end with vowels. Your result cannot contain duplicates.

Select Distinct City From Station Where NOT


(City Like "%a" Or City Like "%e" Or City Like "%i" Or City Like "%o" Or City Like "%u") ;
Query the list of CITY names from STATION that either do not start with vowels or do not end with vowels. Your result
cannot contain duplicates.

Select Distinct City From Station Where NOT


(City Like "a%" Or City Like "e%" Or City Like "i%" Or City Like "o%"
Or City Like "u%")
OR
NOT
(City Like "%a" Or City Like "%e" Or City Like "%i" Or City Like "%o" Or City Like "%u") ;

Query the list of CITY names from STATION that do not start with vowels and do not end with vowels. Your result cannot
contain duplicates.

Select Distinct City From Station Where NOT


(City Like "a%" Or City Like "e%" Or City Like "i%" Or City Like "o%"
Or City Like "u%")
AND
NOT
(City Like "%a" Or City Like "%e" Or City Like "%i" Or City Like "%o" Or City Like "%u") ;

Query the Name of any student in STUDENTS who scored higher than 75 Marks. Order your output by the last three
characters of each name. If two or more students both have names ending in the same last three characters (i.e.: Bobby,
Robby, etc.), secondary sort them by ascending ID.

Select Name from Students where Marks > 75 Order By Right(Name,3) ASC, ID ASC

Write a query that prints a list of employee names (i.e.: the name attribute) from the Employee table in alphabetical order.

Input Format

The Employee table containing employee data for a company is described as follows:


where employee_id is an employee's ID number, name is their name, months is the total number of months they've been working for

the company, and salary is their monthly salary.

Select Name From Employee Order By Name

Write a query that prints a list of employee names (i.e.: the name attribute) for employees in Employee having a salary greater

than  2000 per month who have been employees for less than 10 months. Sort your result by ascending employee_id.

Input Format

The Employee table containing employee data for a company is described as follows:

Select name from Employee where salary > 2000 And months < 10

Write a query identifying the type of each record in the TRIANGLES table using its three side lengths. Output one of the following

statements for each record in the table:

 Equilateral: It's a triangle with  sides of equal length.

 Isosceles: It's a triangle with  sides of equal length.

 Scalene: It's a triangle with  sides of differing lengths.

 Not A Triangle: The given values of A, B, and C don't form a triangle.

Input Format

The TRIANGLES table is described as follows:

Each row in the table denotes the lengths of each of a triangle's three sides.

Sample Input
Sample Output

Isosceles
Equilateral
Scalene
Not A Triangle

Select Case
WHEN A + B <= C OR A + C <= B OR B + C <= A THEN 'Not A Triangle'
WHEN A = B AND B = C THEN 'Equilateral'
WHEN A = B OR B = C OR A = C THEN 'Isosceles'
ELSE 'Scalene'
END
FROM TRIANGLES;

Generate the following two result sets:

1. Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each

profession as a parenthetical (i.e.: enclosed in parentheses). For

example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).

2. Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and

output them in the following format:

3. There are a total of [occupation_count] [occupation]s.


where [occupation_count] is the number of occurrences of an occupation in OCCUPATIONS and [occupation] is

the lowercase occupation name. If more than one Occupation has the same [occupation_count], they should be ordered

alphabetically.

Note: There will be at least two entries in the table for each type of occupation.

Input Format

The OCCUPATIONS table is described as follows:   Occupation will only

contain one of the following values: Doctor, Professor, Singer or Actor.

Sample Input

An OCCUPATIONS table that contains the following records:

Sample Output

Ashely(P)
Christeen(P)
Jane(A)
Jenny(D)
Julia(A)
Ketty(P)
Maria(A)
Meera(S)
Priya(S)
Samantha(D)
There are a total of 2 doctors.
There are a total of 2 singers.
There are a total of 3 actors.
There are a total of 3 professors.

SELECT CONCAT(Name,'(', LEFT(Occupation,1),')') FROM OCCUPATIONS ORDER BY Name ASC;

SELECT
CONCAT("There are a total of", " ", COUNT(occupation), " ", LOWER(occupation), "s", ".")
FROM OCCUPATIONS GROUP By occupation ORDER BY COUNT(occupation) ASC, occupation;

Query the total population of all cities in CITY where District is California.

Input Format

The CITY table is described as follows:

 
SELECT SUM(POPULATION) FROM CITY WHERE DISTRICT = "California"

Query the average population of all cities in CITY where District is California.

Input Format

The CITY table is described as follows:

SELECT AVG(POPULATION) FROM CITY WHERE District = "California"

Query the average population for all cities in CITY, rounded down to the nearest integer.

Input Format

The CITY table is described as follows:

 
SELECT ROUND(AVG(POPULATION))FROM CITY

Query the sum of the populations for all Japanese cities in CITY. The COUNTRYCODE for Japan is JPN.

SELECT SUM(POPULATION) FROM CITY WHERE COUNTRYCODE = "JPN"

Query the difference between the maximum and minimum populations in CITY.

SELECT MAX(POPULATION)-MIN(POPULATION) FROM CITY

Query the following two values from the STATION table:

1. The sum of all values in LAT_N rounded to a scale of  decimal places.

2. The sum of all values in LONG_W rounded to a scale of  decimal places.

Input Format

The STATION table is described as follows:

where LAT_N is the northern latitude and LONG_W is the western longitude.

SELECT ROUND(SUM(LAT_N),2),ROUND(SUM(LONG_W),2) FROM STATION

Query the sum of Northern Latitudes (LAT_N) from STATION having values greater than 38.7880  and less than 137.2345. Truncate

your answer to  decimal places.

Input Format

The STATION table is described as follows:


SELECT TRUNCATE(SUM(LAT_N),4) FROM STATION WHERE LAT_N > 38.7880 AND LAT_N <
137.2345

Query the greatest value of the Northern Latitudes (LAT_N) from STATION that is less than . Truncate your answer
to  137.2345 decimal places.

SELECT TRUNCATE(MAX(LAT_N),4) FROM STATION WHERE LAT_N < 137.2345

Query the Western Longitude (LONG_W) for the largest Northern Latitude (LAT_N) in STATION that is less than 137.2345. Round

your answer to 4 decimal places.

Input Format

The STATION table is described as follows:

SELECT ROUND(LONG_W,4) FROM STATION WHERE LAT_N = (SELECT MAX(LAT_N) FROM STATION
WHERE LAT_N < 137.2345)
Query the smallest Northern Latitude (LAT_N) from STATION that is greater than 38.7880 . Round your answer to  4 decimal places.

Input Format

The STATION table is described as follows:

SELECT ROUND(MIN(LAT_N),4) FROM STATION WHERE LAT_N > 38.7780

Query the Western Longitude (LONG_W)where the smallest Northern Latitude (LAT_N) in STATION is greater than 38.7780 .

Round your answer to 4 decimal places.

Input Format

The STATION table is described as follows:

SELECT ROUND(LONG_W,4) FROM STATION WHERE LAT_N = (SELECT MIN(LAT_N) FROM STATION

WHERE LAT_N > 38.7780)


Samantha was tasked with calculating the average monthly salaries for all employees in the EMPLOYEES table, but did not realize

her keyboard's  key was broken until after completing the calculation. She wants your help finding the difference between her

miscalculation (using salaries with any zeros removed), and the actual average salary.

Write a query calculating the amount of error (i.e.:  average monthly salaries), and round it up to the next integer.

Input Format

The EMPLOYEES table is described as follows:

SELECT CEILING(AVG(SALARY) - AVG(REPLACE(SALARY,0,""))) FROM EMPLOYEES

We define an employee's total earnings to be their monthly SALARY X MONTHS worked, and the maximum total earnings to be the

maximum total earnings for any employee in the Employee table. Write a query to find the maximum total earnings for all employees

as well as the total number of employees who have maximum total earnings. Then print these values as TWO space-separated

integers.

Input Format

The Employee table containing employee data for a company is described as follows:

where employee_id is an employee's ID number, name is their name, months is the total number of months they've been working for

the company, and salary is the their monthly salary.

Sample Input
SELECT (SALARY*MONTHS),COUNT(NAME) FROM EMPLOYEE
WHERE (SALARY*MONTHS) = (SELECT MAX(SALARY*MONTHS) FROM EMPLOYEE)
GROUP BY (SALARY*MONTHS)

Given the CITY and COUNTRY tables, query the sum of the populations of all cities where the CONTINENT is 'Asia'.

Note: CITY.CountryCode and COUNTRY.Code are matching key columns.

Input Format

The CITY and COUNTRY tables are described as follows: 


SELECT SUM(CITY.POPULATION) FROM CITY INNER JOIN COUNTRY
ON CITY.COUNTRYCODE = COUNTRY.CODE
WHERE COUNTRY.CONTINENT = "Asia"

Given the CITY and COUNTRY tables, query the names of all cities where the CONTINENT is 'Africa'.

Note: CITY.CountryCode and COUNTRY.Code are matching key columns.

Input Format
The CITY and COUNTRY tables are described as follows: 

SELECT CITY.NAME FROM CITY INNER JOIN COUNTRY


ON CITY.COUNTRYCODE = COUNTRY.CODE
WHERE COUNTRY.CONTINENT = "Africa"
Given the CITY and COUNTRY tables, query the names of all the continents (COUNTRY.Continent) and their respective average

city populations (CITY.Population) rounded down to the nearest integer.

Note: CITY.CountryCode and COUNTRY.Code are matching key columns.

Input Format

The CITY and COUNTRY tables are described as follows: 


SELECT COUNTRY.CONTINENT,FLOOR(AVG(CITY.POPULATION))
FROM CITY INNER JOIN COUNTRY
ON CITY.COUNTRYCODE = COUNTRY.CODE
GROUP BY COUNTRY.CONTINENT

You are given three tables: Students,  Friends  and  Packages. Students contains two columns: ID and Name. Friends contains

two columns: ID and Friend_ID (ID of the ONLY best friend). Packages contains two columns: ID and Salary (offered salary

in $ thousands per month).

Write a query to output the names of those students whose best friends got offered a higher salary than them. Names

must be ordered by the salary amount offered to the best friends. It is guaranteed that no two students got same salary

offer.

Sample Input
 

Sample Output

Samantha
Julia
Scarlet

Explanation

See the following table:

Now,

 Samantha's best friend got offered a higher salary than her at 11.55

 Julia's best friend got offered a higher salary than her at 12.12

 Scarlet's best friend got offered a higher salary than her at 15.2


 Ashley's best friend did NOT get offered a higher salary than her

The name output, when ordered by the salary offered to their friends, will be:

 Samantha

 Julia

 Scarlet

SELECT s.Name
FROM Students s
INNER JOIN Packages p1 ON s.ID = p1.ID
INNER JOIN Friends f ON s.ID = f.ID
INNER JOIN Packages p2 ON f.Friend_ID = p2.ID
WHERE p2.Salary > p1.Salary
ORDER BY p2.Salary;

Julia just finished conducting a coding contest, and she needs your help assembling the leaderboard! Write a query to print the

respective hacker_id and name of hackers who achieved full scores for more than one challenge. Order your output in descending

order by the total number of challenges in which the hacker earned a full score. If more than one hacker received full scores in same

number of challenges, then sort them by ascending hacker_id.

Input Format

The following tables contain contest data:

 Hackers: The hacker_id is the id of the hacker, and name is the name of the hacker. 

 Difficulty: The difficult_level is the level of difficulty of the challenge, and score is the score of the challenge for the

difficulty level. 
 Challenges: The challenge_id is the id of the challenge, the hacker_id is the id of the hacker who created the challenge,

and difficulty_level is the level of difficulty of the challenge. 

 Submissions: The submission_id is the id of the submission, hacker_id is the id of the hacker who made the

submission, challenge_id is the id of the challenge that the submission belongs to, and score is the score of the

submission. 

Sample Input
Hackers Table:   Difficulty Table:   Challenges Table

:   Submissions Table

Sample Output

90411 Joe
Explanation

Hacker 86870 got a score of 30 for challenge 71055 with a difficulty level of 2, so 86870 earned a full score for this challenge.

Hacker 90411 got a score of 30 for challenge 71055 with a difficulty level of 2, so 90411 earned a full score for this challenge.

Hacker 90411 got a score of 100 for challenge 66730 with a difficulty level of 6, so 90411 earned a full score for this challenge.

Only hacker 90411 managed to earn a full score for more than one challenge, so we print the their hacker_id and name as 2 space-

separated values.
select h.hacker_id, h.name from Submissions as s join Hackers as h
on s.hacker_id = h.hacker_id
join Challenges as c on s.challenge_id = c.challenge_id
join Difficulty as d on c.Difficulty_level = d.Difficulty_level
where s.score = d.score
group by h.hacker_id, h.name
having count(*) > 1
order by count(*) desc, h.hacker_id;

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.

Input Format

The following tables contain data on the wands in Ollivander's inventory:

 Wands: The id is the id of the wand, code is the code of the wand, coins_needed is the total number of gold galleons

needed to buy the wand, and power denotes the quality of the wand (the higher the power, the better the wand

is). 

 Wands_Property: The code is the code of the wand, age is the age of the wand, and is_evil denotes whether the wand is

good for the dark arts. If the value of is_evil is 0, it means that the wand is not evil.

SELECT aa.id, bb.age, aa.coins_needed, aa.power


FROM WANDS AS aa
INNER JOIN WANDS_PROPERTY AS bb ON aa.CODE = bb.CODE
INNER JOIN (SELECT age AS AG, MIN(coins_needed) AS MCN, power AS PW
FROM WANDS AS A
INNER JOIN WANDS_PROPERTY AS B ON A.CODE = B.CODE
WHERE IS_EVIL = 0
GROUP BY power, age) AS Q ON bb.age = AG AND aa.coins_needed = MCN AND aa.power = PW
ORDER BY aa.power DESC, bb.age DESC
Amber's conglomerate corporation just acquired some new companies. Each of the companies follows this

hierarchy: 

Given the table schemas below, write a query to print the company_code, founder name, total number of lead managers, total number

of senior managers, total number of managers, and total number of employees. Order your output by ascending company_code.

Note:

 The tables may contain duplicate records.

 The company_code is string, so the sorting should not be numeric. For example, if the company_codes are C_1, C_2,

and C_10, then the ascending company_codes will be C_1, C_10, and C_2.

Input Format

The following tables contain company data:

 Company: The company_code is the code of the company and founder is the founder of the company. 

 Lead_Manager: The lead_manager_code is the code of the lead manager, and the company_code is the code of the

working company.

  

 Senior_Manager: The senior_manager_code is the code of the senior manager, the lead_manager_code is the code of its

lead manager, and the company_code is the code of the working company. 


 Manager: The manager_code is the code of the manager, the senior_manager_code is the code of its senior manager,

the lead_manager_code is the code of its lead manager, and the company_code is the code of the working company.

  

 Employee: The employee_code is the code of the employee, the manager_code is the code of its manager,

the senior_manager_code is the code of its senior manager, the lead_manager_code is the code of its lead manager, and

the company_code is the code of the working company. 

select c.company_code, c.founder,


count(distinct l.lead_manager_code),
count(distinct s.senior_manager_code),
count(distinct m.manager_code),
count(distinct e.employee_code)
from Company as c
join Lead_Manager as l
on c.company_code = l.company_code
join Senior_Manager as s
on l.lead_manager_code = s.lead_manager_code
join Manager as m
on m.senior_manager_code = s.senior_manager_code
join Employee as e
on e.manager_code = m.manager_code
group by c.company_code, c.founder
order by c.company_code;

A median is defined as a number separating the higher half of a data set from the lower half. Query the median of the Northern

Latitudes (LAT_N) from STATION and round your answer to  decimal places.

Input Format

The STATION table is described as follows:

SELECT ROUND(S1.LAT_N, 4)
FROM STATION AS S1
WHERE (SELECT ROUND(COUNT(S1.ID)/2) - 1
FROM STATION) =
(SELECT COUNT(S2.ID)
FROM STATION AS S2
WHERE S2.LAT_N > S1.LAT_N);

You might also like