- Notifications
You must be signed in to change notification settings - Fork0
shanuhalli/MySQL-Basics-to-HackerRank
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Query all columns for all American cities in the CITY table with populations larger than 100000. The CountryCode for America is USA.
Solution:
SELECT*FROM CITYWHERE COUNTRYCODE='USA'AND POPULATION>100000;
Query the NAME field for all American cities in the CITY table with populations larger than 120000. The CountryCode for America is USA.
Solution:
SELECT NAMEFROM CITYWHERE COUNTRYCODE='USA'AND POPULATION>120000;
Query all columns (attributes) for every row in the CITY table.
Solution:
SELECT*FROM CITY;
Query all columns for a city in CITY with the ID 1661.
Solution:
SELECT*FROM CITYWHERE ID=1661;
Query all attributes of every Japanese city in the CITY table. The COUNTRYCODE for Japan is JPN.
Solution:
SELECT*FROM CITYWHERE COUNTRYCODE='JPN';
Query the names of all the Japanese cities in the CITY table. The COUNTRYCODE for Japan is JPN.
Solution:
SELECT NAMEFROM CITYWHERE COUNTRYCODE='JPN';
Query a list of CITY and STATE from the STATION table.
Solution:
SELECT CITY, STATEFROM 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.
Solution:
SELECT DISTINCT CITYFROM STATIONWHERE MOD (ID,2)=0ORDER BY CITY;
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.
Solution:
SELECT CITY, LENGTH(CITY)FROM STATIONORDER BY LENGTH(CITY)ASC, CITYLIMIT1;SELECT CITY, LENGTH(CITY)FROM STATIONORDER BY LENGTH(CITY)DESC, CITYLIMIT1;
Find the difference between the total number of CITY entries in the table and the number of distinct CITY entries in the table.
Solution:
SELECTCOUNT(CITY) –COUNT (DISTINCT CITY)FROM STATION;
Query the list of CITY names starting with vowels (i.e., a, e, i, o, or u) from STATION. Your result cannot contain duplicates.
Solution:
SELECT DISTINCT CITYFROM STATIONWHERE LEFT(CITY,1)IN ('A','E','I','O','U');
Query the list of CITY names ending with vowels (a, e, i, o, u) from STATION. Your result cannot contain duplicates.
Solution:
SELECT DISTINCT CITYFROM STATIONWHERE RIGHT(CITY,1)IN ('A','E','I','O','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.
Solution:
SELECT DISTINCT CITYFROM STATIONWHERE LEFT(CITY,1)IN ('A','E','I','O','U')AND RIGHT(CITY,1)IN ('A','E','I','O','U');
Query the list of CITY names from STATION that do not start with vowels. Your result cannot contain duplicates.
Solution:
SELECT DISTINCT CITYFROM STATIONWHERE LEFT(CITY,1) NOTIN ('A','E','I','O','U');
Query the list of CITY names from STATION that do not end with vowels. Your result cannot contain duplicates.
Solution:
SELECT DISTINCT CITYFROM STATIONWHERE RIGHT(CITY,1) NOTIN ('A','E','I','O','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.
Solution:
SELECT DISTINCT CITYFROM STATIONWHERE LEFT(CITY,1) NOTIN ('A','E','I','O','U')OR RIGHT(CITY,1) NOTIN ('A','E','I','O','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.
Solution:
SELECT DISTINCT CITYFROM STATIONWHERE LEFT(CITY,1) NOTIN ('A','E','I','O','U')ANDRIGHT(CITY,1) NOTIN ('A','E','I','O','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.
Solution:
SELECT NAMEFROM STUDENTSWHERE MARKS>75ORDER BY RIGHT(NAME,3), IDASC;
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.
Write a query that prints a list of employee names (i.e.: the name attribute) from the Employee table in alphabetical order.
Solution:
SELECT NAMEFROM EMPLOYEEORDER 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.
Solution:
SELECT NAMEFROM EMPLOYEEWHERE SALARY>2000AND MONTHS<10ORDER BY EMPLOYEE_ID;
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 3 sides of equal length.
•Isosceles: It's a triangle with 2 sides of equal length.
•Scalene: It's a triangle with 3 sides of differing lengths.
•Not A Triangle: The given values of A, B, and C don't form a triangle.
Solution:
SELECT CASEWHEN A+B<= COR A+C<= BOR B+C<= A THEN"Not A Triangle"WHEN A= BAND B= C THEN"Equilateral"WHEN A= BOR A= COR B= C THEN"Isosceles"ELSE"Scalene"ENDAS TRIANGLE_SIDESFROM TRIANGLES
Generate the following two result sets:
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).
Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:
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.
Solution:
SELECT CONCAT(NAME,'(',SUBSTRING(OCCUPATION,1,1),')')AS NAMEFROM OCCUPATIONSORDER BY NAME;SELECT CONCAT ('There are a total of',COUNT(OCCUPATION),'',LOWER(OCCUPATION),'s.')AS TOTALSFROM OCCUPATIONSGROUP BY OCCUPATIONORDER BY TOTALS
Pivot the Occupation column in OCCUPATIONS so that each Name is sorted alphabetically and displayed underneath its corresponding Occupation. The output column headers should be Doctor, Professor, Singer, and Actor, respectively.
Note: Print NULL when there are no more names corresponding to an occupation.
Solution:
SELECT Doctor, Professor, Singer, ActorFROM (SELECT NameOrder,MAX(CASE Occupation WHEN'Doctor' THEN Name END)AS Doctor,MAX(CASE Occupation WHEN'Professor' THEN Name END)AS Professor,MAX(CASE Occupation WHEN'Singer' THEN Name END)AS Singer,MAX(CASE Occupation WHEN'Actor' THEN Name END)AS ActorFROM (SELECT Occupation, Name, Row_Number() OVER(PARTITION BY OccupationORDER BY NameASC)AS NameOrderFROM Occupations)AS NameListsGROUP BY NameOrder)AS NAMES
You are given a table, BST, containing two columns: N and P, where N represents the value of a node in Binary Tree, and P is the parent of N.
Write a query to find the node type of Binary Tree ordered by the value of the node. Output one of the following for each node:
•Root: If node is root node.
•Leaf: If node is leaf node.
•Inner: If node is neither root nor leaf node.
Solution:
SELECT N,CASE WHEN P ISNULL THEN'Root' WHEN NIN (SELECT PFROM BST) THEN'Inner' ELSE'Leaf'ENDFROM BSTORDER BY N;
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.
The following tables contain company data:
•Company: The company_code is the code of the company and founder is the founder of the
•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.
Solution:
SELECTC.COMPANY_CODE,C.FOUNDER, (SELECTCOUNT(DISTINCT LEAD_MANAGER_CODE)FROM LEAD_MANAGER LWHEREL.COMPANY_CODE=C.COMPANY_CODE), (SELECTCOUNT(DISTINCT SENIOR_MANAGER_CODE)FROM SENIOR_MANAGER SWHERES.COMPANY_CODE=C.COMPANY_CODE), (SELECTCOUNT(DISTINCT MANAGER_CODE)FROM MANAGER MWHEREM.COMPANY_CODE=C.COMPANY_CODE), (SELECTCOUNT(DISTINCT EMPLOYEE_CODE)FROM EMPLOYEE EWHEREE.COMPANY_CODE=C.COMPANY_CODE)FROM COMPANY CORDER BYC.COMPANY_CODEASC;
Query a count of the number of cities in CITY having a Population larger than.
Solution:
SELECTCOUNT (*)FROM CITYWHERE POPULATION>100000;
Query the total population of all cities in CITY where District is California.
Solution:
SELECTSUM(POPULATION)FROM CITYWHERE DISTRICT='California';
Query the average population of all cities in CITY where District is California.
Solution:
SELECTAVG(POPULATION)FROM CITYWHERE DISTRICT='California'
Query the average population for all cities in CITY, rounded down to the nearest integer.
Solution:
SELECT FLOOR(AVG(POPULATION))FROM CITY
Query the sum of the populations for all Japanese cities in CITY. The COUNTRYCODE for Japan is JPN.
Solution:
SELECTSUM(POPULATION)FROM CITYWHERE COUNTRYCODE='JPN'
Query the difference between the maximum and minimum populations in CITY.
Solution:
SELECTMAX(POPULATION)-MIN(POPULATION)FROM CITY
Samantha was tasked with calculating the average monthly salaries for all employees in the EMPLOYEES table, but did not realize her keyboard's 0 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.: Actual - Miscalculated average monthly salaries), and round it up to the next integer.
Note: Salary is per month.
Constraints: 1000 < Salary < 10**5
Solution:
SELECT CEIL(AVG(SALARY)-AVG (REPLACE (SALARY,'0','')))FROM EMPLOYEES;
We define an employee's total earnings to be their monthly salary * 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 2 space-separated integers.
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.
Solution:
SELECT MONTHS* SALARYAS EARNINGS,COUNT (*)FROM EMPLOYEEGROUP BY EARNINGSORDER BY EARNINGSDESCLIMIT1;
Query the following two values from the STATION table:
- The sum of all values in LAT_N rounded to a scale of 2 decimal places.
- The sum of all values in LONG_W rounded to a scale of 2 decimal places.
Solution:
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 4 decimal places.
Solution:
SELECT ROUND(SUM(LAT_N),4)FROM STATIONWHERE LAT_N BETWEEN38.7880AND137.2345;
Query the greatest value of the Northern Latitudes (LAT_N) from STATION that is less than 137.2345. Truncate your answer to 4 decimal places.
Solution:
SELECT ROUND(MAX(LAT_N),4)FROM STATIONWHERE 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.
Solution:
SELECT ROUND(LONG_W,4)FROM STATIONWHERE LAT_N= (SELECTMAX(LAT_N)FROM STATIONWHERE LAT_N<137.2345);
Query the smallest Northern Latitude (LAT_N) from STATION that is greater than 38.7780. Round your answer to 4 decimal places.
Solution:
SELECT ROUND(MIN(LAT_N),4)FROM STATIONWHERE 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.
Solution:
SELECT ROUND(LONG_W,4)FROM STATIONWHERE LAT_N= (SELECTMIN(LAT_N)FROM STATIONWHERE LAT_N>38.7780);
Consider P1(a,b) and P2(c,d) to be two points on a 2D plane.
•happens to equal the minimum value in Northern Latitude (LAT_N in STATION).
•happens to equal the minimum value in Western Longitude (LONG_W in STATION).
•happens to equal the maximum value in Northern Latitude (LAT_N in STATION).
•happens to equal the maximum value in Western Longitude (LONG_W in STATION).
Query the Manhattan Distance between points P1 and P2 and round it to a scale of 4 decimal places.
Solution:
SELECT ROUND(ABS(MAX(LAT_N)-MIN(LAT_N))+ ABS(MAX(LONG_W)-MIN(LONG_W)),4)FROM STATION;
Consider P1(a,b) and P2(c,d) to be two points on a 2D plane where (a,b) are the respective minimum and maximum values of Northern Latitude (LAT_N) and (c,d) are the respective minimum and maximum values of Western Longitude (LONG_W) in STATION.
Query the Euclidean Distance between points P1 and P2 and format your answer to display 4 decimal digits.
Solution:
SELECT ROUND(SQRT(POWER(MAX(LAT_N)-MIN(LAT_N),2)+ POWER(MAX(LONG_W)-MIN(LONG_W),2)),4)FROM STATION;
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 4 decimal places.
Solution:
SELECT CAST (LAT_NASDECIMAL (7,4))FROM (SELECT LAT_N, ROW_NUMBER () OVER (ORDER BY LAT_N)as ROWNUFROM STATION)AS XWHERE ROWNU= (SELECT ROUND((COUNT(LAT_N)+1)/2,0)FROM STATION);
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.
Solution:
SELECTSUM(CITY.POPULATION)FROM CITYJOIN COUNTRYONCITY.COUNTRYCODE=COUNTRY.CODEWHERECOUNTRY.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.
Solution:
SELECTCITY.NAMEFROM CITYJOIN COUNTRYONCITY.COUNTRYCODE=COUNTRY.CODEWHERECOUNTRY.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.
Solution:
SELECTCOUNTRY.CONTINENT, FLOOR(AVG(CITY.POPULATION))FROM COUNTRYJOIN CITYONCOUNTRY.CODE=CITY.COUNTRYCODEGROUP BYCOUNTRY.CONTINENT;
You are given two tables: Students and Grades. Students contains three columns ID, Name and Marks.
Grades contains the following data:
Ketty gives Eve a task to generate a report containing three columns: Name, Grade and Mark. Ketty doesn't want the NAMES of those students who received a grade lower than 8. The report must be in descending order by grade -- i.e. higher grades are entered first. If there is more than one student with the same grade (8-10) assigned to them, order those particular students by their name alphabetically. Finally, if the grade is lower than 8, use "NULL" as their name and 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.
Write a query to help Eve.
Solution:
SELECT CASE WHEN Grade>=8 THEN Name END, Grade, MarksFROM StudentsJOIN GradesON Marks BETWEEN Min_MarkAND Max_MarkORDER BY GradeDESC, Name, Marks;
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.
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.
Solution:
SELECTH.HACKER_ID,H.NAMEFROM HACKERS HINNER JOIN SUBMISSIONS SONH.HACKER_ID=S.HACKER_IDINNER JOIN CHALLENGES CONS.CHALLENGE_ID=C.CHALLENGE_IDINNER JOIN DIFFICULTY DONC.DIFFICULTY_LEVEL=D.DIFFICULTY_LEVELWHERES.SCORE=D.SCOREANDC.DIFFICULTY_LEVEL=D.DIFFICULTY_LEVELGROUP BYH.HACKER_ID,H.NAMEHAVINGCOUNT(S.HACKER_ID)>1ORDER BYCOUNT(S.HACKER_ID)DESC,S.HACKER_IDASC;
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.
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. The mapping between code and age is one-one, meaning that if there are two pairs, (code1, age1) and (code2, age2), then code1 ≠ code2 and age1 ≠ age2.
Solution:
SELECTW.ID,P.AGE,W.COINS_NEEDED,W.POWERFROM WANDSAS WJOIN WANDS_PROPERTYAS PON (W.CODE=P.CODE)WHEREP.IS_EVIL=0ANDW.COINS_NEEDED= (SELECTMIN(COINS_NEEDED)FROM WANDSAS XJOIN WANDS_PROPERTYAS YON (X.CODE=Y.CODE)WHEREX.POWER=W.POWERANDY.AGE=P.AGE)ORDER BYW.POWERDESC,P.AGEDESC;
About
Learn about basic MySQL and My solutions to various HackerRank SQL problems using MySQL
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.




























