The most asked MySQL interview questions with structured answers — a quick answer, a clear explanation and working code for each. Covers basics for freshers through advanced, scenario and coding questions for experienced developers.
Updated November 2026 Reviewed by Abhishek Kumar 120 min read
100 MySQL interview questions, grouped by level: freshers, intermediate, experienced and coding.
Every answer starts with a one-line “Quick answer” you can say out loud, followed by the explanation and runnable code.
Use the filter bar to practise only the level you are interviewing for, then test yourself with the free MySQL quiz.
What is MySQL, and why do interviewers ask about it?
MySQL is the world's most popular open‑source relational database management system. This page compiles the most frequently asked MySQL interview questions – from basic CRUD operations and data types to advanced topics like indexing, transactions, stored procedures, window functions, replication, and performance optimisation – essential for any backend developer, DBA, or data engineer.
Why companies hire for MySQL
Open‑source and free – zero licensing cost
High performance – optimised for read‑heavy workloads
ACID compliant – strong transaction support
Scalable – from small apps to large enterprise systems
Rich ecosystem – tools, drivers, and community support
Excellent security features – authentication, encryption, and auditing
100 shown
Basic MySQL Interview Questions for Freshers
12 questions
Start here if you are a fresher or switching to MySQL. These fundamentals are asked in almost every first-round and campus interview.
1
How interviewers ask it“Let's start with the basics — how would you explain MySQL?”
Quick answerMySQL functions are stored routines that return a single value. They can be used in SQL statements.
CREATE FUNCTION: CREATE FUNCTION name(params) RETURNS type
DETERMINISTIC: Returns same result for same inputs
READS SQL DATA: Indicates data reading
Return value: Must return a value
Usage: SELECT function_name()
SQL
-- Functions in MySQL-- Basic function
DELIMITER //CREATEFUNCTION add_numbers(a INT, b INT)
RETURNSINTDETERMINISTICBEGINRETURN a + b;
END//
DELIMITER ;
-- Function with default parameters
DELIMITER //CREATEFUNCTION greet(name VARCHAR(100))
RETURNSVARCHAR(200)
DETERMINISTICBEGIN
IF name ISNULLTHENSET name ='Guest';
END IF;
RETURN CONCAT('Hello, ', name, '!');
END//
DELIMITER ;
-- Function with multiple statements
DELIMITER //CREATEFUNCTION divide_numbers(a INT, b INT)
RETURNSVARCHAR(100)
DETERMINISTICBEGINDECLAREresultVARCHAR(100);
IF b =0THENSETresult='Division by zero';
ELSESETresult= CONCAT('Quotient: ', a DIV b, ', Remainder: ', a MOD b);
END IF;
RETURNresult;
END//
DELIMITER ;
-- UsageSELECT add_numbers(5, 3);
SELECT greet('Alice');
SELECT divide_numbers(10, 3);
Quick answerMySQL doesn't have built-in arrays. Alternatives include JSON arrays, temporary tables, or using multiple columns.
JSON arrays: JSON_ARRAY(), JSON_EXTRACT()
Temporary tables: Session-specific tables
Separate tables: Normalized relationships
JSON functions: JSON_LENGTH(), JSON_CONTAINS()
Full-text search: For text arrays
SQL
-- Arrays in MySQL-- MySQL doesn't have arrays, but we can use JSON or temporary tables-- Using JSON arraysCREATE TABLE json_demo (
id INTPRIMARY KEY,
numbers JSON
);
INSERT INTO json_demo VALUES (1, '[1, 2, 3, 4, 5]');
INSERT INTO json_demo VALUES (2, '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]');
-- Access array elementsSELECT
id,
JSON_EXTRACT(numbers, '$[2]') AS third_element,
JSON_LENGTH(numbers) AS array_length
FROM json_demo;
-- Using temporary table as arrayCREATE TEMPORARY TABLE temp_array (
id INT AUTO_INCREMENT PRIMARY KEY,
valueINT
);
INSERT INTO temp_array (value) VALUES (1), (2), (3), (4), (5);
-- Iterate through arraySELECTvalueFROM temp_array ORDERBY id;
-- JSON array functionsSELECTJSON_ARRAY(1, 2, 3, 4, 5) AS numbers,
JSON_ARRAY_APPEND('[1,2,3]', '$', 4) AS appended,
JSON_ARRAY_INSERT('[1,2,3]', '$[1]', 99) AS inserted,
JSON_REMOVE('[1,2,3,4]', '$[2]') AS removed;
Quick answerMySQL uses tables as collections. Rows are documents/records, and columns are fields.
Tables: Collection of rows
Rows: Individual records
Columns: Fields/attributes
JSON collections: JSON data type for flexible schemas
Views: Virtual collections
SQL
-- Collections in MySQL-- Tables as collectionsCREATE TABLE users (
id INTPRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
age INT,
city VARCHAR(100)
);
-- Insert documents (rows)INSERT INTO users (name, age, city) VALUES
('Alice', 25, 'NYC'),
('Bob', 30, 'LA'),
('Charlie', 35, 'Chicago');
-- Query allSELECT*FROM users;
-- Query with filterSELECT*FROM users WHERE age >25;
-- UpdateUPDATE users SET age =26WHERE name ='Alice';
-- DeleteDELETEFROM users WHERE name ='Bob';
-- CountSELECTCOUNT(*) FROM users WHERE age >25;
-- JSON collectionsCREATE TABLE orders (
id INTPRIMARY KEY AUTO_INCREMENT,
customer_id INT,
items JSON,
total DECIMAL(10,2)
);
INSERT INTO orders (customer_id, items, total) VALUES
(1, '[{"product": "A", "qty": 2}, {"product": "B", "qty": 1}]', 30.00);
SELECT
id,
JSON_EXTRACT(items, '$[0].product') AS first_product
FROM orders;
-- Data Classes (Tables as Objects)-- Creating a table as a data classCREATE TABLE person (
id INTPRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
age INTCHECK (age >=0),
city VARCHAR(100) DEFAULT'Unknown',
created_at TIMESTAMPDEFAULTCURRENT_TIMESTAMP,
updated_at TIMESTAMPDEFAULTCURRENT_TIMESTAMPONUPDATECURRENT_TIMESTAMP
);
-- Insert dataINSERT INTO person (name, age, city) VALUES
('Alice', 25, 'NYC'),
('Bob', 30, 'LA');
-- QuerySELECT*FROM person WHERE id =1;
-- UpdateUPDATE person SET age =26WHERE id =1;
-- DeleteDELETEFROM person WHERE id =2;
-- CopyCREATE TABLE person_backup ASSELECT*FROM person;
-- Struct-like viewsCREATEVIEW person_view ASSELECT
id,
name,
age,
city,
CONCAT(name, ' (', age, ')') AS display_name
FROM person;
Quick answerMySQL provides IF, CASE, WHILE, REPEAT, and LOOP statements for control flow in stored procedures.
IF: Conditional execution
CASE: Switch-like conditional
WHILE: Loop with condition
REPEAT: Loop with until condition
LOOP: Infinite loop with LEAVE
SQL
-- Control Flow in MySQL-- IF statement in stored procedures
DELIMITER //CREATEPROCEDURE check_age(IN age INT)
BEGIN
IF age <18THENSELECT'Minor'AS status;
ELSESELECT'Adult'AS status;
END IF;
END//
DELIMITER ;
-- IF function (in SELECT)SELECT
name,
age,
IF(age <18, 'Minor', 'Adult') AS status
FROM users;
-- CASE expressionSELECT
name,
age,
CASEWHEN age <18THEN'Minor'WHEN age <65THEN'Adult'ELSE'Senior'ENDAS category
FROM users;
-- CASE with simple valuesSELECT
name,
status,
CASE status
WHEN'active'THEN'Active'WHEN'inactive'THEN'Inactive'ELSE'Unknown'ENDAS status_description
FROM users;
-- WHILE loop
DELIMITER //CREATEPROCEDURE while_demo()
BEGINDECLARE i INTDEFAULT1;
WHILE i <=5 DO
SELECT i;
SET i = i +1;
END WHILE;
END//
DELIMITER ;
-- REPEAT loop
DELIMITER //CREATEPROCEDURE repeat_demo()
BEGINDECLARE i INTDEFAULT1;
REPEAT
SELECT i;
SET i = i +1;
UNTIL i >5END REPEAT;
END//
DELIMITER ;
-- LOOP with LEAVE
DELIMITER //CREATEPROCEDURE loop_demo()
BEGINDECLARE i INTDEFAULT1;
loop_label: LOOP
SELECT i;
SET i = i +1;
IF i >5THEN
LEAVE loop_label;
END IF;
END LOOP;
END//
DELIMITER ;
Quick answerMySQL doesn't support inheritance directly. Patterns like Single Table Inheritance, Class Table Inheritance, and Polymorphic Associations are used.
Single Table Inheritance: One table with type column
Class Table Inheritance: Separate tables with foreign keys
Concrete Table Inheritance: Separate tables for each type
Polymorphic Associations: Type and ID columns
Views: Combine inherited data
SQL
-- Inheritance in MySQL-- MySQL doesn't support inheritance, but patterns exist-- Single Table InheritanceCREATE TABLE animals (
id INTPRIMARY KEY AUTO_INCREMENT,
type VARCHAR(50),
name VARCHAR(100),
sound VARCHAR(100),
breed VARCHAR(100), -- For dogs
color VARCHAR(50) -- For cats
);
INSERT INTO animals (type, name, sound, breed) VALUES
('Dog', 'Rex', 'Woof!', 'German Shepherd');
INSERT INTO animals (type, name, sound, color) VALUES
('Cat', 'Whiskers', 'Meow!', 'Black');
-- Class Table InheritanceCREATE TABLE persons (
id INTPRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(255)
);
CREATE TABLE employees (
person_id INTPRIMARY KEY,
employee_id VARCHAR(50),
department VARCHAR(100),
FOREIGN KEY (person_id) REFERENCES persons(id)
);
CREATE TABLE customers (
person_id INTPRIMARY KEY,
customer_id VARCHAR(50),
loyalty_points INT,
FOREIGN KEY (person_id) REFERENCES persons(id)
);
-- Concrete Table InheritanceCREATE TABLE employees_detail (
id INTPRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
employee_id VARCHAR(50),
department VARCHAR(100)
);
CREATE TABLE customers_detail (
id INTPRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
customer_id VARCHAR(50),
loyalty_points INT
);
-- Polymorphic associationsCREATE TABLE comments (
id INTPRIMARY KEY AUTO_INCREMENT,
content TEXT,
commentable_type VARCHAR(50),
commentable_id INT
);
Quick answerMySQL handles exceptions using DECLARE ... HANDLER statements, SIGNAL for custom errors, and GET DIAGNOSTICS for error details.
DECLARE HANDLER: Handle specific errors
SIGNAL: Raise custom errors
GET DIAGNOSTICS: Get error details
EXIT HANDLER: Exit on error
CONTINUE HANDLER: Continue after error
SQL
-- Exception Handling in MySQL-- MySQL 5.5+: DECLARE ... HANDLER-- Basic exception handling
DELIMITER //CREATEPROCEDURE safe_divide(
IN numerator INT,
IN denominator INT
)
BEGINDECLARE EXIT HANDLER FORSQLEXCEPTIONBEGINSELECT'Error occurred'ASresult;
END;
SELECT numerator / denominator ASresult;
END//
DELIMITER ;
-- Specific error handling
DELIMITER //CREATEPROCEDURE safe_insert(
IN name VARCHAR(100),
IN email VARCHAR(255)
)
BEGINDECLARE EXIT HANDLER FOR1062-- Duplicate entry errorBEGINSELECT'Email already exists'AS error;
END;
INSERT INTO users (name, email) VALUES (name, email);
SELECT'User inserted successfully'ASresult;
END//
DELIMITER ;
-- Custom error messages
DELIMITER //CREATEPROCEDURE validate_age(
IN age INT
)
BEGIN
IF age <0OR age >150THEN
SIGNAL SQLSTATE'45000'SET MESSAGE_TEXT ='Invalid age: Age must be between 0 and 150';
END IF;
SELECT'Age is valid'ASresult;
END//
DELIMITER ;
-- Using GET DIAGNOSTICS (MySQL 5.6+)
DELIMITER //CREATEPROCEDURE get_error_info()
BEGINDECLARE EXIT HANDLER FORSQLEXCEPTIONBEGINGET DIAGNOSTICS CONDITION1@sqlstate= RETURNED_SQLSTATE,
@errno= MYSQL_ERRNO,
@text= MESSAGE_TEXT;
SELECT@sqlstate, @errno, @text;
END;
-- This will cause an errorINSERT INTO nonexistent_table VALUES (1);
END//
DELIMITER ;
Quick answerWindow functions perform calculations across a set of rows related to the current row. Available in MySQL 8.0+.
ROW_NUMBER: Sequential row number
RANK: Rank with gaps
DENSE_RANK: Rank without gaps
LAG/LEAD: Previous/next row values
SUM/AVG: Aggregate with window
SQL
-- Window Functions in MySQL (8.0+)-- Window functions for advanced analytics-- ROW_NUMBERSELECT
name,
age,
city,
ROW_NUMBER() OVER (PARTITIONBY city ORDERBY age) AS row_num
FROM users;
-- RANK and DENSE_RANKSELECT
name,
salary,
RANK() OVER (ORDERBY salary DESC) AS rank_position,
DENSE_RANK() OVER (ORDERBY salary DESC) AS dense_rank_position
FROM employees;
-- LAG and LEADSELECTdate,
amount,
LAG(amount, 1) OVER (ORDERBYdate) AS previous_amount,
LEAD(amount, 1) OVER (ORDERBYdate) AS next_amount
FROM sales;
-- NTILESELECT
name,
salary,
NTILE(4) OVER (ORDERBY salary DESC) AS quartile
FROM employees;
-- SUM with windowSELECT
name,
salary,
SUM(salary) OVER (ORDERBY salary) AS cumulative_salary
FROM employees;
-- Moving averageSELECTdate,
amount,
AVG(amount) OVER (ORDERBYdateROWSBETWEEN2 PRECEDING ANDCURRENTROW) AS moving_avg_3
FROM sales;
-- FIRST_VALUE and LAST_VALUESELECT
name,
department,
salary,
FIRST_VALUE(name) OVER (PARTITIONBY department ORDERBY salary DESC) AS highest_paid,
LAST_VALUE(name) OVER (PARTITIONBY department ORDERBY salary DESCROWSBETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lowest_paid
FROM employees;
Quick answerCommon Table Expressions (CTEs) are temporary result sets that can be referenced within a query. Available in MySQL 8.0+.
WITH: Define CTE
Recursive CTE: Self-referencing CTE
Multiple CTEs: Define multiple in one query
Reference: Use CTE name in query
Hierarchical queries: Recursive for tree structures
SQL
-- Common Table Expressions (CTE) in MySQL-- CTE for complex queries-- Simple CTEWITH user_stats AS (
SELECT
city,
COUNT(*) AS user_count,
AVG(age) AS avg_age
FROM users
GROUPBY city
)
SELECT*FROM user_stats WHERE user_count >5;
-- Recursive CTE (MySQL 8.0+)WITHRECURSIVE numbers (n) AS (
SELECT1-- AnchorUNIONALLSELECT n +1-- RecursiveFROM numbers
WHERE n <10
)
SELECT*FROM numbers;
-- Recursive CTE for hierarchical dataCREATE TABLE employees (
id INTPRIMARY KEY,
name VARCHAR(100),
manager_id INT
);
INSERT INTO employees VALUES
(1, 'CEO', NULL),
(2, 'VP', 1),
(3, 'Manager', 2),
(4, 'Developer', 3),
(5, 'Developer', 3);
WITHRECURSIVE org_chart AS (
SELECT
id,
name,
manager_id,
0AS level
FROM employees
WHERE manager_id ISNULLUNIONALLSELECT
e.id,
e.name,
e.manager_id,
oc.level +1FROM employees e
INNERJOIN org_chart oc ON e.manager_id = oc.id
)
SELECT
CONCAT(REPEAT(' ', level), name) AS org_chart
FROM org_chart
ORDERBY level, id;
-- Multiple CTEsWITH
stats AS (
SELECT
city,
COUNT(*) AS count,
AVG(age) AS avg_age
FROM users
GROUPBY city
),
ranked AS (
SELECT
city,
count,
avg_age,
RANK() OVER (ORDERBY count DESC) AS rank_position
FROM stats
)
SELECT*FROM ranked WHERE rank_position <=5;
Quick answerViews are virtual tables based on a SELECT query. They provide a way to simplify complex queries and enforce security.
CREATE VIEW: Define view
Updatable views: Views that allow DML operations
WITH CHECK OPTION: Enforce view conditions
Algorithm: MERGE, TEMPTABLE, UNDEFINED
Drop view: DROP VIEW
SQL
-- Views in MySQL-- Views are virtual tables-- Create simple viewCREATEVIEW active_users ASSELECT id, name, email, age
FROM users
WHERE status ='active';
-- Create view with JOINCREATEVIEW user_orders ASSELECT
u.id AS user_id,
u.name AS user_name,
o.id AS order_id,
o.total AS order_total,
o.created_at AS order_date
FROM users u
INNERJOIN orders o ON u.id = o.user_id;
-- Create view with aggregationCREATEVIEW city_stats ASSELECT
city,
COUNT(*) AS user_count,
AVG(age) AS avg_age,
MIN(age) AS min_age,
MAX(age) AS max_age
FROM users
GROUPBY city;
-- Create view with algorithmCREATE ALGORITHM =MERGEVIEW user_names ASSELECT id, CONCAT(first_name, ' ', last_name) AS full_name
FROM users;
-- Create view with check optionCREATEVIEW ny_users ASSELECT*FROM users WHERE city ='NYC'WITHCHECK OPTION;
-- Update data through viewUPDATE active_users SET age =26WHERE id =1;
-- Drop viewDROPVIEW IF EXISTS active_users;
-- Show create viewSHOWCREATEVIEW user_orders;
-- Information about viewsSELECT*FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_SCHEMA ='database_name';
Quick answerIndexes improve query performance by allowing faster data retrieval. They are created on columns used in WHERE, JOIN, and ORDER BY clauses.
CREATE INDEX: Create index
UNIQUE INDEX: Enforce uniqueness
Composite index: Multiple columns
FULLTEXT index: Full-text search
SPATIAL index: Geospatial data
SQL
-- Indexes in MySQL-- Index types and usage-- CREATE INDEXCREATE INDEX idx_users_name ON users(name);
-- CREATE UNIQUE INDEXCREATEUNIQUE INDEX idx_users_email ON users(email);
-- CREATE COMPOSITE INDEXCREATE INDEX idx_users_city_age ON users(city, age);
-- CREATE FULLTEXT INDEXCREATE FULLTEXT INDEX idx_posts_content ON posts(content);
-- CREATE SPATIAL INDEXCREATE SPATIAL INDEX idx_locations_coords ON locations(coordinates);
-- CREATE INDEX WITH DESCCREATE INDEX idx_users_name_desc ON users(name DESC);
-- Index on prefixCREATE INDEX idx_users_name_prefix ON users(name(10));
-- DROP INDEXDROP INDEX idx_users_name ON users;
-- Show indexesSHOW INDEX FROM users;
-- Analyze table for index usage
ANALYZE TABLE users;
-- Optimize table
OPTIMIZE TABLE users;
-- Index usage with EXPLAIN
EXPLAIN SELECT*FROM users WHERE name ='Alice';
-- Invisible index (MySQL 8.0+)CREATE INDEX idx_invisible ON users(name) INVISIBLE;
-- Visible/invisible toggleALTER TABLE users ALTER INDEX idx_invisible VISIBLE;
ALTER TABLE users ALTER INDEX idx_invisible INVISIBLE;
Quick answerStored procedures and functions are both stored routines, but they have different purposes and characteristics.
Procedures: Can modify data, multiple parameters
Functions: Return single value, called in SELECT
Procedures: Can have OUT/INOUT parameters
Functions: Must be deterministic for replication
Procedures: Called with CALL, not in expressions
SQL
-- Stored Procedures vs Functions-- Comparison and examples-- Stored Procedure (can modify data)
DELIMITER //CREATEPROCEDURE update_user_age(
IN user_id INT,
IN new_age INT
)
BEGINUPDATE users SET age = new_age WHERE id = user_id;
SELECT ROW_COUNT() AS rows_affected;
END//
DELIMITER ;
-- Function (must be deterministic, cannot modify data)
DELIMITER //CREATEFUNCTION get_user_age(user_id INT)
RETURNSINTDETERMINISTICREADSSQL DATA
BEGINDECLARE user_age INT;
SELECT age INTO user_age FROM users WHERE id = user_id;
RETURN user_age;
END//
DELIMITER ;
-- Procedure with multiple outputs
DELIMITER //CREATEPROCEDURE get_user_stats(
IN user_id INT,
OUT user_name VARCHAR(100),
OUT user_age INT,
OUT user_city VARCHAR(100)
)
BEGINSELECT name, age, city
INTO user_name, user_age, user_city
FROM users
WHERE id = user_id;
END//
DELIMITER ;
-- Calling proceduresCALL update_user_age(1, 26);
CALL get_user_stats(1, @name, @age, @city);
SELECT@name, @age, @city;
-- Using functionsSELECT get_user_age(1) AS age;
Quick answerUser-defined variables are session-specific variables that can store values for use in statements and queries.
@variable: Session scope
SET: Assign value
SELECT INTO: Assign from query
SQL statements: Use in any statement
Limitations: Session only, no persistence
SQL
-- User-Defined Variables in MySQL-- Session-level variables-- Set variablesSET@var1=10;
SET@var2 :=20; -- Alternative syntaxSELECT@var3 :=30; -- Set from SELECT-- Use variables in queriesSET@min_age=18;
SET@max_age=30;
SELECT*FROM users WHERE age BETWEEN@min_ageAND@max_age;
-- Variables from SELECTSELECTCOUNT(*) INTO@user_countFROM users;
SELECT@user_count;
-- Multiple variablesSELECT name, age INTO@name, @ageFROM users WHERE id =1;
SELECT@name, @age;
-- Variables in LIMITSET@offset=0;
SET@limit=10;
PREPARE stmt FROM'SELECT * FROM users LIMIT ?, ?';
EXECUTE stmt USING@offset, @limit;
-- Session vs global variablesSET SESSION sort_buffer_size =1024;
SETGLOBAL max_connections =1000;
-- System variablesSELECT @@global.max_connections;
SELECT @@session.autocommit;
-- Show all variablesSHOW VARIABLES;
SHOW SESSION VARIABLES;
SHOWGLOBAL VARIABLES;
Quick answerPartitioning divides a table into smaller pieces for better performance and management. MySQL supports RANGE, LIST, HASH, and KEY partitioning.
RANGE: Partition by value ranges
LIST: Partition by list of values
HASH: Partition by hash function
KEY: Partition by MySQL hash function
Subpartitioning: Nested partitions
SQL
-- Partitioning in MySQL-- Table partitioning for performance-- Range partitioningCREATE TABLE orders_partitioned (
id INT,
order_date DATE,
customer_id INT,
amount DECIMAL(10,2)
)
PARTITIONBYRANGE (YEAR(order_date)) (
PARTITION p2020 VALUES LESS THAN (2021),
PARTITION p2021 VALUES LESS THAN (2022),
PARTITION p2022 VALUES LESS THAN (2023),
PARTITION p2023 VALUES LESS THAN (2024),
PARTITION p_future VALUES LESS THAN MAXVALUE
);
-- List partitioningCREATE TABLE users_by_region (
id INT,
name VARCHAR(100),
region VARCHAR(50)
)
PARTITIONBY LIST (region) (
PARTITION p_north VALUESIN ('North', 'Northeast'),
PARTITION p_south VALUESIN ('South', 'Southeast'),
PARTITION p_west VALUESIN ('West', 'Southwest'),
PARTITION p_east VALUESIN ('East', 'Midwest')
);
-- Hash partitioningCREATE TABLE logs (
id INT,
log_data TEXT,
created_at DATETIME
)
PARTITIONBY HASH (id)
PARTITIONS 4;
-- Key partitioning (similar to hash but uses MySQL's hash function)CREATE TABLE sessions (
id INT,
session_id VARCHAR(255),
data TEXT
)
PARTITIONBY KEY (id)
PARTITIONS 4;
-- SubpartitioningCREATE TABLE sales (
id INT,
sale_date DATE,
amount DECIMAL(10,2),
region VARCHAR(50)
)
PARTITIONBYRANGE (YEAR(sale_date))
SUBPARTITION BY HASH (id)
SUBPARTITIONS 2 (
PARTITION p2020 VALUES LESS THAN (2021),
PARTITION p2021 VALUES LESS THAN (2022)
);
-- Query partition informationSELECT*FROM INFORMATION_SCHEMA.PARTITIONS
WHERE TABLE_NAME ='orders_partitioned';
-- Partition pruning
EXPLAIN SELECT*FROM orders_partitioned
WHERE order_date BETWEEN'2021-01-01'AND'2021-12-31';
-- Add partitionALTER TABLE orders_partitioned
ADDPARTITION (PARTITION p2024 VALUES LESS THAN (2025));
-- Drop partitionALTER TABLE orders_partitioned DROPPARTITION p_future;
-- Reorganize partitionsALTER TABLE orders_partitioned
REORGANIZE PARTITION p_future INTO (
PARTITION p2024 VALUES LESS THAN (2025),
PARTITION p_future VALUES LESS THAN MAXVALUE
);
Quick answerFind duplicate emails using GROUP BY and HAVING.
GROUP BY: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1
Self-join: SELECT DISTINCT a.email FROM users a JOIN users b ON a.email = b.email AND a.id != b.id
Subquery: SELECT email FROM (SELECT email, COUNT(*) as cnt FROM users GROUP BY email) t WHERE cnt > 1
SQL
-- JSON in MySQL (MySQL 5.7+)-- JSON data type and functions-- Create table with JSON columnCREATE TABLE json_data (
id INTPRIMARY KEY AUTO_INCREMENT,
data JSON
);
-- Insert JSONINSERT INTO json_data (data) VALUES
('{"name": "Alice", "age": 25, "city": "NYC"}'),
('{"name": "Bob", "age": 30, "city": "LA", "hobbies": ["reading", "gaming"]}');
-- Extract valueSELECT
id,
JSON_EXTRACT(data, '$.name') AS name,
JSON_EXTRACT(data, '$.age') AS age
FROM json_data;
-- Extract with -> operatorSELECT
id,
data->'$.name'AS name,
data->'$.age'AS age
FROM json_data;
-- Extract as text with ->> operatorSELECT
id,
data->>'$.name'AS name,
data->>'$.age'AS age
FROM json_data;
-- JSON functionsSELECTJSON_OBJECT('name', name, 'age', age) AS user_json
FROM users;
SELECTJSON_ARRAY(name, age, city) AS user_array
FROM users;
-- Update JSONUPDATE json_data
SET data = JSON_SET(data, '$.age', 26, '$.city', 'NYC')
WHERE id =1;
-- Add to JSONUPDATE json_data
SET data = JSON_INSERT(data, '$.status', 'active')
WHERE id =1;
-- Remove from JSONUPDATE json_data
SET data = JSON_REMOVE(data, '$.status')
WHERE id =1;
-- Search in JSONSELECT*FROM json_data
WHERE JSON_EXTRACT(data, '$.name') ='Alice';
-- JSON pathSELECT
JSON_SEARCH(data, 'one', 'Alice') AS path
FROM json_data;
-- JSON table (MySQL 8.0+)SELECT*FROMJSON_TABLE(
'[{"name": "Alice"}, {"name": "Bob"}]',
'$[*]' COLUMNS (
name VARCHAR(100) PATH '$.name'
)
) AS jt;
Quick answerDelete duplicate records keeping the first (lowest ID) occurrence.
Self-join: DELETE a FROM users a JOIN users b ON a.email = b.email AND a.id > b.id
Subquery: DELETE FROM users WHERE id NOT IN (SELECT MIN(id) FROM users GROUP BY email)
Window function: WITH ranked AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) as rn FROM users) DELETE FROM users WHERE id IN (SELECT id FROM ranked WHERE rn > 1)
SQL
-- Full-Text Search in MySQL-- Full-text indexing and searching-- Create table with FULLTEXT indexCREATE TABLE articles (
id INTPRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255),
content TEXT,
FULLTEXT INDEX ft_title_content (title, content)
);
-- Insert dataINSERT INTO articles (title, content) VALUES
('MySQL Full-Text Search', 'MySQL supports full-text searching and indexing'),
('Advanced SQL Queries', 'Learn about complex SQL queries and optimization'),
('Database Performance Tuning', 'Tips for improving database performance');
-- NATURAL LANGUAGE MODESELECT*FROM articles
WHEREMATCH(title, content) AGAINST('MySQL'INNATURALLANGUAGE MODE);
-- BOOLEAN MODE-- + Required, - Excluded, * Wildcard, > Increase rank, < Decrease rankSELECT*FROM articles
WHEREMATCH(title, content) AGAINST('+MySQL +search'INBOOLEAN MODE);
SELECT*FROM articles
WHEREMATCH(title, content) AGAINST('MySQL -Oracle'INBOOLEAN MODE);
SELECT*FROM articles
WHEREMATCH(title, content) AGAINST('MySQL*'INBOOLEAN MODE);
SELECT*FROM articles
WHEREMATCH(title, content) AGAINST('>MySQL +search'INBOOLEAN MODE);
-- WITH QUERY EXPANSIONSELECT*FROM articles
WHEREMATCH(title, content) AGAINST('MySQL'WITH QUERY EXPANSION);
-- Query with relevance scoreSELECT*,
MATCH(title, content) AGAINST('MySQL') AS relevance
FROM articles
WHEREMATCH(title, content) AGAINST('MySQL')
ORDERBY relevance DESC;
-- Full-text search on multiple tables (using UNION)SELECT*FROM articles
WHEREMATCH(title, content) AGAINST('MySQL')
UNIONSELECT*FROM comments
WHEREMATCH(comment) AGAINST('MySQL');
-- StopwordsSELECT*FROM INFORMATION_SCHEMA.INNODB_FT_DEFAULT_STOPWORD;
-- Minimum word lengthSHOW VARIABLES LIKE'ft_min_word_len';
SHOW VARIABLES LIKE'innodb_ft_min_token_size';
Quick answerFind employees who earn more than their managers using self-join.
Self-join: SELECT e.name FROM employees e JOIN employees m ON e.manager_id = m.id WHERE e.salary > m.salary
Subquery: SELECT name FROM employees e WHERE salary > (SELECT salary FROM employees WHERE id = e.manager_id)
SQL
-- Spatial Data in MySQL (MySQL 5.7+)-- Spatial data types and functions-- Create table with spatial columnCREATE TABLE locations (
id INTPRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
coordinates POINT NOT NULL,
SPATIAL INDEX idx_coords (coordinates)
);
-- Insert spatial dataINSERT INTO locations (name, coordinates) VALUES
('Central Park', ST_PointFromText('POINT(-73.9654 40.7829)')),
('Times Square', ST_PointFromText('POINT(-73.9855 40.7580)')),
('Empire State', ST_PointFromText('POINT(-73.9857 40.7484)'));
-- Create polygonCREATE TABLE areas (
id INTPRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
boundary POLYGON NOT NULL,
SPATIAL INDEX idx_boundary (boundary)
);
INSERT INTO areas (name, boundary) VALUES
('Manhattan', ST_PolygonFromText('POLYGON((-74.05 40.70, -73.90 40.70, -73.90 40.80, -74.05 40.80, -74.05 40.70))'));
-- Spatial queries-- ST_DistanceSELECT
name,
ST_Distance(coordinates, ST_PointFromText('POINT(-73.97 40.76)')) AS distance
FROM locations
ORDERBY distance;
-- ST_WithinSELECT
l.name AS location,
a.name AS area
FROM locations l, areas a
WHERE ST_Within(l.coordinates, a.boundary);
-- ST_ContainsSELECT
a.name AS area,
COUNT(*) AS location_count
FROM areas a, locations l
WHERE ST_Contains(a.boundary, l.coordinates)
GROUPBY a.id;
-- ST_BufferSELECT
name,
ST_AsText(ST_Buffer(coordinates, 0.01)) AS buffer
FROM locations;
-- ST_IntersectsSELECT
l1.name AS point1,
l2.name AS point2,
ST_Distance(l1.coordinates, l2.coordinates) AS distance
FROM locations l1, locations l2
WHERE l1.id < l2.id
AND ST_Distance(l1.coordinates, l2.coordinates) <0.01;
-- ST_AreaSELECT
name,
ST_Area(boundary) AS area_sq_degrees
FROM areas;
-- ST_CentroidSELECT
name,
ST_AsText(ST_Centroid(boundary)) AS centroid
FROM areas;
How interviewers ask it“Can you find employees in department with highest average salary in MySQL? Then walk me through the edge cases you would test.”
Quick answerFind employees in the department with the highest average salary.
Subquery: SELECT * FROM employees WHERE department_id = (SELECT department_id FROM employees GROUP BY department_id ORDER BY AVG(salary) DESC LIMIT 1)
CTE: WITH dept_avg AS (SELECT department_id, AVG(salary) as avg_sal FROM employees GROUP BY department_id) SELECT e.* FROM employees e JOIN dept_avg d ON e.department_id = d.department_id WHERE d.avg_sal = (SELECT MAX(avg_sal) FROM dept_avg)
SQL
-- Generated Columns in MySQL-- Virtual and stored generated columns-- Stored generated columnCREATE TABLE sales (
id INTPRIMARY KEY AUTO_INCREMENT,
quantity INTNOT NULL,
unit_price DECIMAL(10,2) NOT NULL,
total_price DECIMAL(10,2) GENERATED ALWAYS AS (quantity * unit_price) STORED
);
-- Virtual generated columnCREATE TABLE employees (
id INTPRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(100),
last_name VARCHAR(100),
full_name VARCHAR(200) GENERATED ALWAYS AS (CONCAT(first_name, ' ', last_name)) VIRTUAL
);
-- Generated column with complex expressionCREATE TABLE orders (
id INTPRIMARY KEY AUTO_INCREMENT,
subtotal DECIMAL(10,2),
tax_rate DECIMAL(5,2) DEFAULT10.00,
tax_amount DECIMAL(10,2) GENERATED ALWAYS AS (subtotal * tax_rate /100) STORED,
total DECIMAL(10,2) GENERATED ALWAYS AS (subtotal + (subtotal * tax_rate /100)) STORED
);
-- Generated column with conditional logicCREATE TABLE products (
id INTPRIMARY KEY AUTO_INCREMENT,
price DECIMAL(10,2),
discount_percent DECIMAL(5,2) DEFAULT0,
discounted_price DECIMAL(10,2) GENERATED ALWAYS AS (
CASEWHEN discount_percent >0THEN price * (1- discount_percent /100)
ELSE price
END
) STORED
);
-- Index on generated columnCREATE INDEX idx_discounted_price ON products(discounted_price);
-- Generated column with JSON dataCREATE TABLE json_users (
id INTPRIMARY KEY AUTO_INCREMENT,
user_data JSON,
user_name VARCHAR(100) GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(user_data, '$.name'))) STORED,
user_age INT GENERATED ALWAYS AS (JSON_EXTRACT(user_data, '$.age')) VIRTUAL
);
-- Insert into generated columnINSERT INTO sales (quantity, unit_price) VALUES (5, 10.00);
INSERT INTO employees (first_name, last_name) VALUES ('John', 'Doe');
INSERT INTO json_users (user_data) VALUES ('{"name": "Alice", "age": 25}');
-- Select generated columnsSELECT*FROM sales;
SELECT full_name FROM employees;
SELECT user_name, user_age FROM json_users;
Quick answerCalculate cumulative sum using window functions or self-join.
Window function: SELECT id, amount, SUM(amount) OVER (ORDER BY id) as cumulative_sum FROM transactions
Self-join: SELECT a.id, a.amount, SUM(b.amount) as cumulative_sum FROM transactions a JOIN transactions b ON b.id <= a.id GROUP BY a.id, a.amount
SQL
-- Views with Check Option in MySQL-- Updatable views with check option-- Basic view with check optionCREATEVIEW active_users ASSELECT id, name, email, status
FROM users
WHERE status ='active'WITHCHECK OPTION;
-- Insert through viewINSERT INTO active_users (name, email, status)
VALUES ('Alice', 'alice@example.com', 'active'); -- Works-- This will fail (status not active)INSERT INTO active_users (name, email, status)
VALUES ('Bob', 'bob@example.com', 'inactive'); -- Fails-- View with cascade check optionCREATEVIEW nyc_users ASSELECT id, name, city, status
FROM active_users
WHERE city ='NYC'WITHCASCADEDCHECK OPTION;
-- View with local check optionCREATEVIEW la_users ASSELECT id, name, city, status
FROM active_users
WHERE city ='LA'WITHLOCALCHECK OPTION;
-- View with no check optionCREATEVIEW all_users ASSELECT id, name, email, status, city
FROM users
WHERE status ='active';
-- Insert into no-check viewINSERT INTO all_users (name, email, status, city)
VALUES ('Bob', 'bob@example.com', 'inactive', 'LA');
-- Update view with check optionUPDATE active_users SET status ='inactive'WHERE id =1; -- FailsUPDATE active_users SET status ='active'WHERE id =1; -- Works-- View check option restrictions-- Views with JOIN, GROUP BY, DISTINCT, UNION, subqueries cannot be updatable-- Check if view is updatableSELECT
TABLE_NAME,
IS_UPDATABLE
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_SCHEMA ='database_name';
Quick answerCalculate moving average over a window of rows.
Window function: SELECT date, amount, AVG(amount) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) as moving_avg FROM sales
Self-join: SELECT a.date, a.amount, AVG(b.amount) as moving_avg FROM sales a JOIN sales b ON b.date BETWEEN DATE_SUB(a.date, INTERVAL 2 DAY) AND a.date GROUP BY a.date, a.amount
SQL
-- Temporary Tables in MySQL-- Temporary tables for session-specific data-- Create temporary tableCREATE TEMPORARY TABLE temp_users (
id INTPRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
age INT
);
-- Insert dataINSERT INTO temp_users (name, age) VALUES
('Alice', 25),
('Bob', 30);
-- Query temporary tableSELECT*FROM temp_users;
-- Temporary table with SELECTCREATE TEMPORARY TABLE temp_active_users
SELECT*FROM users WHERE status ='active';
-- Temporary table with indexesCREATE TEMPORARY TABLE temp_orders (
id INTPRIMARY KEY AUTO_INCREMENT,
user_id INT,
total DECIMAL(10,2),
INDEX idx_user (user_id)
);
-- Temporary table with ENGINE optionCREATE TEMPORARY TABLE temp_memory (
id INTPRIMARY KEY,
data VARCHAR(100)
) ENGINE = MEMORY;
-- Temporary table with ON COMMIT DELETE ROWSCREATE TEMPORARY TABLE temp_sessions (
session_id VARCHAR(255),
data TEXT
) ONCOMMITDELETEROWS;
-- Drop temporary tableDROP TEMPORARY TABLE temp_users;
DROP TEMPORARY TABLE IF EXISTS temp_users;
-- Check if table is temporarySELECT
TABLE_NAME,
TABLE_TYPE
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA ='database_name'AND TABLE_TYPE ='TEMPORARY';
-- Using temporary table for complex queryCREATE TEMPORARY TABLE temp_high_spenders
SELECT
user_id,
SUM(total) AS total_spent
FROM orders
GROUPBY user_id
HAVING total_spent >1000;
SELECT
u.name,
u.email,
t.total_spent
FROM users u
JOIN temp_high_spenders t ON u.id = t.user_id
ORDERBY t.total_spent DESC;
-- Temporary table for paginationCREATE TEMPORARY TABLE temp_page
SELECT*FROM users
ORDERBY name
LIMIT 10OFFSET20;
-- Clean upDROP TEMPORARY TABLE temp_high_spenders;
DROP TEMPORARY TABLE temp_page;
Quick answerCreate a pivot table using conditional aggregation.
CASE with SUM: SELECT product, SUM(CASE WHEN month = 'Jan' THEN sales ELSE 0 END) as Jan, SUM(CASE WHEN month = 'Feb' THEN sales ELSE 0 END) as Feb FROM sales GROUP BY product
IF with SUM: SELECT product, SUM(IF(month = 'Jan', sales, 0)) as Jan, SUM(IF(month = 'Feb', sales, 0)) as Feb FROM sales GROUP BY product
SQL
-- Character Sets and Collations in MySQL-- Character set and collation management-- Show character setsSHOWCHARACTER SET;
SHOW CHARSET;
-- Show collationsSHOWCOLLATION;
SHOWCOLLATIONLIKE'utf8%';
-- Set character set for databaseCREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Set character set for tableCREATE TABLE mytable (
id INTPRIMARY KEY,
name VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
) DEFAULTCHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Set character set for columnALTER TABLE users MODIFY name VARCHAR(100) CHARACTER SET utf8mb4;
-- Convert table character setALTER TABLE users CONVERTTOCHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Convert column character setALTER TABLE users MODIFY name VARCHAR(100) CHARACTER SET latin1;
-- Set session character setSET NAMES 'utf8mb4';
SETCHARACTER SET utf8mb4;
-- Set global character setSETGLOBAL character_set_server ='utf8mb4';
SETGLOBAL collation_server ='utf8mb4_unicode_ci';
-- Check character setsSHOW VARIABLES LIKE'character_set%';
SHOW VARIABLES LIKE'collation%';
-- Compare strings with different collationsSELECT'abc'='ABC'COLLATE utf8mb4_unicode_ci; -- 1SELECT'abc'='ABC'COLLATE utf8mb4_bin; -- 0-- Use specific collation in querySELECT*FROM users
WHERE name ='Alice'COLLATE utf8mb4_unicode_ci;
-- Unicode vs non-unicode-- utf8mb4 supports all Unicode characters (including emoji)CREATE TABLE messages (
id INTPRIMARY KEY,
content VARCHAR(255) CHARACTER SET utf8mb4
);
INSERT INTO messages (content) VALUES ('Hello 😊');
Quick answerGet top N records per group using window functions or correlated subqueries.
Window function: WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) as rn FROM employees) SELECT * FROM ranked WHERE rn <= 3
Correlated subquery: SELECT * FROM employees e WHERE (SELECT COUNT(*) FROM employees WHERE department_id = e.department_id AND salary > e.salary) < 3
SQL
-- Information Schema in MySQL-- Querying metadata-- List all databasesSELECT*FROM INFORMATION_SCHEMA.SCHEMATA;
-- List all tables in databaseSELECT
TABLE_NAME,
TABLE_TYPE,
ENGINE,
ROW_FORMAT,
TABLE_ROWS,
DATA_LENGTH,
INDEX_LENGTH
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA ='database_name';
-- List all columns in tableSELECT
COLUMN_NAME,
DATA_TYPE,
IS_NULLABLE,
COLUMN_DEFAULT,
CHARACTER_MAXIMUM_LENGTH,
NUMERIC_PRECISION,
COLUMN_KEY,
EXTRA
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA ='database_name'AND TABLE_NAME ='users';
-- List indexesSELECT*FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA ='database_name'AND TABLE_NAME ='users';
-- List foreign keysSELECT
CONSTRAINT_NAME,
TABLE_NAME,
COLUMN_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA ='database_name'AND REFERENCED_TABLE_NAME ISNOT NULL;
-- List viewsSELECT
TABLE_NAME,
VIEW_DEFINITION,
CHECK_OPTION,
IS_UPDATABLE
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_SCHEMA ='database_name';
-- List privilegesSELECT*FROM INFORMATION_SCHEMA.USER_PRIVILEGES
WHERE GRANTEE LIKE'%app_user%';
-- Table sizesSELECT
TABLE_NAME,
ROUND((DATA_LENGTH + INDEX_LENGTH) /1024/1024, 2) AS size_mb
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA ='database_name'ORDERBY size_mb DESC;
-- Query optimizer statisticsSELECT*FROM INFORMATION_SCHEMA.OPTIMIZER_TRACE;
-- InnoDB metricsSELECT*FROM INFORMATION_SCHEMA.INNODB_METRICS;
-- Show process listSELECT*FROM INFORMATION_SCHEMA.PROCESSLIST;
Quick answerFind missing IDs in a sequence using recursive CTE or self-join.
Recursive CTE: WITH RECURSIVE numbers(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM numbers WHERE n < (SELECT MAX(id) FROM table)) SELECT n FROM numbers WHERE n NOT IN (SELECT id FROM table)
Self-join: SELECT t1.id + 1 as missing_id FROM table t1 LEFT JOIN table t2 ON t2.id = t1.id + 1 WHERE t2.id IS NULL AND t1.id < (SELECT MAX(id) FROM table)
SQL
-- Find missing IDs using recursive CTE (MySQL 8.0+)WITHRECURSIVE numbers(n) AS (
SELECT1UNIONALLSELECT n +1FROM numbers WHERE n < (SELECTMAX(id) FROM mytable)
)
SELECT n AS missing_id
FROM numbers
WHERE n NOTIN (SELECT id FROM mytable);
-- Using self-joinSELECT t1.id +1AS missing_id
FROM mytable t1
LEFTJOIN mytable t2 ON t2.id = t1.id +1WHERE t2.id ISNULLAND t1.id < (SELECTMAX(id) FROM mytable);
Quick answerFind consecutive days of activity using window functions.
ROW_NUMBER: WITH numbered AS (SELECT date, ROW_NUMBER() OVER (ORDER BY date) as rn FROM activities) SELECT MIN(date) as start_date, MAX(date) as end_date, COUNT(*) as days FROM (SELECT date, rn - DATEDIFF(date, (SELECT MIN(date) FROM activities)) as grp FROM numbered) grouped GROUP BY grp HAVING COUNT(*) >= 3
SQL
-- Find consecutive days of activity (MySQL 8.0+)WITH numbered AS (
SELECTdate,
ROW_NUMBER() OVER (ORDERBYdate) AS rn
FROM activities
),
grouped AS (
SELECTdate,
rn - DATEDIFF(date, (SELECTMIN(date) FROM activities)) AS grp
FROM numbered
)
SELECTMIN(date) AS start_date,
MAX(date) AS end_date,
COUNT(*) AS days
FROM grouped
GROUPBY grp
HAVINGCOUNT(*) >=3ORDERBY start_date;
Quick answerFind overlapping time intervals using self-join.
Self-join: SELECT a.id as interval1, b.id as interval2 FROM intervals a JOIN intervals b ON a.id < b.id AND a.start < b.end AND a.end > b.start
SQL
-- Find overlapping intervalsSELECT
a.id AS interval1,
b.id AS interval2,
a.start_date AS start1,
a.end_date AS end1,
b.start_date AS start2,
b.end_date AS end2
FROM intervals a
JOIN intervals b ON a.id < b.id
WHERE a.start_date < b.end_date
AND a.end_date > b.start_date;
Quick answerTraverse hierarchical data using recursive CTE.
Recursive CTE: WITH RECURSIVE org_tree(id, name, manager_id, level) AS (SELECT id, name, manager_id, 0 FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.id, e.name, e.manager_id, ot.level + 1 FROM employees e JOIN org_tree ot ON e.manager_id = ot.id) SELECT * FROM org_tree ORDER BY level, id
SQL
-- Recursive hierarchy (MySQL 8.0+)WITHRECURSIVE org_tree AS (
-- Anchor: top-level employeesSELECT
id,
name,
manager_id,
0AS level,
CAST(name ASCHAR(200)) AS path
FROM employees
WHERE manager_id ISNULLUNIONALL-- Recursive: childrenSELECT
e.id,
e.name,
e.manager_id,
ot.level +1,
CONCAT(ot.path, ' -> ', e.name)
FROM employees e
JOIN org_tree ot ON e.manager_id = ot.id
)
SELECT
CONCAT(REPEAT(' ', level), name) AS org_chart,
level,
path
FROM org_tree
ORDERBY path;
Quick answerFind department with highest average or total salary.
GROUP BY: SELECT department_id, AVG(salary) as avg_salary FROM employees GROUP BY department_id ORDER BY avg_salary DESC LIMIT 1
Subquery: SELECT department_id, AVG(salary) as avg_salary FROM employees GROUP BY department_id HAVING AVG(salary) = (SELECT MAX(avg_salary) FROM (SELECT AVG(salary) as avg_salary FROM employees GROUP BY department_id) t)
SQL
-- Department with highest average salarySELECT
department_id,
AVG(salary) AS avg_salary
FROM employees
GROUPBY department_id
ORDERBY avg_salary DESC
LIMIT 1;
-- Using subquerySELECT
department_id,
AVG(salary) AS avg_salary
FROM employees
GROUPBY department_id
HAVINGAVG(salary) = (
SELECTMAX(avg_salary)
FROM (SELECTAVG(salary) AS avg_salary FROM employees GROUPBY department_id) t
);
Quick answerCalculate running total per category using window function.
Window function: SELECT category, date, amount, SUM(amount) OVER (PARTITION BY category ORDER BY date) as running_total FROM sales
SQL
-- Running total per category (MySQL 8.0+)SELECT
category,
date,
amount,
SUM(amount) OVER (PARTITIONBY category ORDERBYdate) AS running_total
FROM sales
ORDERBY category, date;
-- Running total using self-joinSELECT
a.category,
a.date,
a.amount,
SUM(b.amount) AS running_total
FROM sales a
JOIN sales b ON a.category = b.category AND b.date <= a.date
GROUPBY a.category, a.date, a.amount
ORDERBY a.category, a.date;
Quick answerFind groups of consecutive records (islands) using window functions.
ROW_NUMBER: WITH numbered AS (SELECT *, ROW_NUMBER() OVER (ORDER BY date) as rn FROM activities), grouped AS (SELECT *, rn - ROW_NUMBER() OVER (ORDER BY date) as grp FROM numbered) SELECT MIN(date) as start, MAX(date) as end, COUNT(*) as days FROM grouped GROUP BY grp HAVING COUNT(*) > 1
SQL
-- Find islands of data (MySQL 8.0+)WITH numbered AS (
SELECTdate,
ROW_NUMBER() OVER (ORDERBYdate) AS rn
FROM activities
),
grouped AS (
SELECTdate,
rn -ROW_NUMBER() OVER (ORDERBYdate) AS grp
FROM numbered
)
SELECTMIN(date) AS start_date,
MAX(date) AS end_date,
COUNT(*) AS days
FROM grouped
GROUPBY grp
HAVINGCOUNT(*) >1ORDERBY start_date;
Quick answerFind gaps in sequences using window functions.
LAG: WITH numbered AS (SELECT id, LAG(id) OVER (ORDER BY id) as prev_id FROM table) SELECT prev_id + 1 as gap_start, id - 1 as gap_end FROM numbered WHERE id > prev_id + 1
SQL
-- Gap analysis using LAG (MySQL 8.0+)WITH numbered AS (
SELECT
id,
LAG(id) OVER (ORDERBY id) AS prev_id
FROM mytable
)
SELECT
prev_id +1AS gap_start,
id -1AS gap_end
FROM numbered
WHERE id > prev_id +1;
-- Gap analysis using self-joinSELECT
t1.id +1AS gap_start,
MIN(t2.id) -1AS gap_end
FROM mytable t1
JOIN mytable t2 ON t2.id > t1.id
WHERENOTEXISTS (
SELECT1FROM mytable t3
WHERE t3.id > t1.id AND t3.id < t2.id
)
GROUPBY t1.id;
Quick answerFind the most frequent value using GROUP BY and ORDER BY.
GROUP BY: SELECT column, COUNT(*) as count FROM table GROUP BY column ORDER BY count DESC LIMIT 1
Subquery: SELECT column FROM table GROUP BY column HAVING COUNT(*) = (SELECT MAX(count) FROM (SELECT COUNT(*) as count FROM table GROUP BY column) t)
SQL
-- Mode (most frequent value)SELECT column_name, COUNT(*) AS frequency
FROM mytable
GROUPBY column_name
ORDERBY frequency DESC
LIMIT 1;
-- Using subquerySELECT column_name
FROM mytable
GROUPBY column_name
HAVINGCOUNT(*) = (
SELECTMAX(count)
FROM (SELECTCOUNT(*) AS count FROM mytable GROUPBY column_name) t
);
Quick answerFind the median value using window functions or subqueries.
PERCENTILE_CONT: SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) OVER () as median FROM employees LIMIT 1
NTILE: SELECT AVG(salary) as median FROM (SELECT salary, NTILE(2) OVER (ORDER BY salary) as tile FROM employees) t WHERE tile = 1 OR tile = 2 GROUP BY tile
SQL
-- Median using PERCENTILE_CONT (MySQL 8.0+)SELECTPERCENTILE_CONT(0.5) WITHINGROUP (ORDERBY salary)
OVER () AS median
FROM employees
LIMIT 1;
-- Median using NTILE (MySQL 8.0+)SELECTAVG(salary) AS median
FROM (
SELECT
salary,
NTILE(2) OVER (ORDERBY salary) AS tile
FROM employees
) t
WHERE tile =1OR tile =2GROUPBY tile;
-- Median using user variables (older MySQL)SELECTAVG(salary) AS median
FROM (
SELECT salary
FROM employees
ORDERBY salary
LIMIT 2- (SELECTCOUNT(*) FROM employees) %2OFFSET (SELECT (COUNT(*) -1) /2FROM employees)
) t;
Quick answerFind the N-th highest salary using LIMIT or window functions.
LIMIT: SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT N-1, 1
DENSE_RANK: WITH ranked AS (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rnk FROM employees) SELECT DISTINCT salary FROM ranked WHERE rnk = N
SQL
-- Nth highest salary using LIMITSELECTDISTINCT salary
FROM employees
ORDERBY salary DESC
LIMIT N-1, 1;
-- Nth highest using DENSE_RANK (MySQL 8.0+)WITH ranked AS (
SELECT
salary,
DENSE_RANK() OVER (ORDERBY salary DESC) AS rnk
FROM employees
)
SELECTDISTINCT salary
FROM ranked
WHERE rnk = N;
-- 3rd highest salary exampleSELECTDISTINCT salary
FROM employees
ORDERBY salary DESC
LIMIT 2, 1;
Quick answerCalculate cumulative distribution using window functions.
CUME_DIST: SELECT value, CUME_DIST() OVER (ORDER BY value) as cume_dist FROM table
PERCENT_RANK: SELECT value, PERCENT_RANK() OVER (ORDER BY value) as percent_rank FROM table
SQL
-- Cumulative distribution (MySQL 8.0+)SELECTvalue,
CUME_DIST() OVER (ORDERBYvalue) AS cume_dist,
PERCENT_RANK() OVER (ORDERBYvalue) AS percent_rank
FROM mytable
ORDERBYvalue;
-- Manual calculationSELECTvalue,
(SELECTCOUNT(*) FROM mytable WHEREvalue<= t.value) /COUNT(*) AS cume_dist
FROM mytable t
GROUPBYvalueORDERBYvalue;
Quick answerGet first and last values in a group using window functions.
FIRST_VALUE: SELECT category, FIRST_VALUE(value) OVER (PARTITION BY category ORDER BY date) as first_value FROM table
LAST_VALUE: SELECT category, LAST_VALUE(value) OVER (PARTITION BY category ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as last_value FROM table
SQL
-- First and last value in group (MySQL 8.0+)SELECT
category,
date,
value,
FIRST_VALUE(value) OVER (PARTITIONBY category ORDERBYdate) AS first_value,
LAST_VALUE(value) OVER (
PARTITIONBY category
ORDERBYdateROWSBETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_value
FROM mytable
ORDERBY category, date;
-- Using subquerySELECT
category,
date,
value,
(SELECTvalueFROM mytable t2
WHERE t2.category = t1.category
ORDERBY t2.date ASC LIMIT 1) AS first_value,
(SELECTvalueFROM mytable t2
WHERE t2.category = t1.category
ORDERBY t2.date DESC LIMIT 1) AS last_value
FROM mytable t1;
Quick answerGet previous and next row values using LAG and LEAD.
LAG: SELECT date, amount, LAG(amount, 1) OVER (ORDER BY date) as previous_amount FROM sales
LEAD: SELECT date, amount, LEAD(amount, 1) OVER (ORDER BY date) as next_amount FROM sales
SQL
-- LAG and LEAD (MySQL 8.0+)SELECTdate,
amount,
LAG(amount, 1) OVER (ORDERBYdate) AS previous_amount,
LAG(amount, 2) OVER (ORDERBYdate) AS previous_2_amount,
LEAD(amount, 1) OVER (ORDERBYdate) AS next_amount,
LEAD(amount, 2) OVER (ORDERBYdate) AS next_2_amount
FROM sales
ORDERBYdate;
-- LAG and LEAD with partitionSELECT
category,
date,
amount,
LAG(amount, 1) OVER (PARTITIONBY category ORDERBYdate) AS prev_in_category,
LEAD(amount, 1) OVER (PARTITIONBY category ORDERBYdate) AS next_in_category
FROM sales
ORDERBY category, date;
Quick answerCalculate difference between current and previous row using LAG.
LAG: SELECT date, amount, amount - LAG(amount, 1) OVER (ORDER BY date) as difference FROM sales
Self-join: SELECT a.date, a.amount - b.amount as difference FROM sales a JOIN sales b ON b.date = (SELECT MAX(date) FROM sales WHERE date < a.date)
SQL
-- Difference between current and previous (MySQL 8.0+)SELECTdate,
amount,
amount -LAG(amount, 1) OVER (ORDERBYdate) AS difference,
amount -LAG(amount, 1) OVER (ORDERBYdate) AS diff_from_prev
FROM sales
ORDERBYdate;
-- Using self-joinSELECT
a.date,
a.amount,
a.amount - b.amount AS difference
FROM sales a
JOIN sales b ON b.date = (
SELECTMAX(date)
FROM sales
WHEREdate< a.date
)
ORDERBY a.date;
Quick answerCalculate percentage change between current and previous row.
LAG: SELECT date, amount, ((amount - LAG(amount, 1) OVER (ORDER BY date)) / LAG(amount, 1) OVER (ORDER BY date)) * 100 as pct_change FROM sales
Self-join: SELECT a.date, ((a.amount - b.amount) / b.amount) * 100 as pct_change FROM sales a JOIN sales b ON b.date = (SELECT MAX(date) FROM sales WHERE date < a.date)
SQL
-- Percentage change (MySQL 8.0+)SELECTdate,
amount,
((amount -LAG(amount, 1) OVER (ORDERBYdate)) /LAG(amount, 1) OVER (ORDERBYdate)) *100AS pct_change
FROM sales
ORDERBYdate;
-- Percentage change from previous yearSELECTdate,
amount,
((amount -LAG(amount, 12) OVER (ORDERBYdate)) /LAG(amount, 12) OVER (ORDERBYdate)) *100AS yoy_pct_change
FROM monthly_sales
ORDERBYdate;
Quick answerCompare values with the same period in the previous year.
LAG with INTERVAL: SELECT date, amount, LAG(amount, 12) OVER (ORDER BY date) as same_period_previous_year FROM monthly_sales
Self-join: SELECT a.date, a.amount - b.amount as yoy_change FROM sales a JOIN sales b ON YEAR(a.date) = YEAR(b.date) + 1 AND MONTH(a.date) = MONTH(b.date)
SQL
-- Year-over-year comparisonSELECTYEAR(date) ASyear,
MONTH(date) ASmonth,
amount,
LAG(amount, 12) OVER (ORDERBYdate) AS same_month_last_year,
amount -LAG(amount, 12) OVER (ORDERBYdate) AS yoy_change,
((amount -LAG(amount, 12) OVER (ORDERBYdate)) /LAG(amount, 12) OVER (ORDERBYdate)) *100AS yoy_pct_change
FROM monthly_sales
ORDERBYdate;
Window function: SELECT date, amount, SUM(amount) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) as rolling_7day_sum FROM daily_sales
SQL
-- Rolling sum (MySQL 8.0+)SELECTdate,
amount,
SUM(amount) OVER (
ORDERBYdateROWSBETWEEN6 PRECEDING ANDCURRENTROW
) AS rolling_7day_sum,
AVG(amount) OVER (
ORDERBYdateROWSBETWEEN6 PRECEDING ANDCURRENTROW
) AS rolling_7day_avg
FROM daily_sales
ORDERBYdate;
-- Rolling sum with partitionSELECT
category,
date,
amount,
SUM(amount) OVER (
PARTITIONBY category
ORDERBYdateROWSBETWEEN6 PRECEDING ANDCURRENTROW
) AS rolling_7day_sum_category
FROM daily_sales
ORDERBY category, date;
Quick answerFill missing dates in a time series using recursive CTE.
Recursive CTE: WITH RECURSIVE dates(dt) AS (SELECT MIN(date) FROM sales UNION ALL SELECT dt + INTERVAL 1 DAY FROM dates WHERE dt < (SELECT MAX(date) FROM sales)) SELECT d.dt, COALESCE(s.amount, 0) as amount FROM dates d LEFT JOIN sales s ON d.dt = s.date
SQL
-- Fill missing dates (MySQL 8.0+)WITHRECURSIVE dates(dt) AS (
SELECTMIN(date) FROM sales
UNIONALLSELECT dt +INTERVAL1DAYFROM dates
WHERE dt < (SELECTMAX(date) FROM sales)
)
SELECT
d.dt ASdate,
COALESCE(s.amount, 0) AS amount
FROM dates d
LEFTJOIN sales s ON d.dt = s.date
ORDERBY d.dt;
-- Fill missing dates with previous valueWITHRECURSIVE dates(dt) AS (
SELECTMIN(date) FROM sales
UNIONALLSELECT dt +INTERVAL1DAYFROM dates
WHERE dt < (SELECTMAX(date) FROM sales)
),
filled AS (
SELECT
d.dt ASdate,
s.amount,
@prev_amount :=COALESCE(s.amount, @prev_amount) AS filled_amount
FROM dates d
LEFTJOIN sales s ON d.dt = s.date
CROSSJOIN (SELECT@prev_amount :=0) init
)
SELECTdate, filled_amount AS amount
FROM filled;
Quick answerCalculate difference between dates using DATEDIFF or TIMESTAMPDIFF.
DATEDIFF: SELECT DATEDIFF(end_date, start_date) as days_diff FROM projects
TIMESTAMPDIFF: SELECT TIMESTAMPDIFF(DAY, start_date, end_date) as days_diff FROM projects
SQL
-- Difference between datesSELECT
start_date,
end_date,
DATEDIFF(end_date, start_date) AS days_diff,
TIMESTAMPDIFF(DAY, start_date, end_date) AS days_diff_2,
TIMESTAMPDIFF(MONTH, start_date, end_date) AS months_diff,
TIMESTAMPDIFF(YEAR, start_date, end_date) AS years_diff
FROM projects;
-- Difference from current dateSELECT
start_date,
DATEDIFF(CURDATE(), start_date) AS days_since_start,
TIMESTAMPDIFF(DAY, start_date, CURDATE()) AS days_since_start_2
FROM projects;
Quick answerFormat date using DATE_FORMAT function.
DATE_FORMAT: SELECT DATE_FORMAT(date, '%Y-%m-%d') as formatted_date FROM events
Common formats: SELECT DATE_FORMAT(date, '%M %e, %Y') as full_date FROM events
SQL
-- Format dateSELECT
date_col,
DATE_FORMAT(date_col, '%Y-%m-%d') AS yyyy_mm_dd,
DATE_FORMAT(date_col, '%m/%d/%Y') AS mm_dd_yyyy,
DATE_FORMAT(date_col, '%M %e, %Y') AS full_date,
DATE_FORMAT(date_col, '%W, %M %e, %Y') AS full_date_with_day,
DATE_FORMAT(date_col, '%r') AS time_12h,
DATE_FORMAT(date_col, '%H:%i:%s') AS time_24h,
DATE_FORMAT(date_col, '%Y-%m-%d %H:%i:%s') AS datetime_format
FROM events;
Quick answerAdd or subtract intervals from dates using DATE_ADD or DATE_SUB.
DATE_ADD: SELECT DATE_ADD(date, INTERVAL 1 DAY) as next_day FROM events
DATE_SUB: SELECT DATE_SUB(date, INTERVAL 1 MONTH) as previous_month FROM events
SQL
-- Date arithmeticSELECT
date_col,
DATE_ADD(date_col, INTERVAL1DAY) AS tomorrow,
DATE_ADD(date_col, INTERVAL1 WEEK) AS next_week,
DATE_ADD(date_col, INTERVAL1MONTH) AS next_month,
DATE_ADD(date_col, INTERVAL1YEAR) AS next_year,
DATE_SUB(date_col, INTERVAL1DAY) AS yesterday,
DATE_SUB(date_col, INTERVAL1MONTH) AS last_month,
date_col +INTERVAL1DAYAS tomorrow_alt,
date_col -INTERVAL1DAYAS yesterday_alt
FROM events;
-- Date arithmetic with NOWSELECT
NOW() AS now,
NOW() +INTERVAL1HOURAS in_1_hour,
NOW() -INTERVAL1DAYAS yesterday,
DATE_ADD(NOW(), INTERVAL1HOUR) AS in_1_hour_2;
Quick answerGet current date and time using NOW, CURDATE, CURTIME.
NOW: SELECT NOW() as current_datetime
CURDATE: SELECT CURDATE() as current_date
CURTIME: SELECT CURTIME() as current_time
SQL
-- Current date and timeSELECT
NOW() AS current_datetime,
CURDATE() AScurrent_date,
CURTIME() AScurrent_time,
UTC_TIMESTAMP() AS utc_timestamp,
UNIX_TIMESTAMP() AS unix_timestamp,
CURRENT_TIMESTAMP() AScurrent_timestamp,
SYSDATE() AS sysdate;
-- Date onlySELECTDATE(NOW()) AS date_only,
TIME(NOW()) AS time_only,
YEAR(NOW()) AS current_year,
MONTH(NOW()) AS current_month,
DAY(NOW()) AS current_day;
Quick answerMatch string patterns using LIKE or REGEXP.
LIKE: SELECT * FROM users WHERE email LIKE '%@example.com'
REGEXP: SELECT * FROM users WHERE email REGEXP '^[a-z]+@[a-z]+\.[a-z]+$'
RLIKE: SELECT * FROM users WHERE email RLIKE '^[a-zA-Z]+@[a-zA-Z]+\.[a-zA-Z]+$'
SQL
-- String pattern matching using LIKESELECT*FROM users
WHERE email LIKE'%@example.com';
SELECT*FROM users
WHERE name LIKE'A%';
SELECT*FROM users
WHERE name LIKE'%son%';
-- Using REGEXPSELECT*FROM users
WHERE email REGEXP '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$';
SELECT*FROM users
WHERE name REGEXP '^[A-Z]';
SELECT*FROM users
WHERE phone REGEXP '^[0-9]{3}-[0-9]{3}-[0-9]{4}$';
-- Using RLIKE (synonym for REGEXP)SELECT*FROM users
WHERE email RLIKE '^[a-z]+@[a-z]+\.[a-z]+$';
Quick answerClean strings using TRIM, RTRIM, LTRIM.
TRIM: SELECT TRIM(' hello ') as trimmed
LTRIM: SELECT LTRIM(' hello') as left_trimmed
RTRIM: SELECT RTRIM('hello ') as right_trimmed
SQL
-- String cleaningSELECT' hello 'AS original,
TRIM(' hello ') AS trimmed,
LTRIM(' hello') AS left_trimmed,
RTRIM('hello ') AS right_trimmed,
TRIM(LEADING' 'FROM' hello') AS lead_trimmed,
TRIM(TRAILING' 'FROM'hello ') AS trail_trimmed,
TRIM(BOTH' 'FROM' hello ') AS both_trimmed;
-- Trimming specific charactersSELECTTRIM(LEADING'x'FROM'xxhelloxx') AS trim_leading_x,
TRIM(TRAILING'x'FROM'xxhelloxx') AS trim_trailing_x,
TRIM(BOTH'x'FROM'xxhelloxx') AS trim_both_x;
Quick answerFind position of substring using LOCATE or POSITION.
LOCATE: SELECT LOCATE('World', 'Hello World') as position
POSITION: SELECT POSITION('World' IN 'Hello World') as position
INSTR: SELECT INSTR('Hello World', 'World') as position
SQL
-- Find position of substringSELECT'Hello World'AS str,
LOCATE('World', 'Hello World') AS locate_position,
POSITION('World'IN'Hello World') AS position_function,
INSTR('Hello World', 'World') AS instr_function,
LOCATE('o', 'Hello World', 5) AS locate_from_position,
LOCATE('World', 'Hello World') AS locate_position;
-- Position in columnSELECT
email,
LOCATE('@', email) AS at_position,
LOCATE('.', email) AS dot_position
FROM users;
Quick answerUse JSON functions for aggregation and data manipulation.
JSON_ARRAYAGG: SELECT JSON_ARRAYAGG(name) as names FROM users WHERE city = 'NYC'
JSON_OBJECTAGG: SELECT JSON_OBJECTAGG(id, name) as user_map FROM users
SQL
-- JSON aggregation (MySQL 5.7+)SELECT
department_id,
JSON_ARRAYAGG(name) AS employee_names,
JSON_OBJECTAGG(id, name) AS employee_map
FROM employees
GROUPBY department_id;
-- JSON_ARRAY with groupingSELECT
city,
JSON_ARRAYAGG(name) AS users_in_city
FROM users
GROUPBY city;
-- JSON_OBJECT with groupingSELECT
department_id,
JSON_OBJECT(
'department', department_id,
'employees', JSON_ARRAYAGG(name),
'count', COUNT(*)
) AS department_info
FROM employees
GROUPBY department_id;
Quick answerQuery JSON data using path expressions.
JSON_EXTRACT: SELECT JSON_EXTRACT(data, '$.name') as name FROM users
->: SELECT data->'$.name' as name FROM users
->>: SELECT data->>'$.name' as name FROM users
SQL
-- JSON path queriesSELECT
JSON_EXTRACT(data, '$.name') AS name,
JSON_EXTRACT(data, '$.age') AS age,
data->'$.name'AS name_operator,
data->>'$.name'AS name_operator_text,
data->'$.address.city'AS city,
JSON_EXTRACT(data, '$.hobbies[0]') AS first_hobby
FROM users_json;
-- Nested JSON pathSELECT
data->>'$.name'AS name,
data->'$.address'AS address,
data->'$.address.city'AS city,
JSON_EXTRACT(data, '$.address.zip') AS zip
FROM users_json;
Quick answerConvert JSON to relational table using JSON_TABLE (MySQL 8.0+).
JSON_TABLE: SELECT * FROM JSON_TABLE('[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]', '$[*]' COLUMNS (id INT PATH '$.id', name VARCHAR(100) PATH '$.name')) as jt
SQL
-- JSON_TABLE (MySQL 8.0+)SELECT*FROMJSON_TABLE(
'[{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]',
'$[*]' COLUMNS (
name VARCHAR(100) PATH '$.name',
age INT PATH '$.age'
)
) AS jt;
-- JSON_TABLE with nested dataSELECT*FROMJSON_TABLE(
'{"users": [{"name": "Alice", "hobbies": ["reading", "gaming"]}]}',
'$.users[*]' COLUMNS (
name VARCHAR(100) PATH '$.name',
hobbies JSON PATH '$.hobbies'
)
) AS jt;
Quick answerConcatenate values from grouped rows using GROUP_CONCAT.
GROUP_CONCAT: SELECT department_id, GROUP_CONCAT(name ORDER BY name SEPARATOR ', ') as employees FROM employees GROUP BY department_id
SQL
-- GROUP_CONCATSELECT
department_id,
GROUP_CONCAT(name) AS employees,
GROUP_CONCAT(name ORDERBY name) AS employees_sorted,
GROUP_CONCAT(name ORDERBY name SEPARATOR '; ') AS employees_separated,
COUNT(*) AS employee_count
FROM employees
GROUPBY department_id;
-- GROUP_CONCAT with DISTINCTSELECT
department_id,
GROUP_CONCAT(DISTINCT title ORDERBY title) AS unique_titles
FROM employees
GROUPBY department_id;
-- GROUP_CONCAT with CONCATSELECT
department_id,
GROUP_CONCAT(CONCAT(name, ' (', title, ')') SEPARATOR ', ') AS employees_info
FROM employees
GROUPBY department_id;
Quick answerGenerate random numbers using RAND or RANDOM.
RAND: SELECT RAND() as random, FLOOR(RAND() * 100) as random_int
RANDOM: SELECT RANDOM() as random
SQL
-- Random number generationSELECT
RAND() AS random_float,
RAND(123) AS random_seeded,
FLOOR(RAND() *100) AS random_int_0_99,
FLOOR(RAND() *100) +1AS random_int_1_100,
ROUND(RAND() *100) AS rounded_random;
-- Random orderSELECT*FROM users ORDERBY RAND() LIMIT 5;
-- Random sample (MySQL 8.0+)SELECT*FROM users ORDERBY RAND() LIMIT 5;
-- Random sample using TABLESAMPLE (MySQL 8.0+)SELECT*FROM users TABLESAMPLESYSTEM(10);
Quick answerGenerate row numbers using ROW_NUMBER or user variables.
ROW_NUMBER: SELECT *, ROW_NUMBER() OVER (ORDER BY id) as row_num FROM users
User variable: SELECT *, @row_num := @row_num + 1 as row_num FROM users, (SELECT @row_num := 0) r
SQL
-- Row number using ROW_NUMBER (MySQL 8.0+)SELECT*,
ROW_NUMBER() OVER (ORDERBY id) AS row_num
FROM users;
-- Row number with partitionSELECT*,
ROW_NUMBER() OVER (PARTITIONBY department_id ORDERBY salary DESC) AS rank_in_dept
FROM employees;
-- Row number using user variables (older MySQL)SELECT*,
@row_num :=@row_num+1AS row_num
FROM users, (SELECT@row_num :=0) r
ORDERBY id;
-- Row number with resetSELECT*,
@row_num := IF(@prev_dept= department_id, @row_num+1, 1) AS row_num,
@prev_dept := department_id
FROM employees
CROSSJOIN (SELECT@row_num :=0, @prev_dept :=NULL) r
ORDERBY department_id, salary DESC;
Quick answerAggregate with conditions using CASE in aggregates.
CASE with SUM: SELECT department, SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_count, SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) as inactive_count FROM users GROUP BY department
SQL
-- Conditional aggregationSELECT
department_id,
COUNT(*) AS total_employees,
SUM(CASEWHEN status ='active'THEN1ELSE0END) AS active_count,
SUM(CASEWHEN status ='inactive'THEN1ELSE0END) AS inactive_count,
SUM(CASEWHEN status ='pending'THEN1ELSE0END) AS pending_count,
AVG(CASEWHEN status ='active'THEN salary ELSENULLEND) AS avg_active_salary
FROM employees
GROUPBY department_id;
-- Conditional aggregation with multiple conditionsSELECT
department_id,
SUM(CASEWHEN gender ='M'AND status ='active'THEN1ELSE0END) AS active_males,
SUM(CASEWHEN gender ='F'AND status ='active'THEN1ELSE0END) AS active_females
FROM employees
GROUPBY department_id;
Quick answerFind greatest or least value among columns using GREATEST and LEAST.
GREATEST: SELECT GREATEST(col1, col2, col3) as max_value FROM table
LEAST: SELECT LEAST(col1, col2, col3) as min_value FROM table
SQL
-- GREATEST and LEASTSELECT
col1,
col2,
col3,
GREATEST(col1, col2, col3) AS max_value,
LEAST(col1, col2, col3) AS min_value
FROM mytable;
-- GREATEST with NULL handlingSELECT
col1,
col2,
col3,
GREATEST(COALESCE(col1, 0), COALESCE(col2, 0), COALESCE(col3, 0)) AS max_with_default
FROM mytable;
-- Find max of values from different tablesSELECT
u.id,
GREATEST(u.salary, COALESCE(b.bonus, 0)) AS total_compensation
FROM users u
LEFTJOIN bonuses b ON u.id = b.user_id;
Quick answerConvert between data types using CAST or CONVERT.
CAST: SELECT CAST('123' AS SIGNED) as int_val, CAST('123.45' AS DECIMAL(10,2)) as dec_val
CONVERT: SELECT CONVERT('123', SIGNED) as int_val, CONVERT('2024-01-01', DATE) as date_val
SQL
-- Type conversion-- CASTSELECTCAST('123'AS SIGNED) AS int_val,
CAST('123.45'ASDECIMAL(10,2)) AS dec_val,
CAST('2024-01-01'ASDATE) AS date_val,
CAST(123ASCHAR) AS char_val,
CAST(123.45AS UNSIGNED) AS unsigned_val;
-- CONVERTSELECTCONVERT('123', SIGNED) AS int_val,
CONVERT('123.45', DECIMAL(10,2)) AS dec_val,
CONVERT('2024-01-01', DATE) AS date_val,
CONVERT(123, CHAR) AS char_val;
-- Converting binarySELECTCONVERT('Hello'USING utf8mb4) AS utf8_string,
CAST('Hello'ASBINARY) AS binary_data;
Quick answerConditionally update rows using CASE in UPDATE.
CASE: UPDATE employees SET salary = CASE WHEN performance = 'excellent' THEN salary * 1.10 WHEN performance = 'good' THEN salary * 1.05 ELSE salary END
SQL
-- Conditional UPDATE-- Update with CASEUPDATE employees
SET salary =CASEWHEN performance_rating =5THEN salary *1.20WHEN performance_rating =4THEN salary *1.15WHEN performance_rating =3THEN salary *1.10WHEN performance_rating =2THEN salary *1.05ELSE salary
ENDWHERE status ='active';
-- Update with IFUPDATE employees
SET status = IF(active_years >5, 'senior', 'junior')
WHERE status ='active';
-- Update with multiple conditionsUPDATE products
SET price =CASEWHEN category ='electronics'THEN price *0.90WHEN category ='clothing'THEN price *0.85WHEN category ='books'THEN price *0.80ELSE price
END;
CREATE: CREATE TABLE users (id INT PRIMARY KEY, status VARCHAR(20) DEFAULT 'active', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
ALTER: ALTER TABLE users ALTER COLUMN status SET DEFAULT 'active'
SQL
-- Default values-- Create table with defaultsCREATE TABLE users (
id INTPRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
status VARCHAR(20) DEFAULT'active',
created_at TIMESTAMPDEFAULTCURRENT_TIMESTAMP,
updated_at TIMESTAMPDEFAULTCURRENT_TIMESTAMPONUPDATECURRENT_TIMESTAMP,
age INTDEFAULT0,
city VARCHAR(100) DEFAULT'Unknown'
);
-- Alter default valueALTER TABLE users ALTERCOLUMN status SETDEFAULT'active';
-- Drop defaultALTER TABLE users ALTERCOLUMN status DROPDEFAULT;
-- INSERT with defaultsINSERT INTO users (name) VALUES ('Alice'); -- Uses defaults for other columns-- Explicitly use defaultINSERT INTO users (name, status) VALUES ('Bob', DEFAULT);
Quick answerDrop tables with caution using DROP TABLE.
DROP: DROP TABLE users
DROP IF EXISTS: DROP TABLE IF EXISTS users
TRUNCATE: TRUNCATE TABLE users
SQL
-- Drop table-- Drop tableDROPTABLE users;
-- Drop with IF EXISTSDROPTABLE IF EXISTS users;
-- Drop multiple tablesDROPTABLE users, orders, products;
-- Truncate table (removes all rows)TRUNCATETABLE users;
-- Difference: DROP removes table structure, TRUNCATE keeps structure-- DROP TABLE users; -- Removes table-- TRUNCATE TABLE users; -- Removes all data but keeps table-- Drop with CASCADEDROPTABLE users CASCADE;
-- Drop with RESTRICTDROPTABLE users RESTRICT;
Quick answerUse temporary tables for complex queries.
CREATE TEMPORARY: CREATE TEMPORARY TABLE temp_users SELECT * FROM users WHERE status = 'active'
DROP TEMPORARY: DROP TEMPORARY TABLE temp_users
SQL
-- Temporary tables-- Create temporary tableCREATE TEMPORARY TABLE temp_users (
id INTPRIMARY KEY,
name VARCHAR(100),
age INT
);
-- Temporary table from SELECTCREATE TEMPORARY TABLE temp_active_users
SELECT*FROM users WHERE status ='active';
-- Temporary table with indexesCREATE TEMPORARY TABLE temp_orders (
id INTPRIMARY KEY AUTO_INCREMENT,
user_id INT,
total DECIMAL(10,2),
INDEX idx_user (user_id)
) ENGINE = MEMORY;
-- Use temporary tableINSERT INTO temp_users VALUES (1, 'Alice', 25);
SELECT*FROM temp_users;
-- Drop temporary tableDROP TEMPORARY TABLE temp_users;
DROP TEMPORARY TABLE IF EXISTS temp_users;
-- Temporary tables are session-specific and dropped automatically-- on session end-- Use temporary table for complex queryCREATE TEMPORARY TABLE temp_high_spenders
SELECT user_id, SUM(total) AS total_spent
FROM orders
GROUPBY user_id
HAVING total_spent >1000;
SELECT u.name, u.email, t.total_spent
FROM users u
JOIN temp_high_spenders t ON u.id = t.user_id;
Quick answerShow table information using various commands.
DESCRIBE: DESCRIBE users
SHOW CREATE TABLE: SHOW CREATE TABLE users
SHOW TABLE STATUS: SHOW TABLE STATUS LIKE 'users'
SQL
-- Show table information-- DESCRIBEDESCRIBE users;
DESC users;
-- SHOW CREATE TABLESHOWCREATE TABLE users;
-- SHOW TABLE STATUSSHOWTABLE STATUS LIKE'users';
SHOWTABLE STATUS FROM database_name;
-- SHOW COLUMNSSHOW COLUMNS FROM users;
SHOWFULL COLUMNS FROM users;
-- SHOW INDEXSHOW INDEX FROM users;
-- INFORMATION_SCHEMASELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME ='users';
SELECT*FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='users';
SELECT*FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_NAME ='users';
Connection info: SELECT CONNECTION_ID() as connection_id
SQL
-- Database information-- Current databaseSELECT DATABASE() AS current_database;
-- Server versionSELECT VERSION() AS version;
SELECT @@versionAS version_2;
-- Connection IDSELECT CONNECTION_ID() AS connection_id;
-- Server variablesSHOW VARIABLES;
SHOW VARIABLES LIKE'version%';
SHOW VARIABLES LIKE'max_connections';
SHOW VARIABLES LIKE'character%';
-- Server statusSHOW STATUS;
SHOW STATUS LIKE'Threads%';
SHOW STATUS LIKE'Questions';
-- ProcesslistSHOW PROCESSLIST;
SHOWFULL PROCESSLIST;
-- EnginesSHOW ENGINES;
-- Character setsSHOWCHARACTER SET;
-- CollationsSHOWCOLLATION;
Quick answerEssential query optimization tips for better performance.
Use EXPLAIN: Analyze query execution plans
Create indexes: On columns used in WHERE, JOIN, ORDER BY
Limit results: Use LIMIT for pagination
Avoid SELECT *: Specify only needed columns
Use joins instead of subqueries: When possible
SQL
-- Query optimization tips-- 1. Use EXPLAIN to analyze queries
EXPLAIN SELECT*FROM users WHERE name ='Alice';
EXPLAIN FORMAT=JSON SELECT*FROM users WHERE name ='Alice';
-- 2. Create indexes on frequently used columnsCREATE INDEX idx_users_name ON users(name);
CREATE INDEX idx_users_email_age ON users(email, age);
-- 3. Use LIMIT for paginationSELECT*FROM users ORDERBY id LIMIT 10OFFSET20;
-- 4. Avoid SELECT *SELECT id, name, email FROM users WHERE active =1;
-- 5. Use EXISTS instead of IN when possibleSELECT*FROM users u
WHEREEXISTS (SELECT1FROM orders o WHERE o.user_id = u.id);
-- 6. Use JOIN instead of subqueriesSELECT u.*, o.total
FROM users u
JOIN orders o ON u.id = o.user_id;
-- 7. Use UNION ALL instead of UNION when duplicates are acceptableSELECT id, name FROM users
UNIONALLSELECT id, name FROM archived_users;
-- 8. Use appropriate data types-- VARCHAR for variable length, CHAR for fixed length-- INT vs BIGINT based on range needed-- 9. Use batch operationsINSERT INTO users (name, email) VALUES
('Alice', 'alice@example.com'),
('Bob', 'bob@example.com');
-- 10. Use prepared statements for repeated queriesPREPARE stmt FROM'SELECT * FROM users WHERE id = ?';
SET@id=1;
EXECUTE stmt USING@id;
MySQL is an open-source relational database management system that uses SQL for storing, managing, and retrieving structured data. It is widely used in web applications, enterprise systems, and software development.
What is the difference between SQL and MySQL?
SQL is a standard language used to communicate with relational databases, while MySQL is a database management system that uses SQL to store and manage data.
What are joins in MySQL?
Joins in MySQL are used to combine data from multiple tables. Common types include INNER JOIN, LEFT JOIN, RIGHT JOIN, and CROSS JOIN.
What are indexes in MySQL?
Indexes in MySQL improve query performance by allowing faster data retrieval. Common indexes include PRIMARY KEY, UNIQUE, INDEX, and FULLTEXT indexes.
What is normalization in MySQL?
Normalization is a database design technique used to reduce data redundancy and improve data consistency by organizing tables into structured forms.
What are stored procedures in MySQL?
Stored procedures are reusable SQL programs stored inside the database that contain SQL statements, business logic, parameters, and control flow operations.
What are triggers in MySQL?
Triggers are automatically executed database objects that run when specific events such as INSERT, UPDATE, or DELETE operations occur on a table.
What are transactions in MySQL?
Transactions in MySQL allow multiple SQL operations to be executed as a single unit. They ensure data consistency using commands such as COMMIT, ROLLBACK, and SAVEPOINT.
Why are MySQL interview questions important?
MySQL interview questions evaluate knowledge of database concepts, SQL queries, data modeling, performance optimization, transactions, indexing, and real-world database problem solving.
How can I prepare for a MySQL interview?
Practice SQL queries, joins, subqueries, indexes, normalization, stored procedures, triggers, transactions, database design, optimization techniques, and solve real-world MySQL coding problems.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.