Home > Information Technology

MySQL Interview Questions and Answers

MySQL Interview Questions and Answers

MySQL Interview Questions and Answers

MySQL is one of the most widely used relational database management systems. If you are preparing for a PHP, Laravel, backend, or database-related interview, understanding the fundamentals of MySQL is important.

Below are some commonly asked MySQL interview questions and answers, explained in simple and practical language.

1. What is MySQL?

MySQL is an open-source relational database management system (RDBMS). It uses SQL (Structured Query Language) to store, manage, and retrieve data from databases. It is commonly used for web applications, APIs, and other software that needs structured data storage.

2. What is the difference between UNION and UNION ALL?

UNION: Combines the results of two or more SELECT queries and removes duplicate rows.

UNION ALL: Combines the results of two or more SELECT queries but keeps duplicate rows.

Because UNION ALL does not need to remove duplicates, it can be faster when duplicate removal is not required.

3. What is the purpose of AUTO_INCREMENT?

AUTO_INCREMENT automatically generates a new numeric value when a row is inserted. It is commonly used for ID columns so that each new record gets a different identifier.

4. How can you optimize a MySQL query?

Some common ways to improve query performance are:

  • Create indexes on columns used frequently for searching, joining, or sorting.
  • Avoid selecting unnecessary columns.
  • Use EXPLAIN to understand how MySQL executes the query.
  • Optimize joins and filtering conditions.
  • Avoid unnecessary subqueries or repeated calculations.
  • Retrieve only the required number of rows.

The right optimization depends on the actual query and database structure.

5. What is a primary key in MySQL?

A primary key is a column or combination of columns that uniquely identifies each row in a table. A primary key cannot contain NULL values, and a table can have only one primary key.

6. What is a foreign key in MySQL?

A foreign key is a column or group of columns that references a key in another table, usually its primary key. It helps establish relationships between tables and can enforce referential integrity.

7. How do you handle NULL values in MySQL?

MySQL provides several ways to work with NULL values. For example:

  • IS NULL checks whether a value is NULL.
  • IS NOT NULL checks whether a value is not NULL.
  • COALESCE() returns an alternative value when the expression is NULL.
  • IFNULL() can be used to replace a NULL value with another value.

For example:

SELECT COALESCE(phone, 'Not Available') FROM users;

8. What is the difference between CHAR and VARCHAR?

CHAR is a fixed-length string data type, while VARCHAR is a variable-length string data type.

For example, if a column is defined as CHAR(10), it is designed for fixed-length values. VARCHAR(10) can store values of different lengths up to 10 characters.

VARCHAR is generally more suitable when the length of the stored values varies.

9. What are the storage engines in MySQL?

MySQL supports multiple storage engines, with InnoDB being the default storage engine for new tables in MySQL 8.4. The following are some commonly encountered storage engines:

  • InnoDB: Supports transactions, foreign keys, row-level locking, and crash recovery. It is commonly used for transactional applications.
  • MyISAM: An older engine that does not support transactions or foreign keys. It can still be encountered in older systems.
  • MEMORY: Stores table data in memory, so access can be very fast, but the data is not persistent across server restarts.
  • CSV: Stores table data in CSV-format files and can be useful in specific data exchange scenarios.
  • ARCHIVE: Designed for storing large amounts of archived data with a focus on reducing storage requirements.
  • BLACKHOLE: Accepts data but does not store it, and is mainly useful in specialized replication or logging scenarios.

Some other engines, such as MERGE, FEDERATED, and NDB, also exist in MySQL, but they are less commonly used in typical web applications.

10. What is an index in MySQL?

An index is a data structure that MySQL uses to find rows more efficiently. Instead of scanning every row in a table, MySQL can use an appropriate index to locate the required data faster.

Indexes are particularly useful for columns frequently used in WHERE, JOIN, ORDER BY, and similar operations. However, having too many indexes can increase storage requirements and slow down INSERT, UPDATE, and DELETE operations.

11. What are the types of indexes in MySQL?

Common types and forms of indexes include:

  • Primary Key Index: Created for a table's primary key. It uniquely identifies rows and does not allow NULL values.
  • Unique Index: Ensures that indexed values are unique.
  • Regular/Non-Unique Index: Allows duplicate values and is commonly used to speed up searches.
  • FULLTEXT Index: Used for full-text searches on supported character columns.
  • Composite Index: An index created using multiple columns.
  • Descending Index: An index that can specify descending order for indexed columns.

The appropriate index depends on how the table is queried.

12. What is BLOB?

BLOB stands for Binary Large Object. It is a MySQL data type used to store binary data, such as images, documents, or other files.

In many applications, however, large files are stored outside the database, such as in file storage or object storage, while the database stores the file path or URL.

13. What is a trigger?

A trigger is a database object that MySQL automatically executes when a specified event occurs on a table.

For example, a trigger can execute automatically before or after an INSERT, UPDATE, or DELETE operation.

14. How many types of triggers are available in MySQL?

MySQL supports six trigger event and timing combinations:

  1. BEFORE INSERT
  2. AFTER INSERT
  3. BEFORE UPDATE
  4. AFTER UPDATE
  5. BEFORE DELETE
  6. AFTER DELETE

These allow you to execute trigger logic at different points during data modification.

15. What is the difference between TRUNCATE and DELETE?

The main differences are:

  • DELETE can remove specific rows using a WHERE condition.
  • TRUNCATE removes all rows from the table and does not support a WHERE condition.
  • DELETE is a DML statement, while TRUNCATE is classified as a DDL statement in MySQL.
  • DELETE processes rows as a DML operation, while TRUNCATE is generally faster for removing all rows.
  • TRUNCATE resets the AUTO_INCREMENT counter, whereas deleting rows does not normally reset it.
  • TRUNCATE causes an implicit commit and cannot be rolled back like a normal DML operation.

