MySQL interview questions and answers in 2024

If your aim is to secure a position as a successful MySQL developer at a leading companies, or to build a team of exceptional MySQL developers, you’ve come to the right place. To help you prepare for your MySQL interview, we’ve created a list of interview questions that you can ask or expect to be asked.

1. What is MySQL?

MySQL is an open-source relational database management system (RDBMS) based on Structured Query Language (SQL). It is widely used for web applications.

2.What is a database?

A database is an organized collection of data stored and accessed electronically, typically managed by a database management system (DBMS)

3.How do you create a database in MySQL?

A database can be created using the `CREATE DATABASE` SQL statement:

CREATE DATABASE mydatabase;

4.What is a table in a database?

A table is a collection of related data entries organized in rows and columns, where each row represents a record and each column represents a field.

5.How can you insert data into a MySQL table?

Data can be inserted using the `INSERT INTO` SQL statement:

INSERT INTO users (name, email) VALUES ('John', 'sleepy@example.com');

6.What is normalization?

The normalization is a process of organizing the database's structure to reduce data redundancy and data integrity.

This will eliminate anomolies in the data and create better database design by dividing larger tables into smaller table. Below are the various types of normalization.

1NF

2NF

3NF

BCNF

4NF

5NF

7.What is mysql binary log and how do you use it?

Mysql binary log is log file. this is used to record all changes to the databases such as INSERT, DELETE and UPDATE statements as well as DDL statements.

We can use binary log for various purpose, such as 

  • Replication
  • Point-in-time recovery
  • Auditing and debugging
8.What is database schema?
It defines blueprint or skeleton structure that represent logical configuration of a database.

9.What is primary key?
The primary is key uniquely identifiy the row in the table. 
It must contains unique values. It should not contain null values.
The table should have only one primary key.

10.What is foreign key constraint?

  • The foreign key is used to link two tables together.
  • The foreign key is a field in one table that refers to the PRIMARY KEY of the other table.
  • It maintains referential integrity and control CASCADING actions and support composite keys.

11.What are the different types of JOINs in SQL?

The main types of JOINs are:

      - INNER JOIN

      - LEFT JOIN (or LEFT OUTER JOIN)

      - RIGHT JOIN (or RIGHT OUTER JOIN)

      - FULL JOIN (or FULL OUTER JOIN)

12.How do you update records in a MySQL table?

Records can be updated using the `UPDATE` statement:

UPDATE users SET email = 'john_new@example.com' WHERE name = 'John';

13.What is an index in MySQL?
  • An index is a data structure that improves the speed of data retrieval operations. This will speed up the database search operations. 
  • The maximum limit of indexed columns that can be created for any table is 16.
  • Dont define too many indexes in the tables. It will slow down the DB operations(create, edit, update, read)
14.What are aggregate functions in SQL? 
Aggregate functions perform calculations on a set of values and return a single value. Examples include `COUNT()`, `SUM()`, `AVG()`, `MAX()`, and `MIN()`.

15.Explain the ACID properties in databases.
ACID stands for:
Atomicity: Transactions are all-or-nothing.
      - Consistency: Transactions must bring the database from one valid state to another.
      - Isolation: Transactions are executed independently.
      - Durability: Once a transaction is committed, it remains so even in case of a system failure.

16. What is the purpose of the `GROUP BY` clause?
The `GROUP BY` clause groups rows that have the same values in specified columns into summary rows, often used with aggregate functions.

17. How do you use the `HAVING` clause?

 The `HAVING` clause is used to filter records after a `GROUP BY` operation. It is similar to the `WHERE` clause but is applied to aggregate results.

SELECT COUNT() FROM users GROUP BY age HAVING COUNT() > 1;

18.What is a view in MySQL?

A view is a virtual table based on the result of a SELECT query. It can simplify complex queries and enhance security by restricting access to certain data.

19. How do you back up a MySQL database?

To perform a backup in MySQL, you can use the mysqldump command-line utility to create a backup file containing the database schema and data. You can also use other tools such as MySQL Enterprise Backup or Percona XtraBackup to perform online or incremental backups.

You can back up a MySQL database using the `mysqldump` command:

mysqldump -u username -p database_name > backup.sql


20. What are transactions, and how do you use them in MySQL?

 Transactions are a sequence of operations performed as a single unit of work. They ensure data integrity. You can use `START TRANSACTION`, `COMMIT`, and `ROLLBACK` for transaction management.

21.What is the `EXPLAIN` statement used for?

The `EXPLAIN` statement is used to obtain information about how MySQL executes a query. It shows the query execution plan and can help optimize performance.

22. How do you optimize mysql query performance?
There are several methods to optimize a MySQL query:

