Mastering MySQL for Interviews
Mastering MySQL for Interviews
1. Reliability and Stability: MySQL has a proven track record of handling large-scale
applications efficiently.
2. Flexibility: Supports various data types, including structured, semi-structured, and
unstructured data.
3. High Availability: MySQL’s replication and clustering features ensure minimal
downtime.
4. ACID Compliance: Ensures data integrity through atomicity, consistency, isolation,
and durability.
5. Support for Large Databases: Can handle databases with millions of records
efficiently.
1.3.1 System Requirements Before installation, ensure your system meets the following
requirements:
For Linux:
The MySQL Command-Line Interface (CLI) is a powerful tool for managing and interacting
with your database. It allows users to execute SQL queries, manage users, and perform
administrative tasks.
Basic Commands:
Log in to MySQL:
mysql -u [username] -p
Show all databases:
SHOW DATABASES;
Select a database:
USE database_name;
Show all tables in the database:
SHOW TABLES;
Exit the CLI:
EXIT;
Exercise:
Expected Output:
A database is an organized collection of data, stored and accessed electronically. Tables are
the building blocks of a database, consisting of rows and columns to store data in a structured
format.
Key Concepts:
Create a table:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype
);
View table structure:
DESCRIBE table_name;
Delete a table:
DROP TABLE table_name;
MySQL provides various data types to define the kind of data stored in each column.
Create a table:
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
hire_date DATE
);
Modify a table:
ALTER TABLE employees ADD COLUMN salary DECIMAL(10, 2);
Delete a table:
DROP TABLE employees;
Update records:
UPDATE employees SET salary = 60000.00 WHERE name = 'John Doe';
Delete records:
DELETE FROM employees WHERE name = 'John Doe';
Exercise:
Summary: This chapter covered the fundamentals of databases and tables, data types, and
basic commands for managing and manipulating data. Practice these concepts to strengthen
your foundation in MySQL.
Syntax:
Examples:
The ORDER BY clause is used to sort the result set in ascending (default) or descending order.
Syntax:
Examples:
Syntax:
Examples:
Examples:
Retrieve employees hired after 2024 and earning more than 50,000:
SELECT * FROM employees WHERE hire_date > '2024-01-01' AND salary >
50000;
Retrieve employees hired in 2024 or 2025:
SELECT * FROM employees WHERE hire_date LIKE '2024%' OR hire_date
LIKE '2025%';
Exercise:
Expected Output:
Aggregate functions in MySQL are used to perform calculations on a set of values and return
a single value. Common aggregate functions include:
Examples:
sql
CopyEdit
SELECT COUNT(*) FROM employees;
sql
CopyEdit
SELECT SUM(salary) FROM employees;
sql
CopyEdit
SELECT MAX(salary) FROM employees;
The GROUP BY clause groups rows with the same values in specified columns and allows
aggregate functions to be applied to each group.
Syntax:
sql
CopyEdit
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;
Examples:
Find the total salary for each department:
sql
CopyEdit
SELECT department_id, SUM(salary)
FROM employees
GROUP BY department_id;
sql
CopyEdit
SELECT department_id, COUNT(*)
FROM employees
GROUP BY department_id;
The HAVING clause filters groups after the GROUP BY clause is applied. It is used instead of
WHERE for aggregate functions.
Syntax:
sql
CopyEdit
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;
Examples:
sql
CopyEdit
SELECT department_id, SUM(salary) AS total_salary
FROM employees
GROUP BY department_id
HAVING total_salary > 100000;
You can use GROUP BY, HAVING, and other clauses like ORDER BY together for more complex
queries.
Example: Retrieve departments with more than 5 employees, sorted by total salary:
sql
CopyEdit
SELECT department_id, COUNT(*) AS employee_count, SUM(salary) AS
total_salary
FROM employees
GROUP BY department_id
HAVING employee_count > 5
ORDER BY total_salary DESC;
Exercise:
1. Create a table named sales with columns: id, product_name, quantity, and price.
2. Insert records for at least 5 products.
3. Write queries to:
o Find the total revenue (quantity * price) for all products.
o Group products by their names and calculate total revenue for each product.
o Display only products with revenue greater than 500.
Expected Output:
sql
CopyEdit
CREATE TABLE sales (
id INT AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(50),
quantity INT,
price DECIMAL(10, 2)
);
Summary: In this chapter, we explored aggregate functions, grouping data, and filtering
groups using GROUP BY and HAVING. These tools are essential for analyzing data and
generating reports in MySQL. Practice these concepts with real-world examples to strengthen
your understanding.
Joins in MySQL are used to combine rows from two or more tables based on a related
column between them.
Types of Joins:
Examples:
sql
CopyEdit
SELECT employees.name, departments.name AS department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.id;
Left Join: Get all employees and their department names (including employees
without a department):
sql
CopyEdit
SELECT employees.name, departments.name AS department_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.id;
5.2 Subqueries
Subqueries, also known as nested queries, are queries inside another query. They are useful
for performing intermediate calculations or filtering data.
Types of Subqueries:
Examples:
sql
CopyEdit
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
sql
CopyEdit
SELECT name
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);
5.3 Combining Joins and Subqueries
Example: List all departments along with the total number of employees in each department,
but include only departments with more than 5 employees:
sql
CopyEdit
SELECT d.name AS department_name, COUNT(e.id) AS employee_count
FROM departments d
LEFT JOIN employees e
ON d.id = e.department_id
GROUP BY d.name
HAVING employee_count > 5;
Exercise:
1. Create two tables: products (id, name, category_id, price) and categories (id,
category_name).
2. Insert records into both tables.
3. Write queries to:
o Retrieve all products along with their category names.
o List all categories, including those with no products.
o Find the category with the most expensive product.
Expected Output:
sql
CopyEdit
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
category_id INT,
price DECIMAL(10, 2)
);
SELECT c.category_name
FROM categories c
INNER JOIN products p
ON c.id = p.category_id
WHERE p.price = (SELECT MAX(price) FROM products);
Summary: In this chapter, we covered advanced techniques for joining tables and using
subqueries in MySQL. These tools are invaluable for solving complex data retrieval
challenges. Practice with your own datasets to master these concepts.
Joins are used in MySQL to combine rows from two or more tables based on a related
column between them. They are essential for working with relational databases and retrieving
data efficiently.
1. INNER JOIN: Retrieves records that have matching values in both tables.
2. LEFT JOIN (OUTER JOIN): Retrieves all records from the left table and matching
records from the right table.
3. RIGHT JOIN (OUTER JOIN): Retrieves all records from the right table and
matching records from the left table.
4. FULL JOIN: Combines the result of both LEFT JOIN and RIGHT JOIN, returning
all records with matches in either table. (Not directly supported in MySQL; achieved
using UNION.)
INNER JOIN
sql
CopyEdit
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
employees:
id name department_id
1 John 101
2 Alice 102
id name department_id
3 Bob 101
departments:
id name
101 HR
102 IT
103 Finance
Query:
sql
CopyEdit
SELECT employees.name, departments.name AS department
FROM employees
INNER JOIN departments
ON employees.department_id = departments.id;
Output:
name department
John HR
Alice IT
Bob HR
LEFT JOIN
sql
CopyEdit
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
Example: Retrieve all employees and their departments, even if no matching department
exists:
sql
CopyEdit
SELECT employees.name, departments.name AS department
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.id;
Output:
name department
John HR
Alice IT
Bob HR
RIGHT JOIN
sql
CopyEdit
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
sql
CopyEdit
SELECT employees.name, departments.name AS department
FROM employees
RIGHT JOIN departments
ON employees.department_id = departments.id;
Output:
name department
John HR
Alice IT
NULL Finance
sql
CopyEdit
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column
UNION
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
Example: Retrieve all employees and departments, showing NULL where there are no
matches.
4.3 Self-Join
A self-join is a join where a table is joined with itself. This is useful for hierarchical data,
such as employees and their managers.
Example:
sql
CopyEdit
SELECT A.name AS employee, B.name AS manager
FROM employees A
LEFT JOIN employees B
ON A.manager_id = B.id;
A cross join returns the Cartesian product of two tables, meaning all possible combinations of
rows.
Example:
sql
CopyEdit
SELECT employees.name AS employee, departments.name AS department
FROM employees
CROSS JOIN departments;
4.5 Exercises
1. Create two tables: students and courses. Populate them with data.
2. Write queries to:
o Retrieve all students enrolled in a specific course using INNER JOIN.
o List all courses, even those without students, using LEFT JOIN.
o Find students not enrolled in any course using RIGHT JOIN.
Expected Output:
sql
CopyEdit
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50)
);
Summary: This chapter covered various types of joins in MySQL, their syntax, and practical
use cases. Joins are essential for working with relational data, enabling efficient querying
across multiple tables.