Menu

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)

Query all columns (attributes) for every row in the CITY table.
SELECT id, name, countrycode, district, population
FROM city;
Query all columns for all American cities in the CITY table with populations larger than 100,000. The CountryCode for America is USA.
SELECT id, name, countrycode, district, population
FROM city
WHERE countrycode = 'USA'
AND population > 100000;
Query the NAME field for all American cities in the CITY table with populations larger than 120,000. The CountryCode for America is USA.
SELECT name
FROM city
WHERE countrycode = 'USA'
AND population > 120000;
Query all columns for a city in CITY with the ID 1661.
SELECT id, name, countrycode, district, population
FROM city
WHERE id = 1661;
Query all attributes of every Japanese city in the CITY table. The COUNTRYCODE for Japan is JPN.
SELECT id, name, countrycode, district, population
FROM city
WHERE countrycode = 'JPN';
Query the names of all Japanese cities.
SELECT name
FROM city
WHERE countrycode = 'JPN';
Query a count of the number of cities in CITY having a Population larger than 100,000.
SELECT
    COUNT(name)
FROM
    city
WHERE
    population > 100000;
Query the total population of all cities in CITY where District is California.
SELECT
    SUM(population) AS totalPop
FROM
    city
WHERE
    district = 'California';
Query the average population of all cities in CITY where District is California.
SELECT
    AVG(population)
FROM
    city
WHERE
    district = 'California';
Query the average population for all cities in CITY, rounded down to the nearest integer.
SELECT
    ROUND(AVG(population), 0)
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) 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)

Query a list of CITY and STATE from the STATION table.
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.
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.
SELECT COUNT(city) - COUNT(DISTINCT city) AS difference
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.
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');
Query the list of CITY names ending with vowels (a, e, i, o, u) from STATION. Your result cannot contain duplicates.
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');
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 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');
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
    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');
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 
    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');
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
    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');
Query the list of CITY names from STATION that do not start with vowels or do not end with vowels. Your result cannot contain duplicates.
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');
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
    (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');
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.
(
    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
);
Consider and to be two points on a 2D plane.
• 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;
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.
SELECT
    ROUND(SUM(lat_n), 2) AS totalLatN,
    ROUND(SUM(long_w), 2) AS totalLongW
FROM
    station;
Query the sum of Northern Latitudes (LAT_N) from STATION having values greater than and less than. Truncate your answer to decimal places.
SELECT
    ROUND(SUM(lat_n), 4)
FROM
    station
WHERE
    lat_n > 38.7880
        AND
            lat_n < 137.2375;
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.
SELECT
    ROUND(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.
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.7780. Round your answer to 4 decimal places.
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.
SELECT
    ROUND(long_w, 4)
FROM
    station
WHERE
    lat_n = (
        SELECT
            MIN(lat_n)
        FROM
            station
        WHERE
            lat_n > 38.7780
    );
Consider P1(a,b) and P2(b,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.
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;
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.
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)

Imagine you're working for a library and you're tasked with generating a report on the borrowing habits of patrons. You have two tables in your database: Books and Borrowers.

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)

Query the Name of any student in STUDENTS who scored higher than 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
    SUBSTR(name, -3, 3) ASC,
    id ASC;

Salary (Hackerrank) Queries

Table Schema: Employee (Employee_ID INT, Name STR, Months INT, Salary INT)

Write a query that prints a list of employee names (i.e.: the name attribute) from the Employee table in alphabetical order.
SELECT
    name
FROM
    employee
ORDER BY
    name ASC;
Write a query that prints a list of employee names (i.e.: the name attribute) for employees in Employee having a salary greater than per month who have been employees for less than months. Sort your result by ascending employee_id.
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)

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.
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)

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).

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 )

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.
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)

We define an employee's total earnings to be their monthly 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 space-separated integers.
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)

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.
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)

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:

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;