MySQL Notes

Short Notes Found while Practice in MySQL

1. Find Even Numbers: (Cannot use % in SQL) : MOD

WHERE MOD(ID,2) = 0;

2. Subtraction Operation in SQL: COUNT, DISTINCT

 SELECT COUNT(CITY) - COUNT(DISTINCT CITY) 

3. String Length: LENGTH

SELECT LENGTH(CITY)

4. Using AS Variable: AS

SELECT LENGTH(CITY) AS CITY_LENGTH

5. Return Only the Shortest CITY Name (1 Row Only): LIMIT

SELECT CITY , LENGTH(CITY) AS CITY_LENGTH
FROM STATION
ORDER BY CITY_LENGTH ASC,CITY ASC
LIMIT 1;

6. Return Only the Longest CITY Name (1 Row Only): LIMIT

SELECT CITY , LENGTH(CITY) AS CITY_LENGTH
FROM STATION
ORDER BY CITY_LENGTH DESC, CITY ASC
LIMIT 1;

7. Match Null Value: IS NULL or IS NOT NULL

8. Not equal operator : <>, !=

9. Left Join

LEFT JOIN keyword returns all records from the left table (Customers), even if there are no matches in the right table (Orders).

Leet Code Question: 1378. Replace Employee ID With The Unique Identifier

Write a solution to show the unique ID of each user, if a user does not have a unique ID replace just show null.

Leet Code Question: 577. Employee Bonus

Write a solution to report the name and bonus amount of each employee with a bonus less than 1000. ( But if a employee dont have empId in Bonus Table then show Bonus = NULL)

Leet Code Question: 175. Combine Two Tables

Write a solution to report the first name, last name, city, and state of each person in the Person table. If the address of a personId is not present in the Address table, report null instead.

10. Inner Join

JOIN Three Tables

The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns. If there are records in the "Orders" table that do not have matches in "Customers", these orders will not be shown!

Leet Code Question: 1068. Product Sales Analysis I

Write a solution to report the product_name, year, and price for each sale_id in the Sales table

11. GROUP BY

The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".

The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.

The following SQL statement lists the number of customers in each country, sorted high to low:

GROUP BY With JOIN Example: The following SQL statement lists the number of orders sent by each shipper:

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.

GROUP BY multiple values

1693. Daily Leads and Partners: For each date_id and make_name, find the number of distinct lead_id's and distinct partner_id's.

11. HAVING

Note: The HAVING clause was introduced because the WHERE clause does not support aggregate functions. Also, GROUP BY must be used before the HAVING clause.

The SQL HAVING clause is used if we need to filter the result set based on aggregate functions such as MIN() and MAX(), SUM() and AVG(), and COUNT().

596. Classes More Than 5 Students: Write a solution to find all the classes that have at least five students.

1084. Sales Analysis III : Write a solution to report the products that were only sold in the first quarter of 2019. That is, between 2019-01-01 and 2019-03-31 inclusive.

12. MySQL | Regular expressions (Regexp)

Weather Observation Station 6: Query the list of CITY names starting with vowels (i.e., a, e, i, o, or u) from STATION. Your result cannot contain duplicates

Match beginning of string (^): ^[aeiouAEIOU]

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

Match the end of a string ($): '[aeiouAEIOU]$'

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

[^abc]

Any character not listed between the square brackets


13. Useful Resources

197. Rising Temperature: Write a solution to find all dates' Id with higher temperatures compared to its previous dates (yesterday).

Draw A Triangle : P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5):

Write a query to print the pattern P(20).

14. MySQL SUBSTR() Function

Question: Hacker Rank - Higher Than 75 Marks

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.

15. CONCAT() , UPPER() , LOWER()

1667. Fix Names in a Table : Write a solution to fix the names so that only the first character is uppercase and the rest are lowercase.

16. IFNULL, ROUND, SUM, BETWEEN, AND

1251. Average Selling Price : Write a solution to find the average selling price for each product. average_price should be rounded to 2 decimal places.

Round the number to 2 decimal places:

Return the specified value IF the expression is NULL, otherwise return the expression: if Value == NULL return W3Schools.com else returns Value

Selects all products with a price between 10 and 20:

17. FLOOR() , CEILING()

Return the largest integer value that is equal to or less than 25.75: (Return 25)

Return the smallest integer value that is greater than or equal to a number: (Return 26)

18. SUBQUERY:

1978. Employees Whose Manager Left the Company: Find the IDs of the employees whose salary is strictly less than $30000 and whose manager left the company. When a manager leaves the company, their information is deleted from the Employees table, but the reports still have their manager_id set to the manager that left.

Find employees who earn more than the average salary of their respective departments.

List the names of customers who have placed more than 5 orders.

Percentage Between Two Table

Table: Users

Table: Register

Write a solution to find the percentage of the users registered in each contest rounded to two decimals. Return the result table ordered by percentage in descending order. In case of a tie, order it by contest_id in ascending order.

19.SQL Condition: CASE or IF

Question : The Report

Question Link : The Report

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.

Sample Input

Sample Output

Note

Print "NULL" as the name if the grade is less than 8.

Case Approach:

IF Approach:

Case Use case : 1179. Reformat Department Table

Table: Department

Reformat the table such that there is a department id column and a revenue column for each month.

Example 1:

20.SQL Alternative instead of Using Join (From, Where)

SQL Query using JOIN

To retrieve a list of employees along with their respective department names, you can use an INNER JOIN:

SQL Query using WHERE and FROM

The same result can be achieved using the WHERE clause to specify the join condition:

21. IFNULL(NULL, 0) && Order By on total distance

1407. Top Travellers: Return the result table ordered by travelled_distance in descending order, if two or more users traveled the same distance, order them by their name in ascending order.

22. UNION & UINON ALL

The UNION operator is used to combine the result-set of two or more SELECT statements.

The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL

1795. Rearrange Products Table: Write a solution to rearrange the Products table so that each row has (product_id, store, price). If a product is not available in a store, do not include a row with that product_id and store combination in the result table.

23. FULL OUTER JOIN & COALESCE()

The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or right (table2) table records.

The COALESCE() function returns the first non-null value in a list.

1965. Employees With Missing Information : Write a solution to report the IDs of all the employees with missing information. The information of an employee is missing if:

  • The employee's name is missing, or

  • The employee's salary is missing.

Return the result table ordered by employee_id in ascending order.

Last updated