16. What are the types of relationships in MySQL?

Common database relationships are:

  • One-to-One: One record in one table is associated with one record in another table.
  • One-to-Many: One record in one table can be associated with multiple records in another table.
  • Many-to-One: Multiple records in one table can refer to one record in another table.
  • Many-to-Many: Multiple records in one table can be associated with multiple records in another table. This is normally implemented using a junction or intermediate table.

17. What are the different types of joins in MySQL?

  • INNER JOIN: Returns rows where the join condition matches in both tables.
  • LEFT JOIN: Returns all rows from the left table and matching rows from the right table. If there is no match, the right-side columns contain NULL.
  • RIGHT JOIN: Returns all rows from the right table and matching rows from the left table.
  • CROSS JOIN: Produces the Cartesian product, meaning every row from one table is combined with every row from the other table.

MySQL does not provide a direct FULL OUTER JOIN syntax. A similar result can be achieved using a combination of other queries, such as LEFT JOIN and UNION.

MySQL also supports other join-related techniques, and a self-join can be created by joining a table to itself.

18. What is normalization?

Normalization is the process of organizing database tables to reduce unnecessary data duplication and improve data consistency.

Instead of keeping all information in one large table, related information can be separated into different tables and connected using keys.

For example, customer information and order information can be stored in separate tables and connected using a customer ID.

19. What is a stored procedure?

A stored procedure is a named collection of SQL statements stored in the database. It can be executed when required and can accept input parameters and return results.

Stored procedures can be useful when the same database operation needs to be performed repeatedly.

20. How can you find duplicate rows in a MySQL table?

One common approach is to use GROUP BY with HAVING COUNT(*) > 1.

For example:

SELECT email, COUNT(*) AS total
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

This identifies email values that occur more than once.

DISTINCT is useful for removing duplicates from a result, but by itself it does not tell you which values are duplicated.

21. What is the purpose of the GROUP BY clause?

GROUP BY groups rows having the same values in one or more columns. It is commonly used with aggregate functions such as COUNT(), SUM(), AVG(), MIN(), and MAX().

For example:

SELECT department, COUNT(*)
FROM employees
GROUP BY department;

This returns the number of employees in each department.

22. What is a Super Key in MySQL?

A super key is one or more columns that can uniquely identify a row in a table.

For example, if id uniquely identifies a user, then id is a super key. A combination such as (id, email) can also be a super key, even though the additional email column may not be necessary.

A candidate key is a minimal super key, while a primary key is the candidate key selected as the main identifier for the table.

23. What are the different normalization forms?

  • First Normal Form (1NF): Each column contains atomic values, and repeating groups are removed.
  • Second Normal Form (2NF): The table is in 1NF and non-key attributes depend on the entire candidate key rather than only part of a composite key.
  • Third Normal Form (3NF): The table is in 2NF and non-key attributes do not depend on other non-key attributes.
  • Boyce-Codd Normal Form (BCNF): A stricter version of 3NF where every determinant is a candidate key.

Higher normal forms also exist, but 1NF, 2NF, 3NF, and BCNF are commonly discussed in database interviews.

24. What is the default MySQL port number?

The default port used by MySQL is 3306.

25. What is the purpose of the LIMIT clause in MySQL?

The LIMIT clause restricts the number of rows returned by a query.

For example:

SELECT * FROM users LIMIT 10;

This returns up to 10 rows.

It is commonly used for limiting results and implementing pagination.

26. What is a View in MySQL?

A view is a virtual table based on a SELECT query. It does not normally store the result as a separate copy of the underlying data.

Views can be useful for simplifying complex queries, hiding unnecessary columns, and controlling access to certain data.

27. What is the purpose of the HAVING clause?

HAVING is used to filter grouped results, usually after GROUP BY.

For example:

SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

Here, only departments having more than five employees are returned.

The main difference is that WHERE filters rows before grouping, while HAVING filters groups after aggregation.

28. How can you prevent SQL injection in MySQL?

The most important protection is to use prepared statements or parameterized queries instead of directly inserting user input into SQL statements.

Other good security practices include:

  • Validate input according to the expected format.
  • Give database users only the permissions they actually need.
  • Avoid building SQL queries by concatenating user input.
  • Use appropriate application and database security controls.
  • Keep the database server and software updated.

Input escaping can have a role in specific situations, but it should not replace parameterized queries.

29. How can you back up a MySQL database?

A MySQL database can be backed up using tools such as mysqldump, MySQL Shell, or MySQL Workbench.

For example, mysqldump can export database structures and data into a SQL file that can later be used to restore the database.

For production systems, backup strategies should also consider automated backups, retention, recovery testing, and the size of the database.

30. How can you monitor MySQL performance?

MySQL performance can be monitored using several tools and features, including:

  • Performance Schema: Collects server performance information.
  • EXPLAIN: Helps analyze query execution plans.
  • MySQL Enterprise Monitor: Provides database monitoring capabilities.
  • Server and database metrics: CPU, memory, disk I/O, connections, and query execution time can be monitored.
  • Third-party monitoring tools: These can be used where appropriate.

Regular monitoring can help identify slow queries, excessive resource usage, locking issues, and other performance problems.

Conclusion

These MySQL interview questions cover the fundamentals that are commonly useful for PHP, Laravel, backend, and database-related interviews. Along with learning the definitions, it is a good idea to practice SQL queries, joins, indexes, constraints, transactions, and query optimization with real examples.