Limit the retrieved data: Use the SELECT statement with specific columns rather than using SELECT * to retrieve only the necessary data. Also, consider using the LIMIT clause to reduce the number of records returned by the query.

Use proper indexing: Create indexes on frequently searched or referenced columns to increase search speed and improve query performance. However, use them judiciously, as having too many indexes can slow down insertions and updates.

Apply appropriate constraints: Use constraints, such as NOT NULL, to prevent unnecessary NULL comparisons, which can slow down the query execution.

Use EXPLAIN to analyze the query: Utilize the EXPLAIN keyword to analyze the query execution plan and look for potential bottlenecks or areas to improve.

Use stored procedures: Stored procedures can be more efficient than individual queries because they reduce network traffic and processing load. They also allow for more efficient use of the MySQL query cache.

Join tables using appropriate JOIN types: Choose the correct JOIN type based on the specific use case. For example, prefer INNER JOIN over LEFT JOIN or RIGHT JOIN when only interested in matched rows from both tables.

Optimize database schema: Balance the needs of normalization and denormalization based on the requirements. Normalization can reduce data redundancy and improve data integrity, while denormalization can speed up performance for certain read-heavy workloads.

Filter data earlier: Use the WHERE clause as early as possible in the query to filter the necessary data and minimize the amount of data that needs to be processed in subsequent parts of the query.

Optimize subqueries: If possible, rewrite subqueries as joins or use derived tables to improve query efficiency.

Use the query cache: If your application relies on retrieving the same data repeatedly, take advantage of MySQL's query cache to speed up query execution times.

23.What are triggers in MySQL?

Triggers are stored programs that are automatically executed in response to specific events on a particular table, such as INSERT, UPDATE, or DELETE.

24.What is a recursive query?

A recursive query is a query that refers to itself. It is commonly used to work with hierarchical data structures like organizational charts.

25.How do you implement full-text search in MySQL?

Full-text search can be implemented using FULLTEXT indexes on text columns and utilizing the `MATCH()` and `AGAINST()` functions.

26.How can you prevent SQL injection?

SQL injection can be prevented by using prepared statements and parameterized queries. Always validate and sanitize user input.

27.How do you use the `UNION` operator in SQL?

The `UNION` operator combines the result sets of two or more SELECT queries, removing duplicates:

      ```sql

      SELECT name FROM users

      UNION

      SELECT name FROM admins;

      ```

28.What is data replication in MySQL and how do you setup?

Data replication is the process of copying and maintaining database objects in multiple databases, enhancing availability and reliability.  

To set up replication in MySQL, you can use the MASTER and SLAVE statements to define the master and slave servers and the replication configuration. Replication allows you to maintain multiple copies of the same database and keep them in sync in real-time. Replication is useful for improving data availability and disaster recovery.

29. How do you implement data partitioning in MySQL?

Data partitioning can be implemented by dividing a table into smaller, more manageable pieces, either by range, list, hash, or key partitioning, to improve performance.

30. What are the differences between SQL and NoSQL databases?

SQL databases are relational and use structured schema, while NoSQL databases are non-relational, flexible, and can handle unstructured data. SQL databases use ACID transactions, while NoSQL databases prioritize scalability and performance.

31.How would you troubleshoot a slow MySQL query?

Troubleshooting involves:

      - Analyzing the query execution plan with `EXPLAIN`.

      - Checking for proper indexing.

      - Reducing the dataset using `LIMIT`.

      - Avoiding SELECT  and using specific fields.

32. How do you handle concurrency in MySQL?

Concurrency can be handled using transactions, locking mechanisms (like row-level locking), and isolation levels to prevent data inconsistency.

33. What is profiling and how do you use it? 

MySQL profiling is a technique for tracking and analyzing query performance in order to discover sluggish queries, optimize them, and monitor overall database performance. To enable profiling, you need to set the profiling variable to a non-zero value, run your queries, and then examine the results using the SHOW PROFILES and SHOW PROFILE commands.

34.What is partitioning and how do you use it?

Partitioning in MySQL is a technique for dividing a huge table into smaller, more manageable sections based on a partitioning key in order to enhance query performance and manageability, particularly for large datasets. There are various partitioning techniques available such as range, list, hash, or key partitioning.

35. What is mysql query caching and how do you use it?

The Query Cache is a technique that caches the results of SELECT queries so that following similar queries may be delivered from the cache rather than performing them again, which can assist to improve speed, particularly for read-heavy workloads. To enable the query cache, set the query_cache_size variable to something other than 0.

36. List different ways of perform mysql backup 

There are several ways to perform a MySQL backup, each offering a different level of data consistency, export options, and performance. It's important to choose the backup method that best meets your needs for consistency, recovery time, and complexity. Regularly test backups to ensure reliable recovery when needed.

Here are some of the most common methods:

