Mysql Cheat Sheet: 100 Questions: 1. Basic SQL Queries
Mysql Cheat Sheet: 100 Questions: 1. Basic SQL Queries
● Answer: The SELECT statement is used to query the database and retrieve data
from one or more tables.
Example:
SELECT * FROM employees;
1.2. How do you retrieve all columns from a table named users?
● Answer: Use the SELECT * statement to retrieve all columns from the table.
Example:
SELECT * FROM users;
1.3. How can you select only specific columns from a table?
Example:
SELECT first_name, last_name FROM employees;
● Answer: Use the WHERE clause to specify conditions for filtering records.
Example:
SELECT * FROM employees WHERE department = 'Sales';
Example:
SELECT * FROM employees ORDER BY salary DESC;
2. Aggregate Functions
2.1. How do you find the total number of rows in a table?
Example:
SELECT COUNT(*) FROM employees;
2.2. How can you find the average value of a numeric column?
Example:
SELECT AVG(salary) FROM employees;
Example:
SELECT MAX(salary) FROM employees;
Example:
SELECT MIN(salary) FROM employees;
●
2.5. How do you calculate the sum of a numeric column?
Example:
SELECT SUM(salary) FROM employees;
3. Joins
3.1. What is an INNER JOIN?
● Answer: An INNER JOIN returns rows that have matching values in both tables.
Example:
SELECT employees.first_name, departments.department_name
FROM employees
● Answer: A LEFT JOIN returns all rows from the left table and the matched rows
from the right table. Non-matching rows from the right table will be NULL.
Example:
SELECT employees.first_name, departments.department_name
FROM employees
● Answer: A RIGHT JOIN returns all rows from the right table and the matched rows
from the left table. Non-matching rows from the left table will be NULL.
Example:
SELECT employees.first_name, departments.department_name
FROM employees
● Answer: MySQL does not support FULL JOIN directly. Use a combination of LEFT
JOIN and RIGHT JOIN.
Example:
SELECT employees.first_name, departments.department_name
FROM employees
UNION
FROM employees
● Answer: A CROSS JOIN returns the Cartesian product of both tables, meaning
every combination of rows.
Example:
SELECT employees.first_name, departments.department_name
FROM employees
●
4. Subqueries
4.1. What is a subquery?
Example:
SELECT first_name
FROM employees
● Answer: Place the subquery inside the WHERE clause to filter results based on the
result of the subquery.
Example:
SELECT first_name
FROM employees
● Answer: A correlated subquery references columns from the outer query and is
executed for each row of the outer query.
Example:
SELECT e1.first_name
FROM employees e1
Example:
SELECT avg_salaries.department_id, AVG(salary)
GROUP BY avg_salaries.department_id;
● Answer: A subquery in the SELECT clause returns a value that can be used as a
column in the result set.
Example:
SELECT first_name,
FROM employees;
5. Data Modification
5.1. How do you insert a new record into a table?
Example:
INSERT INTO employees (first_name, last_name, department_id, salary)
● Answer: Use the UPDATE statement with a WHERE clause to specify which records
to update.
Example:
UPDATE employees
SET salary = 55000
● Answer: Use the DELETE FROM statement with a WHERE clause to specify which
records to delete.
Example:
DELETE FROM employees
5.4. How can you delete all records from a table without removing the table itself?
Example:
TRUNCATE TABLE employees;
● Answer: DELETE removes rows one at a time and can be rolled back, while
TRUNCATE removes all rows at once and cannot be rolled back.
Example:
-- DELETE
-- TRUNCATE
6. Indexing
6.1. What is an index in MySQL?
● Answer: An index is a database object that improves the speed of data retrieval
operations.
Example:
CREATE INDEX idx_salary ON employees(salary);
Example:
CREATE INDEX idx_department ON employees(department_id);
6.3. What is the difference between a unique index and a non-unique index?
● Answer: A unique index ensures that all values in the indexed column are
unique, while a non-unique index does not enforce uniqueness.
Example:
-- Unique Index
-- Non-Unique Index
Example:
DROP INDEX idx_salary ON employees;
●
6.5. What is a composite index?
Example:
CREATE INDEX idx_name_dept ON employees(first_name, department_id);
7. Transactions
7.1. What is a transaction in MySQL?
Example:
START TRANSACTION;
COMMIT;
Example:
START TRANSACTION;
● Answer: Use the COMMIT statement to save all changes made during the
transaction.
Example:
COMMIT;
●
7.4. How do you roll back a transaction?
● Answer: Use the ROLLBACK statement to undo changes made during the
transaction.
Example:
ROLLBACK;
● Answer: COMMIT saves changes made during the transaction, while ROLLBACK
undoes them.
Example:
-- Commit
COMMIT;
-- Rollback
ROLLBACK;
8. User Management
8.1. How do you create a new user in MySQL?
Example:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
Example:
GRANT ALL PRIVILEGES ON database_name.* TO 'newuser'@'localhost';
●
Example:
REVOKE ALL PRIVILEGES ON database_name.* FROM 'newuser'@'localhost';
Example:
DROP USER 'newuser'@'localhost';
Example:
ALTER USER 'newuser'@'localhost' IDENTIFIED BY 'newpassword';
9. Data Types
9.1. What are the different types of data in MySQL?
● Answer: MySQL supports several data types, including numeric, date/time, and
string types.
Example:
-- Numeric Types
-- Date/Time Types
Example:
-- CHAR
col CHAR(10)
);
-- VARCHAR
col VARCHAR(10)
);
Example:
CREATE TABLE events (
event_date DATE
);
● Answer: The TEXT data type is used to store large amounts of text.
Example:
CREATE TABLE articles (
content TEXT
);
Example:
CREATE TABLE users (
username VARCHAR(50)
);
● Answer: The query optimizer analyzes SQL queries and determines the most
efficient way to execute them.
Example:
EXPLAIN SELECT * FROM employees WHERE salary > 50000;
● Answer: Use the EXPLAIN statement to get insights into how a query will be
executed.
Example:
EXPLAIN SELECT * FROM employees WHERE department_id = 1;
●
10.3. How can you improve query performance with indexes?
● Answer: Create indexes on columns frequently used in WHERE, JOIN, and ORDER BY
clauses.
Example:
CREATE INDEX idx_dept ON employees(department_id);
● Answer: Regularly use the OPTIMIZE TABLE statement to defragment and improve
table performance.
Example:
OPTIMIZE TABLE employees;
● Answer: Isolation levels define the extent to which the operations in one
transaction are isolated from those in other transactions. Levels include READ
UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE.
Example:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
● Answer: Use transaction retry mechanisms and ensure that transactions access
resources in the same order to avoid deadlocks.
● Example: Detect and handle deadlocks programmatically in application code.
11.3. What is a savepoint in MySQL?
● Answer: A savepoint allows you to set a point within a transaction to which you
can roll back.
Example:
SAVEPOINT my_savepoint;
-- Perform operations
● Answer: Use the LOCK TABLES statement to lock tables for reading or writing.
Example:
LOCK TABLES employees WRITE;
-- Perform operations
UNLOCK TABLES;
● Answer: Implicit locks are automatically managed by MySQL and occur when
rows or tables are accessed in transactions.
● Example: Implicit locks are managed by the MySQL engine during transaction
execution.
Example:
CREATE TABLE employees (
name VARCHAR(50)
);
Example:
CREATE TABLE departments (
department_name VARCHAR(50)
);
department_id INT,
);
Example:
CREATE TABLE users (
);
●
12.4. How do you define a default value for a column?
● Answer: Use the DEFAULT keyword to set a default value for a column.
Example:
CREATE TABLE products (
);
**12.5. What is a
check constraint?**
Example:
CREATE TABLE employees (
);
Example:
CREATE PROCEDURE GetEmployeeById(IN emp_id INT)
BEGIN
END;
●
Example:
CALL GetEmployeeById(1);
Example:
CREATE FUNCTION CalculateBonus(salary DECIMAL(10,2))
RETURNS DECIMAL(10,2)
BEGIN
END;
Example:
CREATE FUNCTION GetEmployeeCount()
RETURNS INT
BEGIN
RETURN emp_count;
END;
●
● Answer: A stored procedure performs an action and may not return a value, while
a function returns a value and can be used in SQL expressions.
Example:
-- Stored Procedure
BEGIN
END;
-- Function
RETURNS INT
BEGIN
END;
Example:
mysqldump -u username -p database_name > backup.sql
Example:
mysql -u username -p database_name < backup.sql
Example:
mysqldump -u username -p database_name > backup.sql
Example:
mysqldump -u username -p database_name table_name > table_backup.sql
● Answer: Partitioning divides a table into smaller, more manageable pieces while
maintaining a single logical view.
Example:
CREATE TABLE orders (
order_id INT,
order_date DATE
);
● Answer: Views are virtual tables created by a query and can simplify complex
queries.
Example:
CREATE VIEW employee_view AS
FROM employees
● Answer: A materialized view is a view that stores the result set physically,
allowing faster query performance. MySQL does not support materialized views
directly; use tables with periodic refreshes.
● Example: Simulate using tables and scheduled jobs.
content TEXT,
FULLTEXT(content)
);
● Answer: SHOW TABLE STATUS provides information about the status and structure
of tables, such as size and number of rows.
● Example: ```sql SHOW TABLE STATUS LIKE employees; Certainly! Here are
advanced MySQL questions, continuing from where we left off:
● Answer: Use the slow_query_log to identify slow queries and the EXPLAIN
statement to analyze their execution plans.
Example:
SET GLOBAL slow_query_log = 'ON';
16.2. What is a covering index and how does it improve query performance?
● Answer: A covering index includes all columns needed by a query, allowing the
query to be resolved using the index alone.
Example:
CREATE INDEX idx_name_age ON employees(name, age);
Example:
ANALYZE TABLE employees;
16.4. What are the implications of using JOIN vs. SUBQUERY for performance?
● Answer: Joins are often more efficient than subqueries because they use indexes
and optimize query plans better.
Example:
-- Join
FROM employees e
-- Subquery
FROM employees e;
● Answer: Index columns used in GROUP BY and ensure statistics are up-to-date to
improve performance.
Example:
CREATE INDEX idx_department ON employees(department_id);
Example:
-- On master
START SLAVE;
● Answer: Configure the master and slave servers with appropriate replication
settings and start the replication process.
Example:
-- On master
-- On slave
START SLAVE;
17.3. What is a replication lag, and how can you monitor it?
● Answer: Replication lag is the delay between the master and slave databases.
Use SHOW SLAVE STATUS to monitor it.
Example:
SHOW SLAVE STATUS \G;
Example:
-- Statement-based
binlog_format = STATEMENT;
-- Row-based
binlog_format = ROW;
Example:
-- Encryption
-- Decryption
Example:
-- Server-side
[mysqld]
ssl-ca=/path/to/ca-cert.pem
ssl-cert=/path/to/server-cert.pem
ssl-key=/path/to/server-key.pem
-- Client-side
[client]
ssl-ca=/path/to/ca-cert.pem
ssl-cert=/path/to/client-cert.pem
ssl-key=/path/to/client-key.pem
18.3. What is MySQL's approach to user authentication and how can it be improved?
● Answer: MySQL uses the mysql.user table for authentication. Improve security
by using strong passwords and enabling caching_sha2_password authentication.
Example:
CREATE USER 'user'@'host' IDENTIFIED WITH caching_sha2_password BY
'password';
● Answer: Use the GRANT and REVOKE statements to control user access to
databases and tables.
Example:
GRANT SELECT, INSERT ON database_name.* TO 'user'@'host';
● Answer: Use MySQL Enterprise Audit plugin or third-party tools to log and
monitor user activity.
Example:
INSTALL PLUGIN audit_log SONAME 'audit_log.so';
● Answer: ETL (Extract, Transform, Load) involves extracting data from various
sources, transforming it, and loading it into a data warehouse. Implement ETL
using MySQL’s LOAD DATA INFILE, INSERT INTO ... SELECT, and other data
import/export methods.
Example:
LOAD DATA INFILE '/path/to/file.csv' INTO TABLE table_name
● Answer: Use SQL functions and expressions to transform data during insertion or
querying.
Example:
INSERT INTO new_table (name, age)
sale_id INT,
sale_date DATE
);
● Answer: Use bulk data loading commands like LOAD DATA INFILE and optimize
import settings.
Example:
LOAD DATA INFILE '/path/to/large_file.csv' INTO TABLE table_name
● Answer: Use schema migration tools and version control to manage and apply
schema changes systematically.
● Example: Tools like Liquibase or Flyway can be used for schema migration and
version control.
● Answer: Use binary logs to restore the database to a specific point in time.
Example:
mysqlbinlog --stop-datetime="2024-07-01 12:00:00" /path/to/binlog >
recovery.sql
20.2. How do you backup and restore MySQL databases using snapshots?
Example:
# Create snapshot
# Restore snapshot
20.3. How can you use MySQL Enterprise Backup for hot backups?