Chapter 27 — Comprehensive Practice System: 300 Progressive Problems
All exercises in this practice system are designed to be executed against the master sql_mastery database schema.
To practice alongside these questions, ensure you have initialized your local database by running the script [sql_mastery_schema.sql](file:///c:/antigravity/master_sql_guide/sql_mastery_schema.sql).
NOTE
Solutions and query explanations are intentionally omitted from this chapter to enable self-testing. For verified solutions and step-by-step breakdowns, refer to [Chapter 28 — The Master Answer Key](file:///c:/antigravity/master_sql_guide/28_answer_key.md).
Section 1: Database & Table Management (DDL, Types & Constraints)
Beginner Questions (1–10)
- Write a SQL statement to display all tables inside the active
sql_masterydatabase. - Write a statement to inspect the schema definition, datatypes, and nullability of the
departmentstable. - Write a command to create a sandbox table named
test_logswith a single integer columnid. - Write a statement to drop the
test_logstable only if it exists. - Write a query to create a table
couponswithcode VARCHAR(20)anddiscount_pct DECIMAL(4,2)that defaults to0.05. - Write an
ALTER TABLEstatement adding a columnexpiry_date DATE NOT NULLto thecouponstable. - Write an
ALTER TABLEstatement modifyingcodeincouponstoVARCHAR(30) NOT NULL. - Write an
ALTER TABLEstatement dropping theexpiry_datecolumn fromcoupons. - Write a statement to rename the table
couponstopromotional_codes. - Drop the
promotional_codestable cleanly.
Intermediate Questions (11–20)
- Write a statement creating a table
project_teamswith an auto-increment primary keyteam_id, a uniqueteam_name VARCHAR(50), and a check constraint ensuringbudget >= 1000.00. - Write an
ALTER TABLEstatement adding a foreign key toproject_teamsnamedfk_team_leadpointingteam_lead_idtoemployees(employee_id)withON DELETE SET NULL. - Write a command to create an exact structural clone of the
productstable namedproducts_backupwithout copying any rows. - Write a query creating a table
high_earnerscontaining all columns and rows fromemployeeswheresalary > 120000.00usingCREATE TABLE ... AS SELECT. - Write an
ALTER TABLEstatement adding a columnpriority_level ENUM('Low', 'Medium', 'High') DEFAULT 'Medium'positioned immediately afterdepartment_nameindepartments. - Remove the
priority_levelcolumn fromdepartmentsto restore the schema. - Write a statement to truncate the
high_earnerstable. - Drop the
high_earnersandproducts_backuptables. - Write a statement to view the complete DDL
CREATE TABLEscript generated by MySQL for theorder_itemstable. - Write an
ALTER TABLEstatement adding a composite unique constraint nameduq_dept_locondepartments(department_name, location).
Advanced Questions (21–25)
- Write a script creating a temporary table
temp_sales_summarythat aggregates total units sold per product fromorder_items. Explain when MySQL purges this table. - Write an
ALTER TABLEstatement that disables foreign key checks temporarily, adds a foreign key constraint, and re-enables foreign key checks. - Write a statement that attempts to add a check constraint
salary > 200000toemployees. Explain why MySQL rejects the DDL if existing rows violate the condition. - Construct an
ALTER TABLEstatement that modifiescustomers.phonetoVARCHAR(25)using MySQL 8.0ALGORITHM=INPLACE, LOCK=NONE. - Demonstrate how to drop a primary key that has an active
AUTO_INCREMENTattribute on an InnoDB table.
Challenge Questions (26–30)
- Schema Migration Challenge: Write a multi-step migration script that splits
customers.first_nameandcustomers.last_nameinto a singlefull_name VARCHAR(100)column without losing any existing customer data, and drops the old columns. - Zero-Downtime Column Addition: Write the SQL pattern to add a non-null column with a default value to a table with 10 million rows without taking an exclusive table lock.
- Foreign Key Integrity Audit: Write a query that queries MySQL's
information_schema.table_constraintsandreferential_constraintsto list all foreign keys and their correspondingON DELETErules insql_mastery. - Storage Footprint Analysis: Write a query against
information_schema.tablescalculating the total data size and index size in Megabytes for each table insql_mastery. - Composite Key Restructuring: Convert a table with an existing composite primary key
(order_id, product_id)into a table with a surrogate primary keyitem_id INT AUTO_INCREMENTwhile preserving the composite uniqueness.
Section 2: Data Querying, Filtering & Sorting (SELECT, WHERE, ORDER BY, LIMIT)
Beginner Questions (31–40)
- Retrieve all columns for all rows from the
departmentstable. - Retrieve only
first_name,last_name, andemailfromcustomers. - Find all products with a
unit_pricestrictly greater than $500.00. - Find all customers who reside in the country
'USA'. - Find all orders that have a status of
'Delivered'. - Retrieve all products with a
unit_pricebetween $100.00 and $400.00 inclusive. - Find all customers who do not have a recorded
state(state IS NULL). - Retrieve all employees sorted by
hire_dateascending (earliest hires first). - Retrieve the top 3 highest-earning employees in the company.
- Retrieve distinct countries from the
customerstable without duplicates.
Intermediate Questions (41–50)
- Find all customers whose
emailaddress ends with'@gmail.com'. - Retrieve all products in
category_id1 or 2 that havestock_quantitygreater than 20. - Find all orders placed between
'2023-08-01'and'2023-08-15'wheretotal_amountexceeds $300.00. - Find all employees whose
salaryis greater than $90,000 and whosemanager_idis NOT NULL. - Retrieve the 5 least expensive products that are currently active (
is_active = TRUE). - Find all customers whose
first_namestarts with'M'or'S'and whose country is NOT'USA'. - Retrieve all orders with
statusof either'Processing'or'Pending', ordered byorder_datedescending. - Implement UI pagination: Retrieve rows 4 through 6 of the
productstable ordered byunit_pricedescending. - Find all products where the product name contains the word
'Air'or'Pro'. - Retrieve all customers sorted such that customers in
'USA'appear first, with all other countries sorted alphabetically below.
Advanced Questions (51–55)
- Write a query against
customersthat sorts byloyalty_pointsdescending, placing any customer withNULLloyalty points at the very bottom. - Write a query retrieving all orders where
shipping_feerepresents more than 2% of thetotal_amount. - Construct a query that searches the
productstable for products whose name has exactly 15 characters. - Using Keyset / Cursor Pagination, write a query to fetch the next page of 3 orders following
order_id = 1005without using theOFFSETkeyword. - Retrieve all employees who were hired in an odd-numbered month.
Challenge Questions (56–60)
- Deterministic Pagination Challenge: Explain why
ORDER BY order_date LIMIT 5 OFFSET 5can return duplicate rows across consecutive pages iforder_datecontains ties. Write the corrected query. - Complex Pattern Matching: Write a regular expression query (
REGEXP) againstcustomersfinding all phone numbers that do not strictly adhere to the pattern555-XXXX. - Dynamic Threshold Filtering: Write a query retrieving products where the current inventory value (
stock_quantity * unit_price) exceeds the average inventory value of all products. - Multi-Condition Search Filter: Write a query that models an e-commerce search bar: given search keyword
'Pro', filter acrossproduct_name,category_name, andsupplier_namesimultaneously. - Safe Range Scanning: Write a query filtering
ordersbyorder_datethat is guaranteed to be SARGable and index-seekable for the entire year of 2023.
Section 3: Built-in SQL Functions (String, Date, Math & Flow)
Beginner Questions (61–70)
- Concatenate
first_nameandlast_nameinto a single columnfull_namefor all employees. - Convert all supplier company names to uppercase.
- Display the length in characters of every product name.
- Round every employee's salary to the nearest thousand.
- Return the current date and time using MySQL functions.
- Extract the calendar year from the
order_dateof all orders. - Find the square root of 144 using a mathematical function.
- Replace any occurrence of
'USA'with'United States'in thecustomerstable projection. - Display each customer's phone number, displaying
'No Phone Provided'if the phone is NULL usingIFNULL(). - Calculate the absolute value of $-45.50$.
Intermediate Questions (71–80)
- Calculate the number of days elapsed between each customer's
registered_atdate and today. - Format all
order_datevalues inordersinto the human-readable format'Month Day, Year'(e.g.'August 01, 2023'). - Extract the first 3 characters of every customer's
country. - Extract the username portion (everything before the
@symbol) fromcustomers.email. - Write a query calculating a 15% promotional discount on all products, truncated (not rounded) to 2 decimal places.
- Calculate each employee's tenure in complete elapsed months using
TIMESTAMPDIFF(). - Use
CONCAT_WS()to format each customer's complete address:city, state, country. Ensure missing states do not produce double commas. - Add a 30-day payment grace period to all order dates using
DATE_ADD(). - Use an
IF()function to flag each product as'Expensive'if price > $500, or'Affordable'otherwise. - Calculate the remainder when dividing order total amounts by 10 using
MOD().
Advanced Questions (81–85)
- Use a searched
CASEexpression to classify customers into tiers:'Diamond'(points $\ge 700$),'Platinum'(points $\ge 400$),'Silver'(points $\ge 100$), and'Basic'otherwise. - Calculate the compound annual growth rate (CAGR) formula in SQL using
POWER(). - Write a query that dynamically replaces all vowels in customer first names with asterisks (
*). - Write a query to find the last day of the month for every order in
ordersusingLAST_DAY(). - Write a query that computes the total payroll, average salary, minimum salary, and maximum salary for employees, ensuring NULLs are converted to 0.
Challenge Questions (86–90)
- Working Day Calculation Challenge: Write a SQL expression that calculates the number of business days (excluding Saturdays and Sundays) between an order's
order_dateand today. - Email Obfuscation Challenge: Write a query that masks customer emails for privacy, showing only the first 2 characters and the domain (e.g., transforming
emily.watson@gmail.comintoem*****@gmail.com). - Safe Division Matrix: Write a query that calculates the ratio of
loyalty_pointsto order counts for each customer, protecting against division by zero usingNULLIF. - Fiscal Quarter Determination: Write an expression that maps each order date to an enterprise fiscal quarter, where Fiscal Year begins on November 1st.
- String Parsing Challenge: Given a comma-delimited string
'alpha,beta,gamma', extract the 2nd element ('beta') using pure SQL string functions without procedural loops.
Section 4: Grouping & Aggregation (GROUP BY & HAVING)
Beginner Questions (91–100)
- Count the total number of employees in the company.
- Find the total sum of all order amounts in
orders. - Find the average unit price across all products.
- Count how many unique countries are represented in
customers. - Find the maximum salary and minimum salary in the
employeestable. - Count the number of products belonging to each
category_id. - Calculate the total payroll expenditure for each
department_id. - Count the number of orders placed by each
customer_id. - Calculate the total quantity of items sold in
order_items. - Count the number of customers residing in each
country.
Intermediate Questions (101–110)
- Find all
department_idgroups where the average employee salary exceeds $100,000. - Find all customers who have placed 2 or more orders.
- Calculate the total revenue generated by each
statusin theorderstable. - List each
category_idthat contains more than 1 active product. - Use
GROUP_CONCATto produce a comma-separated list of employee first names for each department. - Group products by
supplier_idand display the minimum price, maximum price, and price range (max - min). - Find all order dates where more than 1 order was placed on the same day.
- Calculate the average discount given per order in
order_items, filtering to display only orders where average discount > 0. - Group customers by
countryandstate, counting how many customers reside in each combination. - Find the total amount of successful payments for each
payment_method.
Advanced Questions (111–115)
- Write a query grouping employees by
department_idwithWITH ROLLUP, calculating headcount and total salary, with a grand total row labeled'Company Total'. - Explain the cause of
ERROR 1055: only_full_group_bywhen selecting an unaggregated column inGROUP BY. Write a query demonstrating the error and fix it. - Find the department that has the highest average salary using
GROUP BY,ORDER BY, andLIMIT 1. - Find all customers whose cumulative order spending exceeds the company-wide average order value.
- Group orders by calendar month and calculate the month's total sales, shipping costs, and order count.
Challenge Questions (116–120)
- Multi-Dimensional ROLLUP Analysis: Group
productsbycategory_idandsupplier_idusingWITH ROLLUP, using theGROUPING()function to identify subtotal vs grand total rows. - Conditional Aggregation (Pivot): Write a single query that pivots the
orderstable to display total revenue in 5 separate columns:Pending,Processing,Shipped,Delivered, andCancelledusingSUM(CASE ...). - Customer Retention Metric: Group customers by the year of their registration date and calculate how many of those customers have placed an order in 2023.
- Pareto Principle Analysis (80/20 Rule): Write a query that identifies the top 20% of customers who generate 80% of total revenue.
- Aggregating Pre-Calculated Line Items: Calculate the total net revenue for every order from
order_items, accounting for discounts, and filter for orders where net revenue exceeds $1,000 usingHAVING.
Section 5: Relational JOINs & Set Operations
Beginner Questions (121–130)
- Perform an
INNER JOINbetweenemployeesanddepartmentsto display each employee's name and department name. - Perform a
LEFT JOINbetweendepartmentsandemployeesto show all departments, including those with no employees. - Join
ordersandcustomersto show order IDs and customer names. - Join
productsandcategoriesto show each product's title and category description. - Join
productsandsuppliersto display product names and supplier contact emails. - Use
UNIONto combine all distinct cities fromcustomersandsuppliers. - Use
UNION ALLto combine all cities fromcustomersandsuppliers. - Join
ordersandorder_itemsto list all item IDs belonging to each order. - Join
ordersandpaymentsto display order IDs and payment transaction references. - Perform a
CROSS JOINbetweencategoriesanddepartments.
Intermediate Questions (131–140)
- Write an Anti-Join to find all customers who have never placed an order.
- Write an Anti-Join to find all products that have never been purchased in
order_items. - Perform a
Self JOINonemployeesto display each employee's name alongside their direct manager's name. - Write a 3-table join connecting
customers,orders, andorder_itemsto list all products purchased by customer Emily Watson. - Write a query joining
products,categories, andsuppliersto list all products belonging to'Electronics'supplied by suppliers based in'Japan'. - Use
UNION ALLto combine customer phone numbers and employee phone numbers, tagging each row with an'Entity_Type'column. - Perform a
Self JOINto find all pairs of employees who work in the same department. - Join
orders,order_items, andproductsto calculate the total retail value of items inside Order 1001. - Write a query to find all departments that currently employ zero staff.
- Emulate a
FULL OUTER JOINbetweendepartmentsandemployeesusingUNION.
Advanced Questions (141–145)
- Write a 5-table join connecting
customers,orders,order_items,products, andcategoriesto calculate total revenue generated per customer per category. - Write a Non-Equi Join that finds all products whose
unit_priceis strictly greater than the average salary of employees in department 1. - Write a query using
LEFT JOINwhere the filter on the right table is placed inside theONclause, and explain how the result differs from placing it inWHERE. - Find all customers who have purchased both Product 1 AND Product 3 using relational joins.
- Combine the top 2 highest-paid employees and top 2 lowest-paid employees using
UNION ALLwith individual parenthesized subqueries.
Challenge Questions (146–150)
- Full Outer Join Emulation with Nulls: Construct a complete
FULL OUTER JOINbetweencustomersandordersthat accurately returns customers without orders AND orders without valid customers (if orphaned). - Self Join Hierarchy Tree: Write a query displaying employees, their managers, and their manager's managers (2 levels of management hierarchy) using a 3-way Self Join.
- Relational Division Challenge: Find all customers who have purchased every single product in Category 1 (
Electronics). - Basket Analysis (Co-Purchased Products): Write a self-join query on
order_itemsto identify pairs of products that are most frequently purchased together in the same order. - Consolidated Financial Audit: Write a compound query utilizing
UNION ALLto merge completed order revenue, refund deductions, and shipping costs into a chronological general ledger.
Section 6: Nested Queries & Common Table Expressions (CTEs)
Beginner Questions (151–160)
- Write a scalar subquery to find all employees earning more than the company-wide average salary.
- Write a subquery using
INto find all products that belong to categories containing the word'Appliances'. - Write a subquery to find the customer who placed the single largest order by
total_amount. - Find all products priced higher than the Quantum Pro 15 Laptop using a subquery.
- Write a query using a derived table in the
FROMclause that aliases product prices. - Find all customers who registered on the earliest registration date in the table.
- Use a subquery to find all orders placed by customers residing in
'San Francisco'. - Write a basic CTE named
ActiveProductsthat selects active products, and query from it. - Find all employees who share a manager with employee David Kim using a subquery.
- Use
NOT INwith a subquery to find products that have never been ordered.
Intermediate Questions (161–170)
- Write a Correlated Subquery that finds all employees earning more than the average salary of their own department.
- Write a query using
EXISTSto find all suppliers that supply at least one active product. - Write a query using
NOT EXISTSto find all customers who have never placed an order. - Write a CTE that calculates total spending per customer, and query the CTE to find customers who spent over $1,000.
- Write a query using
ALLto find products whose price is greater than the price of all products in Category 3. - Write a query using
ANYto find employees whose salary is greater than the salary of any employee in Department 4. - Write a subquery in the
SELECTprojection list that displays each employee's salary alongside the company maximum salary. - Write a modular query with two chained CTEs:
CustomerOrdersandOrderTotals, calculating average order size per customer. - Find all customers who have placed an order in both August 2023 and September 2023 using subqueries.
- Write a correlated subquery that displays the most recent order date for every customer.
Advanced Questions (171–175)
- Write a Recursive CTE that generates an integer sequence from 1 to 20.
- Write a Recursive CTE that models the entire organizational management tree from the CEO down to individual staff members, computing the hierarchy level depth.
- Write a correlated subquery that finds the top 1 highest-priced product within every category.
- Write a query using a CTE that calculates the percentage of total company revenue contributed by each customer.
- Rewrite a deeply nested subquery into a linear 3-stage Common Table Expression.
Challenge Questions (176–180)
- Recursive Date Series Generator: Write a Recursive CTE generating all calendar dates for the month of August 2023, performing a
LEFT JOINagainstordersto count orders per day (showing 0 on empty days). - BOM (Bill of Materials) Traversal: Design a recursive CTE query that calculates the total component manufacturing cost for a hierarchical assembly.
- Correlated Subquery Optimization: Take a slow correlated subquery calculating running balances and rewrite it into an optimized join with a derived table.
- Detecting Circular Management References: Write a query utilizing a Recursive CTE that traverses manager hierarchies and detects if an employee accidentally reports to themselves through a loop.
- Cumulative Tier Classification: Write a CTE calculating customer percentiles and dynamically tag the top 10% of customers as
'Key Accounts'.
Section 7: Database Design, Normalization & Views
Beginner Questions (181–190)
- What normal form is violated if a column stores multiple phone numbers separated by commas?
- What normal form requires the elimination of partial dependencies on composite keys?
- What normal form requires the elimination of transitive dependencies?
- Create a view named
v_all_productsthat displays product titles, category names, and prices. - Query the
v_all_productsview for products under $300.00. - Create a view named
v_active_employeesshowing only active employees. - Show how to inspect the definition of an existing view in MySQL.
- Drop the view
v_all_products. - Explain whether a view consumes physical disk storage for table rows.
- What happens to a view if you rename one of the underlying base table columns?
Intermediate Questions (191–200)
- Create an updatable view
v_german_customersfiltering forcountry = 'Germany'. - Add
WITH CHECK OPTIONtov_german_customersand demonstrate how it blocks inserting an Italian customer. - Create a security view
v_employee_directorythat masks employee salaries and personal phone numbers. - Create an analytical view
v_monthly_sales_summarythat aggregates revenue, order count, and average order value by month. - Normalize an unnormalized relation
R(OrderID, CustomerName, CustomerAddress, ProductID, ProductName, Quantity)into 3NF tables. - Identify the functional dependencies in
courses(course_id, course_code, instructor_id, instructor_office). - Explain why storing
total_amountin theorderstable is a controlled denormalization decision. - Demonstrate updating an employee's salary through an updatable view.
- Explain why a view containing
GROUP BYcannot be updated directly. - Create a view joining 4 tables to produce a customer order invoice summary.
Advanced Questions (201–205)
- Emulate a Materialized View in MySQL using a physical summary table and a scheduled event.
- Design a 3NF schema for a Car Rental Agency (Customers, Vehicles, Rentals, Maintenance Logs).
- Explain Boyce-Codd Normal Form (BCNF) with a concrete schema example where 3NF is satisfied but BCNF is violated.
- Create a view using
ALGORITHM = MERGEand explain how MySQL combines the view query with the outer user query. - Create a view using
ALGORITHM = TEMPTABLEand analyze its execution plan usingEXPLAIN.
Challenge Questions (206–210)
- Zero-Loss Normalization Decomposition: Decompose relation $R(A, B, C, D, E)$ with functional dependencies $A \rightarrow B, C$, $C \rightarrow D$, and $D \rightarrow E$ into 3NF, proving lossless join property.
- Security View with Row-Level Tenant Isolation: Create a security view that utilizes MySQL's
SESSION_USER()orCURRENT_USER()to restrict users so they can only view records belonging to their own department. - Materialized View Refresh Mechanism: Write a stored procedure and trigger architecture that incrementally maintains a materialized view table when new rows are inserted into
order_items. - Denormalization Trade-off Audit: Calculate the exact byte storage difference between a normalized 3NF schema vs a denormalized Star Schema for 10 million transactions.
- Schema Anti-Pattern Refactor: Take an existing Entity-Attribute-Value (EAV) schema anti-pattern and refactor it into a hybrid relational + JSON document design.
Section 8: Indexes, Transactions & Concurrency Control
Beginner Questions (211–220)
- Write a statement to create an index named
idx_cust_emailoncustomers(email). - Write a statement to drop the index
idx_cust_email. - Show all indexes currently defined on the
orderstable. - What command begins an explicit transaction in MySQL?
- What command commits all pending transactional changes to disk?
- What command rolls back uncommitted changes?
- What is the default transaction isolation level in MySQL InnoDB?
- What is a Clustered Index, and which column represents it in
customers? - Explain what the acronym ACID stands for.
- What is a savepoint, and how do you create one?
Intermediate Questions (221–230)
- Create a composite index on
orders(customer_id, order_date). - Write a query that utilizes the composite index from Question 221 obeying the Leftmost Prefix Rule.
- Write a query that fails to utilize the composite index from Question 221 due to violating the Leftmost Prefix Rule.
- Write a transaction that decrements stock for Product 1 and creates an order. Roll back if stock is insufficient.
- Demonstrate how
SET autocommit = 0;alters transaction persistence in a CLI session. - Use
SELECT ... FOR UPDATEto lock a product record during an inventory verification query. - Use
SELECT ... FOR SHAREto lock a customer record for read-only validation. - Explain the concurrency anomaly known as a "Dirty Read" and state which isolation level permits it.
- Explain what a "Non-Repeatable Read" is and how
REPEATABLE READprevents it. - Explain what a "Phantom Read" is and how InnoDB's Next-Key Locking prevents it.
Advanced Questions (231–235)
- Demonstrate an index-covering query on
employeesusingEXPLAINshowingUsing indexin theExtracolumn. - Simulate a deadlock scenario between two concurrent connections in MySQL.
- Write a transaction utilizing
SAVEPOINTto partially roll back an order item insert while keeping the parent order. - Explain how InnoDB's Multi-Version Concurrency Control (MVCC) allows readers to avoid blocking writers.
- Inspect active transaction locks using MySQL's
performance_schema.data_lockstable.
Challenge Questions (236–240)
- Deadlock Resolution Routine: Write an application-level retry algorithm (in pseudocode or SQL handler) that intercepts MySQL error 1213 (Deadlock found) and retries the transaction.
- Covering Index Optimization Challenge: Design the optimal composite index to accelerate this query to sub-millisecond speeds:
SELECT customer_id, order_date, total_amount FROM orders WHERE status = 'Delivered' ORDER BY order_date DESC LIMIT 10;- Index Cardinality Analysis: Write a query that computes the selectivity ratio of all indexes on
customersto determine which indexes should be dropped. - Implicit Commit Disaster Recovery: Construct a scenario demonstrating how running an
ALTER TABLEinside a transaction commits prior DML statements and breaks atomicity. - InnoDB Lock Escalation Mechanics: Explain why InnoDB uses row-level locking instead of table-level locking, and when row locks can escalate or lock entire ranges via Gap Locks.
Section 9: Programmability & Advanced Analytics (Procedures, Functions, Triggers, Windows)
Beginner Questions (241–250)
- Write a basic stored procedure
sp_list_departmentsthat selects all departments. - Write the command to execute the
sp_list_departmentsprocedure. - Why must the
DELIMITERbe changed when creating stored routines in the MySQL CLI? - Create a deterministic function
fn_add_numbers(a INT, b INT)that returns their sum. - Write a
BEFORE INSERTtrigger onemployeesthat forcesemailto lowercase. - Use the
ROW_NUMBER()window function to number all employees ordered by salary descending. - Extract a JSON value from
'{"brand": "Sony", "model": "XM4"}'using the->>operator. - Show how to drop a stored procedure named
sp_my_proc. - Explain the difference between an
INparameter and anOUTparameter in a procedure. - Which pseudo-record (
OLDorNEW) is available in aDELETEtrigger?
Intermediate Questions (251–260)
- Write a procedure
sp_get_customer_spendtaking anIN p_cust_id INTand returning their total spend as anOUT p_total DECIMAL(12,2). - Write a stored function
fn_discounted_price(price DECIMAL(10,2), pct DECIMAL(4,2))returning the net price. - Write an
AFTER DELETEtrigger onordersthat logs the deletedorder_idandtotal_amountto anorders_archivetable. - Use
RANK()andDENSE_RANK()side-by-side to rank products by price within their category. - Use
LAG()to calculate the difference in salary between each employee and the next lower-paid employee in their department. - Use
LEAD()to display the subsequent order date for each customer inorders. - Write a procedure with an
IF-THEN-ELSEcontrol flow that updates employee salaries based on performance ratings. - Write a function that counts how many orders a given customer has placed.
- Write an
AFTER UPDATEtrigger that prevents modifying an order'stotal_amountonce its status is'Delivered'. - Calculate a running cumulative total of order amounts sorted by
order_dateusing a window function.
Advanced Questions (261–265)
- Write a stored procedure utilizing a
CURSORand aCONTINUE HANDLER FOR NOT FOUNDto iterate through all active customers and award 50 bonus points. - Write a 3-day moving average calculation on daily order revenue using
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW. - Use
NTILE(4)to divide customers into 4 equal quartiles based on their lifetime spend. - Construct a table with a native
JSONcolumn and build an indexed virtual generated column extracting a nested string attribute. - Write an
EXIT HANDLER FOR SQLEXCEPTIONinside a stored procedure that automatically rolls back an open transaction on error.
Challenge Questions (266–270)
- Dynamic Pivot Procedure: Write a stored procedure that dynamically constructs an SQL string using
GROUP_CONCATto pivot sales data across arbitrary years into columns and executes it viaPREPAREandEXECUTE. - Year-over-Year (YoY) Growth Window Pipeline: Write a single SQL query using window functions that calculates monthly revenue, previous year same-month revenue (
LAG 12), and the YoY percentage growth rate. - Strict Invariant Trigger Guard: Write a
BEFORE UPDATEtrigger onorder_itemsthat recalculates the parent order'stotal_amountinordersand rejects the update if the customer's credit limit would be exceeded. - Advanced JSON Array Aggregation: Query the
productstable and useJSON_ARRAYAGGandJSON_OBJECTto produce a single hierarchical JSON document containing each category and its nested array of products. - Audit Trigger with Deep Diffing: Write an
AFTER UPDATEtrigger onemployeesthat compares every single column betweenOLDandNEWand inserts a separate log entry for each modified attribute into a normalizedfield_changes_audittable.
Section 10: Performance Optimization & Enterprise Security
Beginner Questions (271–280)
- Write a command to generate an
EXPLAINexecution plan for a query oncustomers. - What access type in
EXPLAINindicates a full table scan? - What access type in
EXPLAINindicates a lookup using a Primary Key? - Create a MySQL user account named
'intern'@'localhost'with password'InternPass2026!'. - Grant read-only (
SELECT) privileges onsql_mastery.*to'intern'@'localhost'. - Inspect the active privileges granted to
'intern'@'localhost'. - Revoke
SELECTprivileges from'intern'@'localhost'. - Drop the user
'intern'@'localhost'. - What does the term SARGable mean in query optimization?
- Explain why string concatenation in web queries causes SQL Injection vulnerabilities.
Intermediate Questions (281–290)
- Convert this non-SARGable query into a SARGable query:
SELECT * FROM employees WHERE YEAR(hire_date) = 2021;- Convert this non-SARGable query into a SARGable query:
SELECT * FROM customers WHERE phone LIKE '555%';- Use
EXPLAIN ANALYZEto measure the actual execution time of a join betweencustomersandorders. - Create a role named
'analyst_role', grant itSELECTon all tables insql_mastery, and assign the role to a user. - Grant column-level permissions allowing a user to view only
first_name,last_name, andcityfromcustomers. - Show how to prepare and execute a parameterized query in MySQL using
PREPARE,SET, andEXECUTE. - Explain what
Using temporaryandUsing filesortmean in theExtracolumn of anEXPLAINplan. - Write the
mysqldumpcommand to back upsql_masteryusing--single-transaction. - Identify the performance risk of comparing a
VARCHARcolumn to an integer literal (WHERE phone = 5550100). - Enable the Slow Query Log in MySQL and configure it to capture queries running longer than 1.0 second.
Advanced Questions (291–295)
- Analyze an
EXPLAINplan showing a Block Nested Loop (or Hash Join) and construct the index needed to convert it into an Index Nested Loop Join. - Design a multi-column covering index that completely eliminates a Filesort on a query containing both a
WHEREfilter and anORDER BYclause. - Explain the security differences between
caching_sha2_passwordandmysql_native_passwordin MySQL 8.0. - Write an SQL statement using
sys.schema_unused_indexesto identify indexes insql_masterythat have never been utilized by queries. - Configure a user account to require an encrypted SSL/TLS connection (
REQUIRE SSL).
Challenge Questions (296–300)
- Execution Plan Deconstruction: Execute
EXPLAIN FORMAT=JSONon a 4-table join query and interpret the cost metrics (query_cost,read_cost,eval_cost). - SQL Injection Penetration Scenario: Demonstrate how an attacker bypasses authentication when a login query is written as:
SELECT * FROM users WHERE username = '$user' AND password = '$password';Show the exact injection payload and write the secure parameterized prepared statement equivalent. 298. Buffer Pool Sizing & Hit Ratio: Write a query against information_schema and performance_schema that calculates the InnoDB Buffer Pool Read Hit Ratio percentage. 299. Granular Row-Level Access Architecture: Design a multi-tenant security architecture in MySQL where multiple client companies share a single database, but database-level roles and views ensure Tenant A can never query Tenant B's data. 300. High-Performance Query Refactoring: Take a legacy reporting query containing 4 subqueries, 2 self-joins, and a DISTINCT clause, and refactor it into an optimized pipeline using Common Table Expressions and Window Functions, reducing query cost by over 80%.