SQL Basic Queries
This section contains solutions to Basic SQL questions from different websites like Hackerrank, NamasteSQL, etc. demonstrating fundamental SQL proficiency.
City (Hackerrank) Queries
Table Schema: City (ID NUMBER, Name VARCHAR(17), Countrycode VARCHAR(3), District VARCHAR(20), Population NUMBER)
SELECT id, name, countrycode, district, population
FROM city;
SELECT id, name, countrycode, district, population
FROM city
WHERE countrycode = 'USA'
AND population > 100000;
SELECT name
FROM city
WHERE countrycode = 'USA'
AND population > 120000;
SELECT id, name, countrycode, district, population
FROM city
WHERE id = 1661;
SELECT id, name, countrycode, district, population
FROM city
WHERE countrycode = 'JPN';
SELECT name
FROM city
WHERE countrycode = 'JPN';
SELECT
COUNT(name)
FROM
city
WHERE
population > 100000;
SELECT
SUM(population) AS totalPop
FROM
city
WHERE
district = 'California';
SELECT
AVG(population)
FROM
city
WHERE
district = 'California';
SELECT
ROUND(AVG(population), 0)
FROM
city;
SELECT
SUM(population)
FROM
city
WHERE
countrycode = 'JPN';
SELECT
MAX(population) - MIN(population) AS populationDiff
FROM
city;
Weather Obeservation Station Table (Hackerrank) Queries
Table Schema: Station (ID Number, City VARCHAR2(21), State VARCHAR2(2), LAT_N NUMBER, LONG_W NUMBER)
SELECT city, state
FROM
station;
SELECT DISTINCT city
FROM
station
WHERE
MOD(id, 2) = 0;
SELECT COUNT(city) - COUNT(DISTINCT city) AS difference
FROM
station;
SELECT DISTINCT city
FROM station
WHERE LOWER(city) LIKE 'a%'
OR
LOWER(city) LIKE 'e%'
OR
LOWER(city) LIKE 'i%'
OR
LOWER(city) LIKE 'o%'
OR
LOWER(city) LIKE 'u%';
SELECT DISTINCT city
FROM
station
WHERE
LOWER(SUBSTR(city, 1, 1)) IN ('a', 'e', 'i', 'o', 'u');
SELECT DISTINCT city
FROM
station
WHERE LOWER(city) LIKE '%a'
OR
LOWER(city) LIKE '%e'
OR
LOWER(city) LIKE '%i'
OR
LOWER(city) LIKE '%o'
OR
LOWER(city) LIKE '%u';
SELECT DISTINCT city
FROM
station
WHERE
LOWER(SUBSTR(city, -1, 1)) IN ('a', 'e', 'i', 'o', 'u');
SELECT DISTINCT city
FROM
station
WHERE (LOWER(city) LIKE 'a%'
OR
LOWER(city) LIKE 'e%'
OR
LOWER(city) LIKE 'i%'
OR
LOWER(city) LIKE 'o%'
OR
LOWER(city) LIKE 'u%')
AND
(LOWER(city) LIKE '%a'
OR
LOWER(city) LIKE '%e'
OR
LOWER(city) LIKE '%i'
OR
LOWER(city) LIKE '%o'
OR
LOWER(city) LIKE '%u');
SELECT DISTINCT city
FROM
station
WHERE
LOWER(SUBSTR(city, 1, 1)) IN ('a', 'e', 'i', 'o', 'u')
AND
LOWER(SUBSTR(city, -1, 1)) IN ('a', 'e', 'i', 'o', 'u');
SELECT
DISTINCT city
FROM
station
WHERE
LOWER(city) NOT LIKE 'a%'
AND
LOWER(city) NOT LIKE 'e%'
AND
LOWER(city) NOT LIKE 'i%'
AND
LOWER(city) NOT LIKE 'o%'
AND
LOWER(city) NOT LIKE 'u%';
SELECT
DISTINCT city
FROM
station
WHERE
LOWER(SUBSTR(city,1,1)) NOT IN ('a','e','i','o','u')
OR
LOWER(SUBSTR(city,-1,1)) NOT IN ('a','e','i','o','u');
SELECT
DISTINCT city
FROM
station
WHERE
LOWER(SUBSTR(city,1,1)) NOT IN ('a','e','i','o','u')
OR
LOWER(SUBSTR(city,-1,1)) NOT IN ('a','e','i','o','u');
SELECT
DISTINCT city
FROM
station
WHERE
LOWER(city) NOT LIKE '%a'
AND
LOWER(city) NOT LIKE '%e'
AND
LOWER(city) NOT LIKE '%i'
AND
LOWER(city) NOT LIKE '%o'
AND
LOWER(city) NOT LIKE '%u';
SELECT
DISTINCT city
FROM
station
WHERE
LOWER(SUBSTR(city, -1, 1)) NOT IN ('a','e','i','o','u');
SELECT
DISTINCT city
FROM
station
WHERE
(LOWER(city) NOT LIKE '%a'
AND
LOWER(city) NOT LIKE '%e'
AND
LOWER(city) NOT LIKE '%i'
AND
LOWER(city) NOT LIKE '%o'
AND
LOWER(city) NOT LIKE '%u')
OR
(LOWER(city) NOT LIKE 'a%'
AND
LOWER(city) NOT LIKE 'e%'
AND
LOWER(city) NOT LIKE 'i%'
AND
LOWER(city) NOT LIKE 'o%'
AND
LOWER(city) NOT LIKE 'u%');
SELECT
DISTINCT city
FROM
station
WHERE
LOWER(SUBSTR(city, 1, 1)) NOT IN ('a','e','i','o','u')
OR
LOWER(SUBSTR(city, -1, 1)) NOT IN ('a','e','i','o','u');
SELECT
DISTINCT city
FROM
station
WHERE
(LOWER(city) NOT LIKE '%a'
AND
LOWER(city) NOT LIKE '%e'
AND
LOWER(city) NOT LIKE '%i'
AND
LOWER(city) NOT LIKE '%o'
AND
LOWER(city) NOT LIKE '%u')
AND
(LOWER(city) NOT LIKE 'a%'
AND
LOWER(city) NOT LIKE 'e%'
AND
LOWER(city) NOT LIKE 'i%'
AND
LOWER(city) NOT LIKE 'o%'
AND
LOWER(city) NOT LIKE 'u%');
SELECT
DISTINCT city
FROM
station
WHERE
LOWER(SUBSTR(city, 1, 1)) NOT IN ('a','e','i','o','u')
AND
LOWER(SUBSTR(city, -1, 1)) NOT IN ('a','e','i','o','u');
(
SELECT
city,
LENGTH(city)
FROM (
SELECT
city
FROM
station
ORDER BY
LENGTH(city) ASC,
city ASC
)
WHERE ROWNUM = 1
)
UNION ALL
(
SELECT
city,
LENGTH(city)
FROM (
SELECT
city
FROM
station
ORDER BY
LENGTH(city) DESC,
city ASC
)
WHERE ROWNUM = 1
);
• a happens to equal the minimum value in Northern Latitude (LAT_N in STATION).
• b happens to equal the minimum value in Western Longitude (LONG_W in STATION).
• c happens to equal the maximum value in Northern Latitude (LAT_N in STATION).
• d happens to equal the maximum value in Western Longitude (LONG_W in STATION).
Query the Manhattan Distance between points and round it to a scale of decimal places.
SELECT
ROUND(ABS(MIN(lat_n) - MAX(lat_n)) + ABS(MIN(long_w) - MAX(long_w)), 4)
FROM
station;
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.
SELECT
ROUND(SUM(lat_n), 2) AS totalLatN,
ROUND(SUM(long_w), 2) AS totalLongW
FROM
station;
SELECT
ROUND(SUM(lat_n), 4)
FROM
station
WHERE
lat_n > 38.7880
AND
lat_n < 137.2375;
SELECT
ROUND(MAX(lat_n), 4)
FROM
station
WHERE
lat_n < 137.2345;
SELECT
ROUND(long_w, 4)
FROM
station
WHERE
lat_n = (
SELECT
MAX(lat_n)
FROM
station
WHERE
lat_n < 137.2345
);
SELECT
ROUND(MIN(lat_n), 4)
FROM
station
WHERE
lat_n > 38.7780;
SELECT
ROUND(long_w, 4)
FROM
station
WHERE
lat_n = (
SELECT
MIN(lat_n)
FROM
station
WHERE
lat_n > 38.7780
);
Query the Euclidean Distance between points P1 and P2 and format your answer to display 4 decimal digits.
SELECT
ROUND(
SQRT(
POWER(MAX(lat_n) - MIN(lat_n), 2) +
POWER(MAX(long_w) - MIN(long_w), 2)
), 4
) AS euclidean_distance
FROM
station;
SELECT
ROUND(MEDIAN(lat_n), 4)
FROM
station;
Library Borrowing Habits (NamasteSQL) Queries
Table Schema: Books (BookID INT, BookName VARCHAR(30), Genre VARCHAR(20))
Table Schema: Borrowers (BorrowersID INT, BorrowerName VARCHAR(10), BookID INT)
Write an SQL to display the name of each borrower along with a comma-separated list of the books they have borrowed in alphabetical order, display the output in ascending order of Borrower Name.
SELECT borrowerName,
STRING_AGG(bookName, ',') WITHIN GROUP (ORDER BY bookName) AS books
FROM
borrowers
JOIN
books
ON
borrowers.bookid = books.bookid
GROUP BY
borrowerName
ORDER BY
borrowerName;
Marksheet (Hackerrank) Queries
Table Schema: Students (ID INT, Name STR, Marks INT)
SELECT
name
FROM
students
WHERE
marks > 75
ORDER BY
SUBSTR(name, -3, 3) ASC,
id ASC;
Salary (Hackerrank) Queries
Table Schema: Employee (Employee_ID INT, Name STR, Months INT, Salary INT)
SELECT
name
FROM
employee
ORDER BY
name ASC;
SELECT
name
FROM
employee
WHERE
salary > 2000
AND
months < 10
ORDER BY
employee_id ASC;
Triangle (Hackerrank) Queries
Table Schema: Triangles (A INT, B INT, C INT)
• 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.
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'
WHEN a<>b AND b<>c AND a<>c THEN 'Scalene'
END
FROM
triangles;
Occupations (Hackerrank) Queries
Table Schema: Occupations (Name STR, Occupation STR)
Q. 2. 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.
-- For listing names with short occupation abbreviation
SELECT
CONCAT(
CONCAT(name, '('),
CONCAT(UPPER(SUBSTR(occupation, 1, 1)), ')')
)AS nameOccupation
FROM
occupations
ORDER BY
name;
-- For listing counts per occupation
SELECT
CONCAT(
CONCAT('There are a total of ', COUNT(*) || ' '),
CONCAT( LOWER(occupation), 's.')
)AS occupationCount
FROM
occupations
GROUP BY
occupation
ORDER BY
COUNT(*) ASC,
occupation ASC;
Employee Salary (Hackerrank) Queries
Table Schema: Employees (ID INT, Name STR, Salary INT )
Write a query calculating the amount of error (i.e.: average monthly salaries), and round it up to the next integer.
SELECT
CEIL(AVG(salary) - AVG(CAST(REPLACE(salary, '0', '') AS INT))) AS differenceSalary
FROM
employees;
Monthly Salary (Hackerrank) Queries
Table Schema: Employee (Employee_id INT, Name STR, Months INT, Salary INT)
WITH totalEarning AS(
SELECT
months * salary AS earnings,
employee_id
FROM
employee
)
SELECT
MAX(earnings),
COUNT(*)
FROM
totalEarning
WHERE
earnings = (SELECT MAX(earnings) FROM totalEarning);
Binary Tree Nodes (Hackerrank) Queries
Table Schema: BST (N INT, P INT)
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.
SELECT
N,
CASE
WHEN P IS NULL THEN 'Root' --Gets the value from N whose P value is NULL
WHEN N IN (SELECT DISTINCT P FROM BST) --Value N which has Parent node and that Parent node parent node THEN 'Inner'
ELSE 'Leaf' --Has a parent node but does not appears in P column
END AS node_type
FROM
BST
ORDER BY
N;
Binary Tree Nodes (Hackerrank) Queries
Table Schema: Company (company_code STR, founder STR)
Table Schema: Lead Manager (lead_manager_code STR, company_code STR)
Table Schema: Senior Manager (senior_manager_code STR, lead_manager_code STR, company_code STR)
Table Schema: Manager (manager_code STR, senior_manager_code STR, lead_manager_code STR, company_code STR)
Table Schema: Employee (employee_code STR, manager_code STR, senior_manager_code STR, lead_manager_code STR, company_code STR)
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:
1. Company: The company_code is the code of the company and founder is the founder of the company.
2. Lead_Manager: The lead_manager_code is the code of the lead manager, and the company_code is the code of the working company.
3. 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.
4. 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.
5. 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
comp.company_code,
comp.founder,
COUNT(DISTINCT lead.lead_manager_code) AS lead_manager_count,
COUNT(DISTINCT senior.senior_manager_code) AS senior_manager_count,
COUNT(DISTINCT mang.manager_code) AS manager_count,
COUNT(DISTINCT emp.employee_code) AS employee_count
FROM
company comp
INNER JOIN
lead_manager lead
ON
comp.company_code = lead.company_code
INNER JOIN
senior_manager senior
ON
lead.company_code = senior.company_code
INNER JOIN
manager mang
ON
senior.company_code = mang.company_code
INNER JOIN
employee emp
ON
mang.company_code = emp.company_code
GROUP BY
comp.company_code,
comp.founder
ORDER BY
comp.company_code;