mysqldump: This command-line utility comes with MySQL and is widely used for creating logical backups. It exports the database schema and data in the form of SQL statements, which can be easily restored by executing them in the MySQL server. Example usage:
mysqldump -u username -p your_database_name > backup_file.sql

mysqlhotcopy: This utility is designed for backing up MyISAM and ARCHIVE tables. It uses file system-level operations to create a consistent snapshot of the tables. The main advantage is its speed, but it's limited in terms of supported storage engines and backup flexibility.

MySQL Enterprise Backup: This is a commercial solution provided by MySQL, offering a wide range of backup features, such as online backups, incremental backups, and partial backups. It is designed for InnoDB and offers better performance and flexibility than mysqldump or mysqlhotcopy.

MySQL Workbench: This graphical management tool provides a user-friendly way to create logical backups using an Export Data feature. This approach is suitable for smaller databases or less frequent backups and is more accessible for users who are not comfortable with command-line utilities.

File System-level Backup: This method involves manually copying the database files from the MySQL data directory to a backup location. It's essential to ensure that the server is stopped or the tables are locked to create a consistent backup. This method allows for fast restoration but involves more manual efforts.

Replication and Cloning: You can use MySQL replication or cloning to create a consistent backup of the database on another server. The replicated server acts as a live copy of the original server, which can be used for backup and disaster recovery purposes.

Third-Party Tools: Several third-party backup tools, such as Percona XtraBackup or Navicat for MySQL, offer additional features and interfaces to perform MySQL backups more efficiently or with more options.

37.How do you monitor mysql performance?

MySQL Enterprise Backup is a commercial solution offered by MySQL (owned by Oracle) that provides a comprehensive, easy-to-use, and efficient way to perform hot, online, and incremental backups of MySQL databases. It is tailored to work seamlessly and optimally with InnoDB storage engine, though it also supports other storage engines such as MyISAM, NDB, and others.

Some of the key features of MySQL Enterprise Backup include:

Online Backups: This tool allows for taking backups without locking the tables, ensuring minimal impact on the performance or availability of the database, and doesn't require stopping the server to create a consistent snapshot.

Incremental Backups: Instead of taking full backups every time, MySQL Enterprise Backup enables incremental backup functionality. This feature only backs up the changes made since the last backup, reducing storage requirements and backup time.

Partial Backups: MySQL Enterprise Backup lets you selectively backup specific tables, tablespaces, or databases, giving you the flexibility to maintain multiple smaller backups scoped to specific data sets.

Compression and Encryption: Backups can be compressed to save storage space and reduce backup time, and they can also be encrypted to ensure data security during transport or storage in backup repositories.

Backup Verification: MySQL Enterprise Backup includes features to verify the backups for consistency and correctness, ensuring the backups can be relied upon for recovery.

Optimized for InnoDB: The tool is specifically designed to work optimally with the InnoDB storage engine and supports advanced features like InnoDB tablespace management and optimization.

Point-in-Time Recovery: The tool allows for point-in-time recovery, which means you can restore the database to a specific point in time by applying the necessary incremental backups and transaction logs.

To use MySQL Enterprise Backup, you need to have a MySQL Enterprise Edition subscription, which provides access to the tool, along with other enterprise features, such as MySQL Enterprise Monitor, MySQL Audit, MySQL Firewall, and technical support.

38.What are some common performance issues in mysql and how do you address it?

Some common performance issues in MySQL include slow queries, inefficient database schema design, inadequate server resources, and insufficient indexing. To address these issues, we can optimize your queries and database schema, allocate more resources to your server, and use proper indexing strategies.

39.What is mysql slow query log and how do you use it ?

The MySQL slow query log is a log file that captures queries that take longer than a specified amount of time to execute. This log helps database administrators identify poorly performing or inefficient queries that may be impacting the overall database performance. Monitoring and optimizing slow queries is critical for maintaining a fast and responsive database system.

To use the MySQL slow query log, follow these steps:

Enable the slow query log: You'll first need to enable and configure the slow query log in the MySQL configuration file (usually my.cnf or my.ini). Add or modify the following lines in the configuration file:

slow_query_log = ON

slow_query_log_file = /path/to/slow_query_log_file.log

long_query_time = 2

Here, slow_query_log_file is the path to the output log file, and long_query_time is the threshold for logging slow queries (in seconds). In this example, queries taking over 2 seconds to execute will be logged.

Restart the MySQL server: After modifying the configuration file, you'll need to restart the MySQL server for the changes to take effect.

Analyze the slow query log: After enabling the slow query log, monitor the specified log file to identify slow queries. You can use command-line utilities like grep, awk, or sort to filter and analyze data. Additionally, third-party tools like Percona's pt-query-digest offer more advanced analysis features.

Optimize slow queries: Once problematic queries have been identified, you can optimize them by rewriting the query, creating or modifying indexes, or making changes to the database schema. After optimizing the query, continue monitoring the slow query log to ensure the changes have improved performance.

40.What are some common data migration strategies in mysql?

Data migration is the process of transferring data from one system, format, or structure to another. In MySQL, data migration often involves moving data between different servers, database systems, or table structures. Here are some common data migration strategies in MySQL:

  • Using mysqldump mysqldump is a utility provided by MySQL that creates a logical backup of a database or table, exporting the SQL statements required to rebuild the data. This utility is useful for migrating smaller databases and tables.

Image 09-06-23 at 8.07 PM.webp

  • Using SELECT INTO OUTFILE and LOAD DATA INFILE These MySQL statements can be used to export data from the source table into a CSV or TSV file and then import it into the destination table.

Export data from the source table:

Image 09-06-23 at 8.10 PM.webp

Import data into the destination table:

Image 09-06-23 at 8.10 PM-2.webp

  • Using MySQL Workbench MySQL Workbench provides a graphical interface and advanced tools for data migration, including schema and data transfer between different MySQL servers and databases. MySQL Workbench is appropriate for more complex migration tasks, including those involving changes to the table structure and data transformations.
  • Using custom scripts In some cases, you might need to write custom scripts using programming languages (e.g., Python, PHP, or Java) to handle more specific data migration scenarios. These scripts can utilize MySQL connectors to connect to both source and target databases, retrieve data, apply transformations, and then insert data into the target database.
  • ETL tools Extract, Transform, Load (ETL) tools are specifically designed to handle large-scale data migration and transformation tasks. These tools, such as Apache NiFi, Talend, or Microsoft SQL Server Integration Services (SSIS), provide a wide range of advanced features to manage the entire data migration process, including pre- and post-migration tasks.

During data migration, it's essential to maintain data integrity, handle exceptions, and monitor the process closely. Additionally, thorough testing should be conducted after the migration to ensure that the data has been correctly transferred and transformed before deploying the new system in production.

40.Can you describe a project where you used PHP and MySQL together?

 (Provide a brief overview of a relevant project, detailing the objectives, technologies used, and your specific contributions.)

Example:

I worked  mainly on Analytics and Reports component in marketing automation application.

I used php and mysql for report generation and built report queries based on pivot table format. like getting data as aggregated format using when case, multiple joins and temp tables

Mainly worked on db query optimizations since the data volume increasing day by day. 

Basically this leads to long running queries. 

I used the explain extended plan to evaluate query plans which helped me to optimize the index and rewrite the queries for better performance. 

This improved query execution time and improved user experience. 

I worked on  the data dicrepancies for multiple customers by iodku feature in php mysql. this helped the customer to have the proper reporting data . 


41.What challenges did you face while integrating PHP with MySQL?

 - Answer: Challenges can include managing database connections, handling errors, optimizing queries, or ensuring data integrity during transactions.

Example:

Optimizing Queries: 

As the application grew, some SQL queries became slow due to increased data volume. Identifying the bottlenecks was challenging. I used the EXPLAIN statement to analyze query execution plans, which helped me optimize indexes and rewrite queries for better performance. This significantly reduced load times and improved user experience.

Ensuring Data Integrity: 

Maintaining data integrity during transactions posed another challenge, especially in scenarios where multiple users interacted with the database simultaneously. I implemented transactions using the BEGIN, COMMIT, and ROLLBACK statements to ensure that all parts of a process completed successfully or none at all. This was particularly important for operations involving order processing, where partial data could lead to inconsistencies.

42. How do you keep your PHP and MySQL skills up to date?

    - Answer: Keeping skills up to date can involve:

      - Reading documentation and tutorials.

      - Participating in online courses and webinars.

      - Contributing to open-source projects.

43. Explain CASCADE and RESTRICT

The CASCADE and RESTRICT keywords define how the database should handle a situation involving foreign keys when a parent record is deleted or updated:

CASCADE: When the parent record is deleted or updated, the corresponding child records are automatically deleted or updated.
RESTRICT: Deletion or update of the parent record is prevented if there are child records.

Example:

CREATE TABLE authors (

    author_id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100) NOT NULL

);

CREATE TABLE books (

    book_id INT AUTO_INCREMENT PRIMARY KEY,

    title VARCHAR(100) NOT NULL,

    author_id INT,

    FOREIGN KEY (author_id) REFERENCES authors(author_id) 

        ON DELETE CASCADE

);


44. Difference between count(*) and count(column_name)

The difference between COUNT(*) and COUNT(column_name) in MySQL is how NULL values are handled:

COUNT(*): Counts all rows in a table (or with a given condition), including NULLs.
COUNT(column_name): Counts rows with non-NULL values in the specified column (or with a given condition).

45.

Comments