Mysql Viva
Mysql Viva
Mysql Viva
structured tabular format using rows and columns. It uses Structured Query Language (SQL) for
accessing, managing, and manipulating databases. It was originally developed by MySQL AB, a Swedish
company, and is now owned by Oracle Corporation. It’s known for its high performance, reliability,
and ease of use, making it one of the most popular databases in the world.
Here, we’ll cover 50+ MySQL Interview Questions with answers that are asked in Data Analyst/SQL
Developer Interviews at MAANG and other high-paying companies. Whether you are a fresher or an
experienced professional with 1, 5, or 10+ years of experience, this article gives you all the confidence
you need to ace your next interview.
Table of Content
MySQL Interview Questions And Answers for Freshers
Intermediate MySQL Interview Questions and Answers
Advanced MySQL Interview Questions For Experienced
MySQL Interview Questions And Answers for Freshers
1. What is MySQL and How does it differ from other relational databases?
MySQL is an open-source relational database management system (RDBMS) that is widely used for
managing structured data. It utilizes SQL (Structured Query Language) for querying and managing
data. MySQL is known for its reliability, scalability, and performance, making it a popular choice for
various applications
2. How to create a database in MySQL?
To create a database in MySQL, we can use the CREATE DATABASE statement followed by the name
we want to give to our database. For example:
CREATE DATABASE mydatabase;
3. Difference between CHAR and VARCHAR data types.
CHAR: Fixed-length character data type where the storage size is predefined. Trailing spaces are
padded to reach the defined length.
VARCHAR: Variable-length character data type where the storage size depends on the actual data
length. No padding of spaces is done.
4. Explain the differences between SQL and MySQL?
SQL MySQL
It is a structured query language that manages the It is a relational database management system that
relational database management system. uses SQL.
MySQL is an open-source platform. It allows access
It is not an open-source language.
to anyone.
It doesn’t support XML and any user defined
SQL supports XML and user defined functions.
functions
SQL can be implemented in various RDBMS such as MySQL is a specific implementation of an RDBMS
PostgreSQL, SQLite, Microsoft SQL Server, and that uses SQL for querying and managing
others. databases.
SQL itself is not a product and doesn’t have a MySQL is open-source and available under the
license. It’s a standard language. GNU General Public License (GPL).
5. What is the MySQL server’s default port?
3306 is MySQL server‘s default port.
6. How can we learn batch mode in MySQL?
Below is the syntax used to run batch mode.
mysql <batch-file>;
mysq <batch-file> mysql.out
7. How many different tables are present in MySQL?
There are 5 types of tables present in MySQL.
Heap table
merge table
MyISAM table
INNO DB table
ISAM table
8. What are the differences between CHAR and VARCHAR data types in MySQL?
Storage and retrieval have been different for CHAR and VARCHAR.
Column length is fixed in CHAR but VARCHAR length is variable.
CHAR is faster than VARCHAR.
CHAR datatype can hold a maximum of 255 characters while VARCHAR can store up to 4000
characters.
9. What is Difference between CHAR_LENGTH and LENGTH?
LENGTH is byte count whereas CHAR_LENGTH is character count. The numbers are the same for Latin
characters but different for Unicode and other encodings.
Syntax of CHAR_LENGTH:
SELECT CHAR_LENGTH(column_name) FROM table_name;
Syntax of LENGTH:
SELECT LENGTH(column_name) FROM table_name;
10. What do you understand by % and _ in the like statement?
‘_’ corresponds to only one character but ‘%’ corresponds to zero or more characters in the LIKE
statement.
11. How many index columns can be created in a table?
There are 16 indexed columns can be created in a table.
12. What are string types available for columns?
There are six string types available for the column.
SET
BLOB
TEXT
ENUM
CHAR
VARCHAR
13. Explain the main difference between FLOAT and DOUBLE?
FLOAT stored floating point number with 8 place accuracy. The size of FLOAT is 4 bytes.
DOUBLE also stored floating point numbers with 18 place accuracy. The size of DOUBLE is 8 bytes.
14. Explain the differences between BLOB and TEXT.
BLOB:
A BLOB is a large object in binary form that can hold a variable amount of data. Sorting and comparing
in BLOB values are case-sensitive.
There are four types of BLOB.
TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB
TEXT:
Sorting and comparison are performed in case-insensitive for TEXT values. we can also say a TEXT is
case-insensitive BLOB.
There are four types of TEXT.
TINYTEXT
TEXT
MEDIUMTEXT
LONGTEXT
15. Explain the difference between having and where clause in MySQL.
WHERE statement is used to filter rows but HAVING statement is used to filter groups.
GROUP BY is not used with WHERE. HAVING clause is used with GROUP BY.
16. Explain REGEXP?
REGEXP is a pattern match where the pattern is matched anywhere in the search value.
For more detail you refer to our MySQL | Regular expressions Article.
17. How can we add a column in MySQL?
A column is a series of table cells that store a value for table’s each row. we can add column by using
ALTER TABLE statement.
ALTER TABLE tab_name
ADD COLUMN col_name col_definition [FIRST|AFTER exist_col];
18. How to delete columns in MySQL?
We can remove columns in MySQL by using ALTER TABLE statement.
Syntax:
ALTER TABLE table_name DROP COLUMN column1, column2….;
19. How to delete a table in MySQL?
We can delete a table by using DROP TABLE statement. This statement deletes complete data of table.
DROP TABLE table-name;
20. How are mysql_fetch_array() and mysql_fetch_object() different from each another?
mysql_fetch_array() Gets a result row as a related array or a regular array from database.
mysql_fetch_object gets a result row as an object from the database.
21. How to get the top 10 rows?
The following query will be used to get top 10 rows.
SELECT * FROM table_name LIMIT 0,10;
22. How does NOW() differ from CURRENT_DATE()?
current year, month, and date with hours, minutes, and seconds is shown by using NOW() command
while CURRENT_DATE shows current year current month, and current date.
Syntax:
SELECT NOW();
SELECT CURRENT_DATE();
23. What is the use of the ‘DISTINCT’ keyword in MySQL?
the DISTINCT keyword allows for the removal of all duplicate records and the retrieval of unique
records. The DISTINCT keyword is used with the SELECT statement.
Syntax:
SELECT DISTINCT colu1, colum2..
FROM table_name;
24. Which storage engines are used in MySQL?
Storage engines are also called table types. Data is stored in a file using multiple techniques.
Below are some techniques.
Locking Level
Indexing
Storage mechanism
Capabilities and functions
25. How to create a table in MySQL?
The CREAT TABLE command will be used to create a table in MySQL.
Syntax:
CREATE TABLE ‘Employee’ (‘Employee_Name’ VARCHAR(128), ‘Employee_ID’ VARCHAR(128),
‘Employee_Salary’ VARCHAR(16), ‘Designation’ CHAR(4)) ;
26. How to insert data in MySQL table?
We can add data to a table using the INSERT INTO statement .
Syntax:
INSERT INTO table_name ( field1, field2, field3 )
VALUES ( value1, value2, value3 );
Intermediate MySQL Interview Questions and Answers
27. Write a statement to find duplicate rows In the MySQL table?
The below statement is used to find duplicate rows.
SELECT Table_Name, Category
FROM Product
GROUP BY Name, Category
HAVING COUNT(id) > 1;
28. What types of relationships are used in MySQL?
There are three types of relationships used in MySQL.
One-to-one: Elements with a one to one relationship can be included as columns in the table.
One-to-many: One to many or many to one relationships both are same. It will occur when one row in
a table is related to multiple rows in different table.
Many-to-many: Many rows in a table are related to many rows in different table is called many to
many relationship.
29. How to insert Date in MySQL?
We can use INSERT statement to insert date in MySQL table. MySQL default date format is YYYY-MM-
DD. Automatic MySQL consist many data types to store dates.
DATE
DATETIME
TIMESTAMP
YEAR
Syntax:
INSERT INTO table_name (column_name, column_date) VALUES (‘DATE: Manual Date’, ‘2023-5-20’);
30. What is join? Tell different join in MySQL.
Joins are used to connect two or more tables. It returns only same values in all tables.
There are four different ways to join MySQL tables.
Inner Join
left Join
Right Join
Full Join
31. What is a primary key? How to drop the primary key in MySQL?
A primary key in MySQL is a single field or a group of fields that are used to uniquely identify each
record in a table. A primary key cannot be null or empty. ALTER TABLE statement is used to delete a
primary key from a table.
Syntax:
ALTER TABLE table_name DROP PRIMARY KEY;
32. What is a heap table in MySQL?
A heap table is usually used for temporary and fast temporary storage.
BLOB or TEXT fields are not permitted in the heap table.
comparison operator like =, <,>, = >,=< can be used only.
Heap table didn’t support the AUTO_INCREMENT command.
Indexes should be NOT NULL in the heap table.
33. What is the main difference between the primary key and the candidate key?
The primary key uniquely identified each row of a table. only one primary key is available for a table.
A primary is also a candidate key.
Candidate key that can be used for all foreign key references.
For mor detail you can see: Difference between Primary and Candidate Key
34. What is the difference between DELETE and TRUNCATE commands in MySQL?
DELETE Command is used to delete rows from the table depending on given the condition. TRUNCATE
command is used to DELETE all rows from the table. DELETE command is a Data Manipulation
Language command. TRUNCATE command is a Data Definition Language command.
For More detail you can see : Difference between DELETE and TRUNCATE
35. What is InnoDB?
A SQL storage database is called InnoDB database. The InnoDB offers ACID transactions, row-level
locking, and foreign key support. InnoDB is owned by Oracle Corporation.
36. What is the difference between UNION and UNION ALL in MySQL?
During combining the results of more than one SELECT statement, the UNION operator deletes
duplicate rows between the various SELECT statements. The UNION ALL also combines the result set
of more than one SELECT statement, but it does not delete duplicate rows.
37. What is a ‘timestamp’ in MySQL?
In MySQL, When a row is added to or updated in a table, a data type “timestamp” automatically
records the time.
38. What is the use of ENUMs in MySQL?
ENUM is a string object that can be used when creating tables to specify a set of predefined values.
CREATE table size(name ENUM(‘Small’, ‘Medium’, ‘Large’);
For more detail refer to those article on Enumerator (Enum) in MySQL
39. How can you control max size of heap in MySQL?
MySQL config variable max_heap_table_size can be used to control the max size of heap.
Syntax:
SET max_heap_table_size = M
40. What is a view? How to create a view?
A database object that has no value is called view. Rows and columns exist in a view. A view is virtual
table. it is created by combining one or more tables. The difference of a view and a table is that views
are definition that build on other tables. If the underlying table changes, the View will also reflect
those same changes.
The below syntax is used to create a view.
Syntax:
CREATE VIEW view_name AS
SELECT columns
FROM tables
[WHERE conditions];
41. Where MyISAM table will be stored and also give MyISAM formats of storage?
Every MyISAM table is stored on disk.
There are three storage formats can be used .
The .frm file can be used to store table definition.
The .MYD( MYData) extension can be used for data files.
The .MYI(MYIndex) extension can be used to Index files.
42. How can we save images in MySQL?
In MySQL, Blobs can be used to store images. All database images are first converted into blobs then
saved and then they will be added to the database, and finally, it will later be stored on the disk.
43. What are trigger and how many TRIGGERS are available in MySQL table?
A trigger is a procedural code in a database. Triggers are automatically triggered when specific events
occur on a particular table. During column updating triggers are invoked automatically.
SIX triggers are available in MySQL table.
BEFORE INSERT
AFTER INSERT
BEFORE UPDATE
AFTER UPDATE
BEFORE DELETE
AFTER DELETE
For more detail you can see: Different types of MySQL Triggers (with examples) – GeeksforGeeks
44. What are the different characteristics of MySQL MyISAM Static and MyISAM Dynamic?
Width of all fields is fixed in MyISAM Static table whereas width of all fields is not fixed in MyISAM
Dynamic. In MyISAM Dynamic table width will be like TEXT, BOLD, etc.
In case of corruption MyISAM static table is easy to store.
MySQL Interview Questions For Experienced
45. What are Access Control Lists?
A list of permissions known as an Access Control List is connected to an object. It is MySQL server
security model helps in troubleshooting issues like users being unable to connect. MySQL holds the
ACL’s cached in memory. ACL’s also called grant tables. MySQL verifies the authentication data and
permissions against the ACLs. It predetermined order whenever a user tries to log in or execute a
command.
46. What is Normalization and list the different types of normalization?
Normalization is used to avoid duplication and redundancy. it is a process of organizing data. There
are many normal forms of normalization. which are also called successive levels. The first three regular
forms are sufficient.
First Normal Form (1NF): There are no repeating groups within rows.
Second Normal form(2NF): Value of every supporting column depending on the whole primary key.
Third Normal Form(3NF): It depends only on the primary key and no other value of non-key column.
47. What are various ways to create an index?
There are many options to create an index as below:
T-SQL statements can be used to create an index.
The SQL Server Management Studio is available for use. we can use this to browse to the table where
the index will be created, and then right-click on the Indexes node. We must select the New Index
option over here.
We can identify the index indirectly by specifying the PRIMARY KEY and the UNIQUE constraint in the
CREATE TABLE or ALTER TABLE statement.
48. What are a clustered index and a non clustered index?
Cluster Index: An index type used to arrange data in a table is called a clustered index. The table’s
data are stored in a specific order based on the clustered index.
Non Cluster Index: A non-clustered index is also a type of index used to organize data in a table. The
table’s data are not stored in a specific order based on the non clustered index.
For more details, Check our latest article on Difference between Clustered and Non-clustered index.
49. How to validate emails using a single query?
We can use the regular expressions function (REGEXP_LIKE) to validate emails. Below is the example
of validate emails using a single query.
SELECT
Email
FROM
Vehicle
where NOT REGEXP_LIKE(Email, ‘[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}’, ‘i’);
For detail you can check our latest article on Regular expressions (Regexp).
50. How can you handle the –secure-file-priv in MySQL?
The MySQL Server is restricted from loading directories using the LOAD DATA INFILE command by the
-secure-file-priv option. Use the SHOW VARIABLES LIKE “secure_file_priv” command to view the
directory that has been configured.
There are two options to handle as below.
Either transfer your file to the directory that secure-file-priv specifies.
Or you can turn off secure-file-priv. This must be removed at the beginning and cannot be disabled
later.
1.
What is MySQL clustering?
MySQL clustering, also known as MySQL Cluster or MySQL NDB Cluster, is a high-availability, scalable,
and distributed database architecture that ensures fault tolerance and automatic data partitioning
across multiple nodes. It combines the MySQL server with the NDB (Network DataBase) storage
engine and provides real-time, in-memory storage with support for disk-based data as well.
The main components of MySQL Cluster are:
Data Nodes (NDB storage engine): These store the actual data in a partitioned and replicated manner,
ensuring data availability and redundancy. Each data node operates in parallel, which improves
performance and resilience.
MySQL Server Nodes (SQL Nodes): These are conventional MySQL servers that connect to the data
nodes, processing SQL queries and transactions for client applications.
Management Nodes: These nodes handle the configuration and orchestration of the cluster,
monitoring its health and managing node membership.
2.
What is the purpose of the SELECT statement in MySQL?
The SELECT statement is used to retrieve data from one or more tables in a MySQL database. It's a
fundamental SQL command and allows specifying various clauses like WHERE, GROUP BY, ORDER BY,
and HAVING to define which data should be returned and how it should be organized.
3.
What is normalization?
Normalization is the process of organizing a relational database's structure to reduce data
redundancy, improve data integrity, and optimize its performance. The primary goal of normalization
is to eliminate anomalies in the data and create a better database design by dividing large tables into
smaller, related ones and defining relationships between them.
Normalization involves organizing data into multiple tables, ensuring that each table serves a single
purpose and contains minimal redundant data. The process is carried out through a series of
normalization forms called normal forms, including First Normal Form (1NF), Second Normal Form
(2NF), Third Normal Form (3NF), Boyce-Codd Normal Form (BCNF), Fourth Normal Form (4NF), and
Fifth Normal Form (5NF). Each normal form has specific rules and builds on the previous one, leading
to a more organized and efficient database structure.
4.
What are the different data types in MySQL?
MySQL offers various data types to store different types of information. These data types are broadly
categorized into the following groups:
Numeric Data Types:
INT: A standard integer, signed range (-2,147,483,648 to 2,147,483,647) or unsigned range (0 to
4,294,967,295).
FLOAT: A floating-point number with single-precision (approximate values).
DECIMAL: A fixed-point, exact-number data type for storing precise values (such as monetary
amounts).
Date and Time Data Types:
DATE: Stores a date in the format 'YYYY-MM-DD'.
TIME: Stores a time in the format 'hh:mm:ss'.
String Data Types:
CHAR: A fixed-length string, with a specified maximum length between 1 and 255 characters.
VARCHAR: A variable-length string, with a specified maximum length between 1 and 65,535
characters.
Spatial Data Types: Spatial data types are used for storing geometric and geographic objects, such as
points, lines, and polygons.
5.
What is the difference between MySQL and SQL?
SQL (Structured Query Language) is a standardized programming language used to manage and
manipulate relational databases. It provides a consistent syntax and set of commands for creating,
querying, updating, and deleting data stored in relational databases. SQL is not tied to any specific
vendor or database system; instead, it serves as the foundation for working with various database
management systems.
MySQL, on the other hand, is an open-source Relational Database Management System (RDBMS) that
uses SQL to interact with the data stored in its databases. Developed by Oracle Corporation, MySQL is
one of the most popular RDBMS solutions due to its speed, reliability, and ease of use. MySQL
supports many database features, such as transactions, indexing, and stored procedures.
Note: Also read - SQL vs NoSQL Database
6.
How can you install MySQL on your system?
To install MySQL on your system, follow the steps for the specific operating system you are using:
For Windows:
Download the MySQL Community Edition installer for Windows from the official MySQL website:
https://dev.mysql.com/downloads/mysql/
Run the installer and choose the "Setup Type" according to your requirements. Common options are
"Server only," "Full," and "Custom."
Follow the installation wizard, and configure the MySQL server according to your preferences.
Complete the installation process, making sure to set your MySQL root password and any other user
credentials needed.
MySQL service should start running automatically after installation. You can manage it using the
MySQL Workbench or the command line.
For macOS:
Download the MySQL Community Edition installer for macOS from the official MySQL website:
https://dev.mysql.com/downloads/mysql/
Open the downloaded .dmg file and follow the installation instructions.
During installation, ensure to note the root password as it will be required to connect to your MySQL
server.
After completing the installation, you can manage MySQL server using the MySQL Workbench, the
command line, or macOS preferences.
For Linux (using APT on Debian/Ubuntu):
Update package information and install the MySQL APT repository
Install MySQL server and client packages
During the installation process, you will be prompted to set a password for the MySQL root user.
To manage the MySQL server, use the command line or install MySQL Workbench.
After installing MySQL, you can connect to the MySQL server using various client tools like the
command-line client (mysql), MySQL Workbench, or any other graphical tools of your preference.
7.
How can you start and stop the MySQL server?
To start and stop the MySQL server, you can use the appropriate commands for your operating system
or distribution. Here are some common examples for different platforms:
On Linux using systemd:
To start the MySQL server, run: sudo systemctl start mysqld
To stop the MySQL server, run: sudo systemctl stop mysqld
To check the status of the MySQL server, run: sudo systemctl status mysqld
On Linux using init.d:
If your distribution uses init.d scripts, you may use the following commands:
To start the MySQL server: sudo /etc/init.d/mysql start
To stop the MySQL server: sudo /etc/init.d/mysql stop
To check the status of the MySQL server: sudo /etc/init.d/mysql status
On macOS using Homebrew:
If you've installed MySQL using Homebrew, you can use the following commands:
To start the MySQL server: brew services start mysql
To stop the MySQL server: brew services stop mysql
To check the status of the MySQL server: brew services list
On Windows using services:
On Windows, MySQL is usually installed as a service. You can control the MySQL service using the
Services management console or the command prompt.
To start or stop the MySQL server via the Services management console:
Open the Services management console by typing services.msc in the search bar or the Run dialog
box.
Find the MySQL service, usually named MySQL, MySQLxx or MySQL Server (where "xx" represents the
version number).
Right-click on the service and select "Start" or "Stop" as needed.
To start or stop the MySQL server using the command prompt:
Open a command prompt with administrative privileges.
To start the MySQL server, run: net start MySQL
To stop the MySQL server, run: net stop MySQL
Each MySQL installation might have specific scripts, commands, or aliases to start or stop the server.
Always refer to the documentation for your particular installation or distribution for more detailed
information.
8.
What are DDL, DML, and DCL?
These specific MySQL interview questions and answers for experienced candidates can be helpful. DDL
stands for Data Definition Language in MySQL, and it is used in database schemas and descriptions to
determine how data should be stored in the database.
DDL Queries:
CREATE
ALTER
DROP
TRUNCATE
COMMENT
RENAME
DML stands for Data Manipulation Language and is used to manipulate data in databases. It largely
consists of standard SQL commands for storing, modifying, retrieving, deleting, and updating data.
DML Queries are:
SELECT
INSERT
UPDATE
DELETE
MERGE
CALL
EXPLAIN PLAN
LOCK TABLE
DCL stands for Data Control Language and encompasses instructions that deal with user rights,
permissions, and other database system controls.
List of queries for DCL:
GRANT
REVOKE
9.
What is the MySQL binary log, and how do you use it?
The MySQL binary log is a log file that records all changes to the database, such as INSERT, UPDATE,
and DELETE statements, as well as DDL statements. You can use the binary log for various purposes,
such as replication, point-in-time recovery, auditing, and debugging. To use the binary log, you need to
enable it and configure its settings.
10.
What is a query in MySQL?
A query in MySQL is a question or request for data or information from a MySQL database. In other
words, it is a way to interact with the database to perform various operations such as retrieving,
inserting, updating, or deleting data. Queries in MySQL are typically written using SQL (Structured
Query Language), which is a standardized language designed to communicate with relational
databases.
A query typically consists of SQL commands, expressions, and operators that define criteria for how
the database should search, filter, modify, or present the data.
11.
What is a database schema?
A database schema is the blueprint or skeleton structure that represents the logical configuration of a
database. It defines the organization and relationships between tables, as well as the columns, data
types, constraints, indexes, and other elements that comprise the database.
In essence, a database schema is a high-level representation of how data is organized, stored, and
related within the database. It plays a critical role in designing and maintaining database systems, as it
allows developers and administrators to visualize the overall structure, identify redundancies, ensure
normalization, and optimize performance.
Database schema can also be referred to as the formal definition of the database structure, which is
typically designed, managed, and queried using SQL (Structured Query Language).
12.
What is the difference between a primary key and a unique key?
Both primary key and unique key are used to enforce constraints and uniquely identify records in a
MySQL table. However, there are some differences between the two:
13.
What is a composite primary key?
A composite primary key, also known as a compound primary key or a concatenated primary key, is a
primary key that is composed of two or more columns in a table. It is used when a single column is not
sufficient to uniquely identify a row within the table.
By combining multiple columns, a composite primary key enforces uniqueness for the combination of
those column values and ensures that every row in the table can be uniquely identified. It also
maintains referential integrity in relationships with other tables that involve those columns.
14.
What is a foreign key constraint?
A foreign key constraint is a rule that enforces referential integrity within a relational database by
establishing a relationship between two tables. Specifically, the foreign key constraint ensures that the
values in the foreign key column(s) of one table must match the corresponding values of the primary
key column(s) in the related table.
A foreign key constraint has four main characteristics:
Establishes relationships: A foreign key in one table refers to the primary key of another table,
creating a parent-child (referenced-referencing) relationship between them.
Maintains referential integrity: By requiring a match between the foreign key and primary key values,
the constraint ensures that no orphan records are left in the child table, and that all child table rows
have a valid parent in the parent table.
Controls cascading actions: Foreign key constraints can define cascading actions such as CASCADE, SET
NULL, SET DEFAULT, and NO ACTION (or RESTRICT) for ON DELETE and ON UPDATE events. These
actions determine how the foreign key columns in the child table should be affected when a
referenced row in the parent table is deleted or updated.
Supports composite keys: A foreign key can reference multiple columns in the parent table's primary
key. In this case, the set of columns in the child table that forms the foreign key is called a composite
foreign key.
15.
How do you update data in a table in MySQL?
To update data in a MySQL table, you can use the UPDATE statement. The basic syntax for the
UPDATE statement includes the table name, the new values for each column, and a WHERE condition
to identify the row(s) to be updated:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
The WHERE clause is optional but highly recommended to avoid updating all rows in the table
unintentionally. When the WHERE clause is not used, the UPDATE statement will modify all rows in
the specified table.
16.
How do you delete data from a table in MySQL?
To delete data from a MySQL table, you can use the DELETE statement. The basic syntax for the
DELETE statement consists of the table name and a WHERE condition to identify the row(s) to be
deleted:
DELETE FROM table_name
WHERE condition;
The WHERE clause is optional but highly recommended to avoid deleting all rows in the table
unintentionally. When the WHERE clause is not used, the DELETE statement will remove all rows from
the specified table.
17.
How do you retrieve data from a table in MySQL?
To retrieve data from a table in MySQL, you use the SELECT statement. The basic syntax for the SELECT
statement includes the columns you want to retrieve, along with the table name and an optional
WHERE condition to filter the data:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
18.
What is the difference between a left join and a right join?
In MySQL, both LEFT JOIN and RIGHT JOIN are types of outer joins used to retrieve data from multiple
tables. The difference between the two lies in how they handle non-matching rows. Here's a
breakdown of their behavior:
19.
What is the difference between a full outer join and a cross join?
A FULL OUTER JOIN and a CROSS JOIN are two different types of join operations in SQL that achieve
different results.
A FULL OUTER JOIN combines the results of both LEFT JOIN and RIGHT JOIN, returning all rows from
both tables, even if there is no match between the joined columns. If there is no match, the resulting
row will have NULL values for the non-matching columns.
A CROSS JOIN, also known as a Cartesian product, returns every possible combination of rows from
the two joined tables, without any conditions. The result set will contain the total number of rows in
Table1 multiplied by the total number of rows in Table2.
20.
How do you add a new column to an existing table in MySQL?
To add a new column to an existing table in MySQL, you can use the ALTER TABLE statement followed
by the ADD COLUMN keyword and the column definition. For example, to add a new column called
"phone_number" to a table called "customers," you would use the following SQL statement: ALTER
TABLE customers ADD COLUMN phone_number VARCHAR(20). This will add a new column to the
"customers" table with a data type of VARCHAR and a maximum length of 20 characters.
21.
What is the difference between a NULL value and a zero value in MySQL?
In MySQL, a NULL value and a zero value are conceptually different and serve distinct purposes:
NULL value: A NULL value represents the absence of a value or an unknown value for a specific
column in a row. It signifies that the data is either missing, not applicable, or not collected. When a
column contains NULL, it means it has no value, and any comparison or operation involving NULL
typically results in NULL as well. For example, NULL + 1 = NULL.
Zero value: A zero value is an actual numeric value, indicating that the value of the specific column in
a row is zero. Zero participates in arithmetic and comparison operations like any other number. It is a
valid value for numeric data types such as INT, FLOAT, and DECIMAL and carries a distinct meaning
when used in calculations. For example, 0 + 1 = 1.
It's essential to understand the difference between NULL and zero values to ensure that the database
design, data integrity, and query results are accurate and meaningful.
22.
How do you rename a table in MySQL?
You can rename a table in MySQL using the RENAME TABLE statement. The syntax for renaming a
table is as follows:
RENAME TABLE old_table_name TO new_table_name;
Replace old_table_name with the current name of the table you want to rename, and
new_table_name with the new name you want to assign to the table. For example, to rename a table
called employees to staff, the command would be:
RENAME TABLE employees TO staff;
23.
What is a database transaction?
A database transaction is a logical work unit that includes one or more database activities. It is a
technique for combining many database operations into a single, atomic action that either succeeds or
fails as a whole. Transactions guarantee that all database activities are carried out as a single,
consistent unit, preserving data integrity.
24.
What is the difference between a clustered and a non-clustered index?
A clustered and a non-clustered index represent two types of indexing techniques used in database
systems, and they have different structures and use-cases:
25.
What is the difference between an inner join and a natural join?
The primary difference between an inner join and a natural join lies in the way they determine which
columns to use for joining and how they handle duplicates. Here's a detailed comparison:
26.
What is the difference between the CHAR and TEXT data types in MySQL?
The difference between the CHAR and TEXT data types in MySQL is their storage capacity, use case,
and how they handle character length:
Storage Capacity: CHAR is typically used for storing short strings with a fixed length. The maximum
length of a CHAR column can be 255 characters. On the other hand, TEXT is used for storing longer
text data with variable lengths. It can store up to 65,535 characters.
Use Case: CHAR is suitable for storing data with known and consistent lengths, such as postal codes or
country codes. TEXT is more appropriate for storing large chunks of text data, like paragraphs,
comments, or descriptions, that can have variable lengths.
Character Length Handling: CHAR is a fixed-length data type, which means that it always uses the
maximum defined length, and the unused characters are padded with spaces. In contrast, TEXT is a
variable-length data type, using only the space required for the stored data without any padding.
Remember that both CHAR and TEXT are non-binary string data types and store character data. If you
need to store binary data, you should use the corresponding binary types: BINARY for fixed-length and
BLOB for variable-length data.
27.
What is a subquery, and how do you use it in MySQL?
A subquery, also known as a nested query or inner query, is a query embedded within another query
in MySQL. Subqueries are enclosed within parentheses and can be used within various SQL clauses,
such as SELECT, FROM, WHERE, HAVING, and JOIN. They help in breaking down complex queries into
simpler parts, increasing readability, and providing more flexibility in data manipulation and retrieval.
Subqueries can return a single value (scalar subquery), a single row or column, or a table.
Here's an example of how you can use a subquery in MySQL:
Consider two tables: orders and customers. You want to find all customers who have placed an order
worth more than the average order value.
In this example:
The innermost subquery calculates the average order value across all orders.
The middle subquery selects a flag (1) for all orders where the customer ID matches and the order
value is greater than the calculated average.
The outer query returns the customer ID and customer name for all customers who have at least one
order that matches the conditions defined in the middle subquery.
28.
What is a correlated subquery?
A correlated subquery is one that is run once for every row returned by the outer query. The subquery
refers to a column from the outer query and utilizes it as a condition. A correlated subquery in MySQL
can be used to extract data from one table depending on the values of another table.
29.
How do you use the EXISTS operator in MySQL?
The EXISTS operator in MySQL is used in conjunction with a subquery to determine if the subquery
returns any rows. The EXISTS operator returns TRUE if the subquery produces at least one row and
FALSE if the subquery returns no rows. It is often used in the WHERE and HAVING clauses to filter
results based on the existence of related records in other tables or based on specific conditions.
Here's an example of how you can use the EXISTS operator in MySQL:
Consider two tables: employees and projects. You want to find all employees who are working on at
least one project.
30.
What is a temporary table, and how do you create one in MySQL?
A temporary table in MySQL is a non-permanent table that is created to store intermediate results for
complex queries or procedures, or used for a specific session or operation within the database.
Temporary tables are automatically dropped when the user's session ends or when the connection is
closed.
To create a temporary table in MySQL, use the CREATE TEMPORARY TABLE statement, followed by the
table name and its columns along with their data types and constraints. Here's an example:
4.
How do you perform a self-join in MySQL?
A self-join is a technique for combining rows from the same table based on a related column, typically
with the help of aliases. In MySQL, you can perform a self-join using the following syntax:
In this example, table_name is the table you wish to perform a self-join on. The AS keyword is used to
create aliases named A and B, which represent two instances of the same table in the query. The JOIN
clause specifies the condition for joining the instances based on a related column.
5.
What is the difference between a subquery and a join in MySQL?
The main difference between a subquery and a join in MySQL lies in their approach to combining data
from multiple tables.
Subquery: A subquery, also known as a nested query or inner query, is a query written within another
SQL query. It is used to retrieve intermediate results, which are then used by the outer query to
perform operations and return the final result set. Subqueries can be part of various clauses like
WHERE, HAVING, or FROM. They often involve more than one query execution, which can lead to
slower performance, especially for large data sets.
Example of a subquery:
Join: A join operation is used to combine related data from two or more tables based on a common
column or relationship (usually primary key to foreign key). Joins are often more efficient than
subqueries, as they can combine and filter data in a single query execution. There are different types
of joins available in MySQL, such as INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN.
Example of a join:
6.
What is a trigger, and how do you create one in MySQL?
A trigger is a user-defined, automatically executed piece of code in a MySQL database that responds to
specific events, such as INSERT, UPDATE, or DELETE. Triggers help maintain data integrity, enforce
business rules, and automatically perform actions when specific changes occur within the database.
They usually operate on the same row as the event that activated them.
To create a trigger in MySQL, follow these steps:
Choose the event that activates the trigger: INSERT, UPDATE, or DELETE.
Specify the timing of the trigger: BEFORE or AFTER. The timing indicates when the trigger will be
executed in relation to the specified event.
Define the table where the trigger will be associated.
Write the SQL statements or procedural code to be executed when the trigger is activated.
The general syntax for creating a trigger is:
7.
What is a stored procedure, and how do you create one in MySQL?
A stored procedure is a reusable, predefined piece of SQL code that is stored on the database server.
It can be called and executed multiple times by various applications or SQL scripts, improving
performance and consistency. Stored procedures can take input parameters, return results, and
manipulate data in the database.
To create a stored procedure in MySQL, use the following syntax:
8.
What is a cursor, and how do you use one in MySQL?
A cursor is a pointer to a result set returned by a query. In MySQL, you can use a cursor to traverse
through the rows in a result set one at a time. Cursors are handy for managing vast amounts of data or
completing complex calculations.
9.
What is a user-defined function, and how do you create one in MySQL?
In MySQL, a user-defined function is a program that can be invoked from within a query. The construct
FUNCTION statement in MySQL can be used to construct a user-defined function. User-defined
functions are useful for doing sophisticated computations or data manipulations that would be
difficult to perform using normal MySQL methods.
10.
What is a materialized view, and how do you create one in MySQL?
A materialized view is a database object that contains the result of a pre-defined query, and unlike a
regular view, it stores the data physically like a table. Materialized views are beneficial for situations
where data retrieval is time-consuming or resource-intensive. By caching query results, materialized
views can significantly improve query performance. However, they require more storage and
maintenance, as the data must be periodically updated to stay in sync with the underlying tables.
MySQL does not have built-in support for materialized views, but you can create a workaround using
tables and triggers.
Here's an example of creating a "materialized view" in MySQL:
Create a table to store the materialized view data:
For maintaining data consistency in employees_summary, create triggers that automatically update
the materialized view table when rows are inserted, updated, or deleted in the employees table.
Here's an example of creating a trigger for the INSERT operation:
Similar triggers must be created for UPDATE and DELETE operations. By combining tables and triggers,
you can emulate materialized view functionality in MySQL and maintain the cached data for faster
query execution.
11.
How do you optimize a MySQL query?
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.
12.
How do you use a prepared statement in MySQL?
A prepared statement in MySQL is a precompiled SQL statement that can be executed multiple times
with different input values. You can use a prepared statement in MySQL to improve query
performance and prevent SQL injection attacks. To use a prepared statement in MySQL, you can use
the PREPARE statement to create the statement and the EXECUTE statement to execute it.
13.
How do you use partitioning in MySQL?
The PARTITION BY clause is used in Window functions to break the result set into partitions to which
the window function is applied. This allows the calculation of a function for each row in the partition
independently.
Example:
14.
How do you create a stored function in MySQL?
To create a stored function in MySQL, use the CREATE FUNCTION statement followed by the function
name, input parameters, return type, and the function body with the logic. For example:
15.
How do you set up replication in MySQL?
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.
16.
How do you perform a backup in MySQL?
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.
Backups are useful for preventing data loss and for restoring the database in case of hardware failure
or other disasters.
17.
What is the difference between Data Definition Language (DDL) and Data Manipulation Language
(DML)?
SQL commands are classified as Data Definition Language (DDL) and Data Manipulation Language
(DML). DDL is used to establish the database structure as well as to create, change, and destroy
database objects including tables, indexes, views, and constraints. CREATE, ALTER, DROP, and
TRUNCATE are examples of DDL commands. DML is used to manipulate database data, such as
inserting, updating, removing, and retrieving information. SELECT, INSERT, UPDATE, and DELETE are
examples of DML commands.
18.
In a SELECT query, which statement is used for partial matching?
The LIKE operator is the statement used in a SELECT query for partial matching. The LIKE operator
matches a pattern in a column value. The wildcard character % is used to match any sequence of
characters, whereas the underscore (_) is used to match any single character. Here's an illustration:
SELECT * FROM my_table WHERE column_name ='%partial_match%' This statement will return all
rows with the substring "partial_match" in the column_name.
19.
What is profiling in MySQL 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.
20.
What is connection pooling in MySQL and how do you use it?
Connection pooling is a method that allows you to reuse database connections rather than generate
new ones for each request, which can assist increase speed and minimize costs. You can employ a
third-party library such as c3p0 or HikariCP to use connection pooling in MySQL, or you can configure
your database driver to use built-in connection pooling.
21.
What is a table? How do you create a new table in MySQL?
A table in MySQL is a collection of data organized into rows and columns. It is the primary storage unit
in which data is stored and maintained. Each table has a distinct name and one or more columns that
specify the data contained in the table.
To create a new table in MySQL, use the CREATE TABLE statement followed by the table name and its
columns along with their data types and constraints. For example:
22.
What is partitioning in MySQL 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.
23.
What is replication in MySQL and how do you set it up?
Replication in MySQL is a technique for creating and maintaining copies of a database on several
servers, typically in a master-slave or master-master arrangement, to increase availability, scalability,
and performance. You must configure the master and slave servers, establish a replication user, and
activate replication before you can begin.
24.
What is the difference between master-slave replication and master-master replication in MySQL?
In MySQL, replication is a technique used to synchronize data across multiple servers, which can
improve performance, provide redundancy, and distribute load. The difference between master-slave
and master-master replication lies in how the data is synchronized and the roles of the servers
involved:
Master-Slave Replication: In this configuration, there's one master server and one or more slave
servers. The master server handles all the write operations, while the slave servers replicate the data
from the master and handle read operations. The data flows in a unidirectional manner from the
master to the slaves. This setup is commonly used to distribute read load, or for backup and analytics
purposes.
Master-Master Replication: In this configuration, two or more servers act as masters, and the data is
synchronized bidirectionally across the servers. Each server can handle both read and write
operations, allowing updates on any of the masters. This setup provides redundancy, fault tolerance,
and improved write performance. However, it can lead to increased complexity in managing potential
conflicts and ensuring consistency between the masters.
25.
What is Sharding in MySQL and how do you implement it?
Sharding in MySQL is a technique used to distribute data across multiple servers, based on a shared
key, to improve scalability and performance. Each server stores a subset of the data, and queries are
routed to the appropriate server based on the shard key. To implement sharding in MySQL, you can
use third-party tools or build your own solution.
26.
What is a MySQL proxy and how do you use it?
A MySQL proxy is a lightweight middleware that sits between client applications and the MySQL
server, providing features such as load balancing, failover, query routing, and caching. To use MySQL
proxy, you need to install and configure it, and then point your client applications to the proxy instead
of the MySQL server.
27.
What is the Query Cache in MySQL and how do you enable 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.
28.
How do you use the Performance Schema in MySQL?
The MySQL Performance Schema is a tool that collects and aggregates data about server events,
threads, queries, and resources in order to monitor and analyze database performance. Various
Performance Schema tables and views may be used to discover performance bottlenecks, optimize
queries, and monitor server activity.
Also read: Best practices for MySQL performance tuning
29.
How can you check the status of the MySQL server?
To check the status of the MySQL server, you can use any of the following methods:
Command-line (UNIX-based systems): Run the following command in the terminal:
sudo service mysql status
The output will indicate whether the MySQL server is active and running.
Command-line (Windows systems): Open the command prompt and run the following command:
sc query MySQL
(Replace 'MySQL' with the name of the MySQL service if named differently.)
The output will indicate the current state of the MySQL service.
Query within MySQL: Connect to MySQL using a MySQL client and execute the following command:
SHOW GLOBAL STATUS;
This command will return detailed information about the server status, including various metrics and
variables.
Using MySQL Workbench: If you use MySQL Workbench, open the "Server Status" panel under the
"Management" tab to view the status and various performance metrics of the MySQL server.
Remember that in order to execute these commands, you may need the necessary privileges or
administrative rights.
30.
List different ways to 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.
31.
Can you explain more about the MySQL Enterprise Backup tool?
MySQL Enterprise Backup is a paid utility that offers a dependable and effective method of backing up
MySQL databases. It includes sophisticated features like hot backups, incremental backups, point-in-
time recovery, and compression to help you save time and space. It also supports multiple backup
destinations and can be integrated with popular cloud-based storage solutions.
32.
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.
33.
What is the MySQL Workbench tool, and how do you use it?
MySQL Workbench is a graphical user interface tool for managing MySQL databases. It provides
features like visual database design, SQL development, administration, and performance monitoring.
You can use it to create and edit database objects, write and execute SQL queries, manage users and
permissions, and monitor the performance of the database.
34.
What is the MySQL Router, and how do you use it?
MySQL Router is a small and scalable program that transparently routes and balances client
connections to one or more MySQL server instances. It can be used to disperse traffic over numerous
servers, increasing availability, scalability, and performance.
MySQL Router can be configured by a configuration file or command-line parameters, and it supports
several routing algorithms such as round-robin, least-connections, and random.
35.
What is the MySQL Connector/ODBC, and how do you use it?
MySQL Connector/ODBC is a driver that allows programs to connect to MySQL databases using the
ODBC interface. It provides a standard interface via which programs built in languages such as C++,
Java, and, .NET can interact with the MySQL database.
Installing the driver on the client system and configuring it to connect to the MySQL server through a
Data Source Name (DSN) or a connection string are also options.
36.
How do you use the MySQL Connector/J, and what are its benefits?
MySQL Connector/J is a driver that allows Java applications to connect to MySQL databases. It
provides a JDBC interface for Java applications to communicate with the MySQL database. You can
install the driver on the client machine or include it as a dependency in your project, and configure it
to connect to the MySQL server using a connection string.
By using MySQL Connector/J, developers can leverage various benefits for their Java-based
applications:
Cross-platform compatibility: Being a Java-based driver, Connector/J can run on any platform that
supports the Java runtime environment, offering seamless cross-platform compatibility.
Standardized API: Connector/J adheres to the JDBC API, which is a widely recognized and consistent
standard for connecting Java applications to relational databases. By following this standard,
developers can easily switch between different databases with minimal code changes.
Efficient communication: Connector/J is designed specifically for MySQL databases, ensuring
optimized communication and performance when interacting with a MySQL server. The driver handles
the underlying protocol, data conversion, and feature implementation, so developers can focus on the
business logic of their applications.
Advanced features support: Connector/J supports MySQL's advanced features, such as SSL/TLS
encryption, server-side prepared statements, transaction management, various authentication
methods, and connection pooling. This enables developers to take full advantage of MySQL's
capabilities when building their Java applications.
Active development and support: As an official MySQL product, Connector/J is actively maintained
and supported by the MySQL team. This ensures regular updates, bug fixes, and compatibility with the
latest Java and MySQL versions.
Ease of integration: MySQL Connector/J can be easily integrated with popular Java frameworks and
libraries, such as JPA (Java Persistence API), Hibernate, and Spring, allowing developers to work with
familiar and widely-used tools in combination with MySQL.
37.
What is the role of InnoDB in MySQL, and how does it differ from MyISAM?
InnoDB and MyISAM are both storage engines in MySQL, and they play a crucial role in defining the
underlying behavior and performance characteristics of your database tables. Here's how they differ:
38.
What are some common performance issues in MySQL, and how do you address them?
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 the 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.
How do you use MySQL with other programming languages, such as PHP or Python?
To use MySQL with other programming languages like PHP or Python, you need to interact with the
MySQL server using libraries or modules that provide a convenient way to connect, query, and
manage data in your database.
Here are simple examples for connecting to MySQL and executing a basic query using PHP and Python:
PHP: In PHP, you can use the MySQLi (MySQL Improved) extension or the PDO (PHP Data Objects)
extension to interact with MySQL. Here's an example using MySQLi:
Python: In Python, you can use the mysql-connector-python library to interact with MySQL. First,
you'll need to install the library using pip:
pip install mysql-connector-python
Then, here's a simple example using this library:
Using the Information Schema is particularly valuable for tasks such as inspecting database objects,
maintaining or generating reports, and developing database applications that need to adapt to the
structure of various MySQL installations.
43.
What is the MySQL Storage Engine API, and how do you use it?
The MySQL Storage Engine API is a programming interface that enables developers to design bespoke
MySQL storage engines. It offers a collection of methods and callbacks that implement the essential
data storage and retrieval procedures.
44.
How do you optimize the storage of large binary files in MySQL?
To optimize the storage of large binary files in MySQL, you can use the BLOB and LONGBLOB data
types, which store binary data in the database. You can also use external storage solutions, such as
Amazon S3 or Google Cloud Storage, to store large files and only store metadata in the database.
45.
What are some best practices for designing a MySQL database schema?
Some best practices for designing a MySQL database schema include using a normalized design,
defining appropriate data types and constraints, avoiding NULL values, using descriptive column
names, and creating indexes for frequently queried columns.
Tired of interviewing candidates to find the best developers?
Hire top vetted developers within 4 days.
Hire Now
Advanced MySQL interview questions and answers
1.
What is the role of indexes in MySQL, and how do you create and use them effectively?
Indexes in MySQL play a crucial role in improving query performance by minimizing the number of
rows that need to be examined to return the result of a query. They act as efficient data lookups that
allow MySQL to quickly find and retrieve the required records. Indexes are particularly beneficial when
dealing with large tables.
Creating an index involves determining the appropriate columns to include, based on which columns
are frequently accessed or used in WHERE clauses, JOINs, or sorting operations. Efficient indexing can
significantly speed up query execution times, but excessive indexing can lead to additional overhead
associated with maintaining index structures during INSERT, UPDATE, and DELETE operations.
To create an index, you can use the CREATE INDEX statement or specify the index while creating the
table with the CREATE TABLE statement.
Some guidelines for creating and using indexes effectively:
Primary Key: Add a primary key to any table if it doesn't have one. Primary keys are unique identifiers
for each record and automatically create a unique index.
CREATE TABLE Employees (
id INT AUTO_INCREMENT PRIMARY KEY,
...
);
Common Search Columns: Create indexes on the columns that are frequently used in WHERE clauses,
JOINs, or ORDER BY operations. For multiple columns, you can create a composite (multi-column)
index.
CREATE INDEX idx_employee_name ON Employees (name);
CREATE INDEX idx_employee_department ON Employees (department_id, salary);
Foreign Key Columns: Add an index to columns that serve as foreign keys to improve JOIN
performance.
ALTER TABLE Orders ADD INDEX idx_orders_customer_id (customer_id);
Consider Index Types: Depending on your use case, you can create and use different types of indexes,
such as FULLTEXT for text search or SPATIAL for geolocation-based search.
CREATE FULLTEXT INDEX idx_article_content ON Articles (content);
Index Maintenance: Regularly review and update your indexes based on new or removed columns,
changing query patterns, or evolving data distribution. Remove unused or redundant indexes to
minimize maintenance overhead.
Monitor Performance: Use tools like the MySQL Slow Query Log, Performance Schema, or the
EXPLAIN statement to analyze how your indexes are being used and make necessary adjustments.
2.
How do you use MySQL for full-text search?
Full-text search in MySQL allows you to search for words or phrases in text-based data, like searching
articles, product descriptions, or blog posts. MySQL supports full-text search using the FULLTEXT index
and the MATCH() ... AGAINST() functions.
Here's how to use MySQL for full-text search:
Create FULLTEXT index: The first step is to create a FULLTEXT index on the columns that you want to
perform full-text search. Add the FULLTEXT index when creating the table or alter an existing table.
Example (creating a table with a FULLTEXT index on the content column):
For an existing table, you can use the ALTER TABLE statement:
ALTER TABLE articles ADD FULLTEXT(content);
Perform a Full-text search: After creating the FULLTEXT index, use the MATCH() and AGAINST()
functions to perform a full-text search on the indexed columns.
Example (search for the term "MySQL"):
Advanced Full-text search modes: MySQL supports several advanced search modes that can be used
with the AGAINST() function for more complex text searching:
Boolean mode : Allows the use of boolean operators (+, -, *, etc.) and wildcard characters to create
detailed search combinations.
Example (search for articles containing "MySQL" but not "Oracle"):
Natural Language mode: By default, when not specifying Advanced Search mode, MySQL uses natural
language search mode, which provides a relevance score for each match.
Example (search for "data storage" and sort results by relevance score):
Query Expansion mode: This search mode extends search results by including related words
(automatically) in the search query. It can help improve the search result when the user provides
words or phrases that aren't necessarily the most relevant.
Example (search for "performance tuning" using Query Expansion mode):
3.
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.
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:
Manage and Monitor: Use the AWS Management Console to monitor performance, set up automated
backups, enable logging, and configure scaling options for the RDS instance. You can also enable AWS
monitoring services like CloudWatch and EventBridge for better insight.
Google Cloud SQL:
Create a Cloud SQL Instance: Sign in to the Google Cloud Console, navigate to the Cloud SQL service,
and create a Cloud SQL instance for MySQL. Configure instance specifications, storage settings,
network access permissions, and other options as needed.
Connect to the Cloud SQL Instance: Once the Cloud SQL instance is provisioned, retrieve the instance
connection name, user credentials, and other details in the Cloud SQL Console. Use this information to
connect to the Cloud SQL instance using any MySQL client.
Example (using MySQL command line via Cloud SQL Proxy):
First, set up the Cloud SQL Proxy on your local machine.
Manage and Monitor: Use the Google Cloud Console to monitor performance, set up automated
backups, enable logging, and configure scaling options for the Cloud SQL instance. You can also
employ monitoring services like GCP Monitoring for better insight.
5.
How do you fetch the top 'n' records for each group in a dataset?
You can use the window function ROW_NUMBER() with the PARTITION BY and ORDER BY clauses to
achieve this.
Example (fetch the top 2 salaries in each department):
6.
How do you perform a case-insensitive search in MySQL?
By default, the search is case-insensitive when using a collation that has ci (e.g., utf8mb4_0900_ai_ci).
If you're using a case-sensitive collation, you can use the LOWER() function to achieve a case-
insensitive search.
Example:
7.
Briefly explain the concept of Common Table Expressions (CTEs) in MySQL and provide an example
A CTE is a temporary result set that can be used within a SELECT, INSERT, UPDATE, or DELETE
statement. They provide a more readable and maintainable alternative to subqueries and derived
tables.
Example:
8.
In MySQL, how do you find the length of a given string or binary data without taking into account
trailing spaces?
Use the LENGTH() function for binary data lengths and the CHAR_LENGTH() function for string data
lengths, ignoring trailing spaces.
Example:
9.
How do you calculate the sum of two or more columns in MySQL?
Use the + operator or the SUM() function with the GROUP BY clause to calculate the sum of two or
more columns.
Example:
10.
Explain the concept of Prepared Statements in MySQL and give an example of creating and using
them.
Prepared statements are a way of precompiling and executing SQL statements securely and efficiently,
as they separate SQL code from data, reducing the risk of SQL injection.
Example (using MySQL command line):
11.
What are some advanced replication techniques in MySQL, such as multi-source replication or GTID-
based replication?
Multi-source replication and GTID-based replication are two advanced replication strategies in MySQL.
Data from numerous sources can be replicated to a single destination using multi-source replication.
GTID-based replication provides a more accurate method of tracking data changes in a replicated
environment.
12.
How do you use MySQL for machine learning or data mining?
Using tools such as MySQL Connector/Python and MySQL Connector/ODBC, you can utilize MySQL for
machine learning or data mining. These tools enable you to connect to a database and analyze data
using popular machine learning frameworks such as TensorFlow and sci-kit-learn.
13.
How would you copy data from one table to another existing table with the same structure in MySQL?
Use the INSERT INTO ... SELECT statement to copy data from one table to another.
Example:
14.
Explain the concept of User-Defined Variables in MySQL and provide an example of using them with a
SELECT statement.
User-Defined Variables are session-specific variables, meaning that they retain their values for a
MySQL session and can be used across multiple statements within that session. They can be created,
used, and displayed using the @variable_name syntax.
Example:
15.
What is the difference between CHAR and VARCHAR data types in MySQL, and when would you use
one over the other?
CHAR and VARCHAR are both used to store string (non-binary) data.
CHAR is a fixed-length data type, meaning that it will always use the full length specified upon its
creation. Use CHAR when storing strings of a short, fixed length (e.g., country codes).
VARCHAR is a variable-length data type, meaning it uses only the amount of space required for a given
value (plus some minimal overhead). Use VARCHAR when storing strings of varying lengths (e.g.,
names or addresses).
Here is an example:
16.
How do you create a full-text index on a column in MySQL, and how do you perform a full-text search?
Provide an example.
To create a full-text index, use the FULLTEXT keyword in the CREATE TABLE or ALTER TABLE statement.
To perform a full-text search, use the MATCH and AGAINST functions in your SELECT query.
Example:
17.
Can you explain CASCADE and RESTRICT keywords with reference to MySQL foreign key constraints?
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:
18.
What is the difference between COUNT(*) and COUNT(column_name) in MySQL?
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).
Example:
19.
What are Any and All operators in MySQL, and how are they used? Give examples.
The ANY and ALL operators are used to compare a value to each value in another result set or
expression.
ANY: It's true if the comparison is true for any value.
ALL: It's true only if the comparison is true for all values.
Examples:
Using ANY:
Using ALL:
20.
What is MySQL event scheduler, and how do you create a scheduled event?
The MySQL Event Scheduler is a process that runs in the background and periodically executes stored
routines like procedures, functions, or SQL statements at predefined times or intervals.
To create a scheduled event:
Ensure that Event Scheduler is enabled: SET GLOBAL event_scheduler = ON;
Create the event using the CREATE EVENT syntax:
21.
How do you paginate results in MySQL?
You can paginate results using the LIMIT and OFFSET clauses. Here is an example:
22.
What is the purpose of SQL_CALC_FOUND_ROWS and FOUND_ROWS() in MySQL?
SQL_CALC_FOUND_ROWS is an option in a SELECT statement that calculates the total number of rows
that would have been returned had there been no LIMIT constraint. FOUND_ROWS() is the function
used to fetch the value calculated by SQL_CALC_FOUND_ROWS.
Example:
23.
What is the MySQL Query Analyzer, and how do you use it to analyze and optimize queries?
MySQL Query Analyzer is a part of MySQL Enterprise Monitor, a commercial product provided by
Oracle that allows users to monitor MySQL database performance and optimize SQL queries. MySQL
Query Analyzer analyzes queries executed on MySQL servers in real-time, helping to locate and
resolve performance issues.
Key features of MySQL Query Analyzer include:
Visualization of query performance data
Identification of problematic queries
Detection of query execution deviations
Query execution statistics aggregation
Support for drill-down analysis
To use MySQL Query Analyzer to analyze and optimize queries, follow these steps:
Install and configure MySQL Enterprise Monitor: You need to have a valid Oracle MySQL Enterprise
subscription to access MySQL Query Analyzer. Download, install, and configure the MySQL Enterprise
Monitor.
Configure the Query Analyzer:
Go to the MySQL Enterprise Monitor dashboard.
Click on the 'MySQL Query Analyzer' tab located at the top.
Select the database server instance you want to monitor by clicking on 'Choose Server'.
Analyze queries:
Query Analyzer lists executed queries in a tabular format, showing details like execution time, latency,
and rows affected.
Use this data to identify problematic queries with high execution times or impacting the overall
performance.
Click on the query to view its execution details, and analyze the deviations in the performance.
Optimize problematic queries:
Use the insights gained from the Query Analyzer to optimize the problematic queries.
Review the query logic and structure, ensure proper indexing, remove full table scans, minimize
subqueries, and use appropriate JOIN methods to improve performance.
Additionally, you can also use the MySQL EXPLAIN statement to better understand the query
execution plan and look for optimization opportunities, such as better indexes or denormalization.
Monitor and iterate: Continuously monitor your database performance using MySQL Query Analyzer,
and optimize your queries as needed to maintain optimal performance.
24.
How do you prevent SQL injection in MySQL?
You can prevent SQL injection by using prepared statements and parameterized queries to separate
SQL code from data. Example (using prepared statements in PHP):
25.
What are SEQUENCES in MySQL? Can you simulate a sequence without using AUTO_INCREMENT?
In MySQL, there is no inbuilt SEQUENCE. Instead, you can create a table with an AUTO_INCREMENT
column to generate a sequence. To simulate a sequence without using AUTO_INCREMENT:
Basic MySQL Interview Questions
1. What is MySQL?
MySQL is a relational database management system based on SQL (Structured Query Language). It is
an open source software owned by Oracle and can run on various platforms. Most websites or web
applications are developed using MySQL.
2. In which language has MySQL been written?
MySQL is written in C and C++. Its SQL parser is written in yacc.
3. What are the advantages of using MySQL?
MySQL is a fast, stable, and reliable solution that provides advantages like:
Data Security – most secure and reliable database management system
Flexibility – runs on all operating systems; features 24X7 support and enterprise indemnification
High Performance – powerful, designed to meet highly demanding applications while maintaining
optimum speed and high performance
On-demand Scalability – offers on-demand scalability and complete customization
Enterprise-level SQL Features – the enterprise edition includes advanced features and management
tools, and technical support for enterprise
Full-text Indexing and Searching – has support for full-text indexing and searching
Query Caching – unique memory caches help enhance the speed of MySQL greatly
Replication – one MySQL server can be duplicated on another, resulting in numerous benefits
4. What is a database?
A database is a structured repository of data stored electronically in a computer system and organized
in a way that data can be quickly searched and information rapidly retrieved. A database is generally
controlled by a database management system.
5. What does 'MySQL' stand for?
'My' in MySQL represents the first name of its co-founder, Michael Widenius' daughter, My Widenius.
SQL is an abbreviation for the term "Structured Query Language". SQL is also used in databases like
Oracle and Microsoft SQL Server.
6. How to check MySQL version?
The command 'MySQL-v' can be used to check MySQL version on Linux
7. What does a MySQL database contain?
A MySQL database contains one or many tables, with each table containing several records or rows.
Within these rows, data is contained in various columns or fields.
8. List the ways to interact with MySQL.
There are 3 main ways users can interact with MySQL:
Using a command line
Through a web interface
Using a programming language
9. What are the different tables in MySQL?
They are:
MyISAM
HeapMerge
INNO DB
ISAM
10. What are MySQL Database Queries?
A query is a request for data or information from a database. Users can query a database for specific
information, and the resultant record/records are returned by MySQL.
Become a Software Development Professional
Full Stack Java Developer
o Kickstart Full Stack Java Developer career with industry-aligned curriculum by experts
o Hands-on practice through 20+ projects, assessments, and tests
6 Months months
View Program
Full Stack Developer - MERN Stack
o 40+ micro skilling exercises & 6+ work-like professional projects
o Develop expertise in 10+ full stack development tools and frameworks
6 Months months
View Program
Here's what learners are saying regarding our programs:
Mayur Kharad
Product Engineer, IKS Health
During the lockdown, I realized I needed to upskill myself, and my journey with Simplilearn has been
fantastic. I learned many things during the full stack java developer course, thanks to trainer Virendra
Sharma. I've always wanted to work in this sector, and after completing my certification in Fullstack
Java Development, I got placed at IKS Health through Simplilearn.
Manish Maccha
Software Engineer, SolvenTek
I was looking for a new job with a better salary and position, so I knew I needed to upskill. My
experience with Simplilearn was very good. Each topic was innovative and interesting, with quality
content. After completing the full stack java developer course, I landed a new job with Neo Geo Info
Technologies with a 30% salary hike.
Not sure what you’re looking for?View all Related Programs
11. What are some common MySQL commands?
Some common MySQL commands are:
CREATE – To create Table
INSERT – To insert data
JOIN – To join tables
DELETE – To delete a row from a table
ALTER – To alter database or table
BACKUP – to back up a table
DROP – To delete a database or table
CREATE INDEX – to add indexing to a column in a table
GRANT – To change user privileges
TRUNCATE – Empty a table
EXIT – to exit
12. How to create a database in MySQL?
The CREATE DATABASE command can be used to create a new database.
13. How to create table using MySQL?
The following query can be used to create a table:
CREATE TABLE 'history' (
'author' VARCHAR(128),
'title' VARCHAR(128),
'type' VARCHAR(16),
'year' CHAR(4))
ENGINE = InnoDB;
A table "history" gets created in the selected database.
14. How to insert data in MySQL?
The INSERT INTO statement is used to insert new records in a table in MySQL.
The two main syntaxes are:
INSERT INTO table_name (column 1, column 2, column 3,…columnN)
VALUES (value 1, value 2, value 3,...valueN)
15. How do you remove a column form a database?
The DROP command is used to remove a column from a database.
Alter table 'history' drop column title;
16. How to create an index?
There are different types of indexes in MySQL, like a regular INDEX, a PRIMARY KEY, or a FULLTEXT
index. Indexes are created on a column basis. Indexing helps to quickly search for results, either by
ordering the data on disk or by telling the SQL engine which location to find your data in.
Syntax:
ALTER TABLE history ADD INDEX(author(10));
17. How do you delete data from MySQL table?
We use the DELETE statement to remove records from a table.
The syntax is as follows:
DELETE FROM table_name WHERE column_name
18. How can you view a database in MySQL?
The SHOW DATABASES command allows the user to view all databases on the MySQL server host.
mysql> SHOW DATABASES;
19. How to import database in MySQL?
There are two ways to import database or move data from one place to another:
Command Line Tool
MySQL Workbench
20. What are numeric data types in MySQL?
There are numeric data types for integer, fixed-point, floating-point, and bit values in MySQL. Except
for BIT, the other numeric data types can be signed or unsigned.
Examples:
INT - Standard Integer
TINYINT - Very Small Integer
SMALLINT - Small Integer
MEDIUMINT - Medium-sized Integer
BIGINT - Large Integer
DECIMAL - Fixed-point number
FLOAT - Single-precision floating-point number
DOUBLE - Double-precision floating-point number
BIT - Bit-field
21. What are string data types in MySQL?
The string data types in MySQL are:
CHAR
VARCHAR
BINARY
VARBINARY
TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB
TINYTEXT
TEXT
MEDIUMTEXT
LONGTEXT
ENUM
SET
NULL
22. What are temporal data types in MySQL?
MySQL provides temporal data types for date and time, as well as a combination of date and time.
These are:
DATE - A date value in CCYY-MM-DD Format
TIME - A Time value in hh : mm :ss format
DATETIME - Date and time value in CCYY-MM-DD hh : mm :ss format
TIMESTAMP - A timestamp value in CCYY-MM-DD hh : mm :ss format
YEAR - A year value in CCYY or YY format
23. What is BLOB?
BLOB is an acronym for a binary large object. It is a string data type used to hold a variable amount of
data.
24. How do you add users in MySQL?
The CREATE command, along with necessary credentials, can be used to add users.
CREATE USER 'testuser' IDENTIFIED BY 'sample password';
Intermediate MySQL Interview Questions
25. What are views in MySQL?
A view is a set of rows returned when a particular query is executed in MySQL. It is also known as a
virtual table, which does not store any data of its own but displays data stored in other tables.
26. How to create and execute views?
The CREATE VIEW command is used to create a view in MySQL.
The syntax is:
CREATE VIEW [databasename.] view_name [(column_list)] AS select-statement;
27. What are MySQL triggers?
A task that is executed automatically in response to a predefined database event is known as a trigger.
Each trigger is associated with a table and is activated by commands like INSERT, DELETE, or UPDATE.
28. How many triggers are possible in MySQL?
There are 6 different types of triggers in MySQL:
Before Insert
After Insert
Before Update
After Update
Before Delete
After Delete
29. What is MySQL server?
The server 'mysqld' is the MySQL server, which performs all manipulation of databases and tables.
30. What are the clients and utilities in MySQL?
There are several MSQL programs available to help users communicate with the server. Some
important ones for administrative tasks are:
.mysql – this interactive program helps to send SQL statements to the server and view the results. One
can even use MySQL to use batch scripts.
.mysqladmin – this administrative program helps perform tasks like shutting down the server,
checking configuration, monitoring status if it is not functioning properly.
.mysqldump – for backing up databases or copying them to another server
.mysqlcheck and myisamchk – these programs help perform table checking, analysis, and
optimization, plus repairs for damaged tables.
31. What types of relationships are used in MySQL?
Three types of relationships are used in MySQL:
One-to-one – items with one-to-one relation can be included as columns in the same table
One-to-many – or many-to-one relationships are seen when one row in a table is related to multiple
rows in another table
Many-to-many – many rows in a table are linked to many rows in another table
32. Explain the logical architecture of MySQL
The top layer comprises the services required by most network-based client/server tools like
connection handling, security, authentication, etc.
The 2nd layer comprises code for query parsing, optimization, analysis, caching, and all built-in
functions.
The 3rd layer comprises storage engines where storage and retrieval of data stored in MySQL is
performed.
33. What is Scaling?
Scaling capacity in MySQL is the ability to handle the load in terms of:
Data quantity
Number of users
User activity
Size of related datasets
34. What is Sharding?
The process of breaking up large tables into smaller chunks or shards spread across many servers is
called sharding. It makes querying, maintenance, and other tasks faster.
35. What are Transaction Storage Engines?
The InnoDB storage engine enables users to use the transaction facility of MySQL.
We hope this list of MySQL interview questions will be helpful for you. Register with Simplilearn today
to get access to top-rated courses on database training and full stack web development.
36. How does MySQL differ from PostgreSQL?
MySQL and PostgreSQL are both popular relational database management systems (RDBMS) but have
differences in features, performance, and syntax. MySQL is known for its speed and ease of use, while
PostgreSQL is praised for its advanced features, including support for complex data types,
transactions, and advanced indexing.
37. Can you explain the difference between MyISAM and InnoDB storage engines?
MyISAM is a storage engine in MySQL known for its simplicity and speed, but lacks support for
transactions and foreign keys. InnoDB, on the other hand, is a more robust storage engine that
supports transactions, foreign keys, and row-level locking, making it suitable for mission-critical
applications.
38. What is a primary key in MySQL?
A primary key in MySQL is a unique identifier for each row in a table. It ensures that each record can
be uniquely identified and provides a way to enforce entity integrity. A primary key can consist of one
or more columns, and its values cannot be null.
39. Explain the concept of a foreign key.
A foreign key in MySQL establishes a relationship between two tables by linking a column or group of
columns in one table to the primary key column(s) in another table. It enforces referential integrity,
ensuring that values in the foreign key column(s) match values in the referenced primary key
column(s) of the related table.
40. Describe the difference between DELETE and TRUNCATE commands.
The DELETE command is used to remove rows from a table based on specified criteria, allowing for
selective deletion. TRUNCATE, on the other hand, removes all rows from a table, resetting auto-
increment values, and is faster than DELETE as it does not generate transaction logs.
41. What does the JOIN statement do in MySQL? Explain the different types of joins.
The JOIN statement in MySQL is used to retrieve data from multiple tables based on a related column
between them. Different types of joins include INNER JOIN (returns rows when there is a match in
both tables), LEFT JOIN (returns all rows from the left table and matching rows from the right table),
RIGHT JOIN (returns all rows from the right table and matching rows from the left table), and FULL
JOIN (returns all rows when there is a match in either table).
42. How can you optimize a MySQL query?
MySQL query optimization involves various techniques such as indexing, using appropriate data types,
minimizing the number of queries, optimizing table structure, avoiding unnecessary calculations, and
utilizing query caching.
43. Explain the concept of normalization in database design.
Normalization is the process of organizing data in a database to reduce redundancy and dependency.
It involves breaking down tables into smaller, related tables and defining relationships between them
to ensure data integrity and minimize anomalies.
44. Describe denormalization and when you might use it.
Denormalization is the process of intentionally introducing redundancy into a database design to
improve performance by reducing the number of joins required to retrieve data. It is often used in
read-heavy applications where query performance is critical, at the expense of some data redundancy
and update complexity.
45. What are transactions in MySQL and how do you manage them?
Transactions in MySQL are sequences of SQL operations that are executed as a single unit of work,
either all succeed or all fail. They are managed using the BEGIN, COMMIT, and ROLLBACK statements
to start, commit, and roll back transactions, respectively.
46. How would you implement ACID properties in MySQL?
ACID (Atomicity, Consistency, Isolation, Durability) properties can be implemented in MySQL by using
transactions to ensure that database operations are atomic, consistent, isolated, and durable.
47. What is the significance of HAVING clause in MySQL?
The HAVING clause in MySQL is used to filter rows returned by a GROUP BY clause based on specified
conditions. It is similar to the WHERE clause but is applied after grouping and aggregation functions.
48. Explain the difference between CHAR and VARCHAR data types.
CHAR and VARCHAR are both string data types in MySQL. CHAR stores fixed-length strings, while
VARCHAR stores variable-length strings. CHAR is padded with spaces to its defined length, while
VARCHAR only stores the actual length of the string.
49. How do you perform a full-text search in MySQL?
Full-text search in MySQL is performed using the MATCH() AGAINST() syntax, where MATCH() specifies
the columns to search and AGAINST() specifies the search query. It is applicable only on columns
indexed as FULLTEXT.
50. Explain the LIKE clause in MySQL.
The LIKE clause in MySQL is used to search for patterns in strings. It allows the use of wildcard
characters such as '%' (matches zero or more characters) and '_' (matches any single character) to
perform flexible pattern matching.
51. Describe the use of GROUP BY and ORDER BY in MySQL.
GROUP BY in MySQL is used to group rows that have the same values into summary rows, typically in
conjunction with aggregate functions like SUM or COUNT. ORDER BY is used to sort
52. How do you update a value in a MySQL table?
To update a value in a MySQL table, you can use the UPDATE statement followed by the SET clause to
specify the column(s) to be updated and their new values, along with optional WHERE clause to filter
which rows to update.
53. Explain the use of LIMIT in MySQL.
The LIMIT clause in MySQL is used to constrain the number of rows returned by a query. It is often
used in conjunction with the SELECT statement to retrieve a limited number of rows, such as the first
10 rows, or to implement pagination.
54. Explain the difference between INNER JOIN and OUTER JOIN.
INNER JOIN returns only the rows that have matching values in both tables based on the join condition
specified, while OUTER JOIN returns all rows from one or both tables, with unmatched rows filled with
NULL values where the join condition is not met.
55. Explain the BETWEEN operator in MySQL.
The BETWEEN operator in MySQL is used to select values within a specified range. It includes both the
start and end values in the range. For example, column BETWEEN value1 AND value2 selects rows
where the column value is between value1 and value2.
56. What is the significance of the AUTO_INCREMENT attribute?
The AUTO_INCREMENT attribute in MySQL is used with numeric primary key columns to automatically
generate a unique value for each new row inserted into the table. It simplifies the process of creating
primary key values, ensuring uniqueness and sequentiality.
57. Describe how MySQL uses locking to manage concurrency.
MySQL uses locking mechanisms to manage concurrency and ensure data consistency in multi-user
environments. It employs various types of locks, including table locks, row locks, and explicit locks, to
control access to data and prevent conflicts between concurrent transactions.
58. How would you change a column's data type in an existing MySQL table?
To change a column's data type in an existing MySQL table, you can use the ALTER TABLE statement
followed by the MODIFY COLUMN clause, specifying the column name and the new data type.
Become a Software Development Professional
Full Stack Java Developer
o Kickstart Full Stack Java Developer career with industry-aligned curriculum by experts
o Hands-on practice through 20+ projects, assessments, and tests
6 Months months
View Program
Full Stack Developer - MERN Stack
o 40+ micro skilling exercises & 6+ work-like professional projects
o Develop expertise in 10+ full stack development tools and frameworks
6 Months months
View Program
Here's what learners are saying regarding our programs:
Mayur Kharad
Product Engineer, IKS Health
During the lockdown, I realized I needed to upskill myself, and my journey with Simplilearn has been
fantastic. I learned many things during the full stack java developer course, thanks to trainer Virendra
Sharma. I've always wanted to work in this sector, and after completing my certification in Fullstack
Java Development, I got placed at IKS Health through Simplilearn.
Manish Maccha
Software Engineer, SolvenTek
I was looking for a new job with a better salary and position, so I knew I needed to upskill. My
experience with Simplilearn was very good. Each topic was innovative and interesting, with quality
content. After completing the full stack java developer course, I landed a new job with Neo Geo Info
Technologies with a 30% salary hike.
Not sure what you’re looking for?View all Related Programs
59. What are the common types of errors in MySQL and how do you troubleshoot them?
Common types of errors in MySQL include syntax errors, database connection errors, and data
integrity violations. Troubleshooting involves reviewing error messages, checking log files, validating
SQL syntax, verifying database connections, and ensuring data consistency.
60. How can you prevent SQL injection in MySQL?
To prevent SQL injection in MySQL, use prepared statements with parameterized queries or use
parameterized stored procedures. Additionally, sanitize user input by validating and escaping input
data before incorporating it into SQL queries.
MySQL Interview Questions
A list of top frequently asked MySQL interview questions and answers are given below.
1) What is MySQL?
MySQL is a multithreaded, multi-user SQL database management system which has more than 11
million installations. It is the world's second most popular and widely-used open source database. It is
interesting how MySQL name was given to this query language. The term My is coined by the name of
the daughter of co-founder Michael Widenius's daughter, and SQL is the short form of Structured
Query Language. Using MySQL is free of cost for the developer, but enterprises have to pay a license
fee to Oracle.
Formerly MySQL was initially owned by a for-profit firm MySQL AB, then Sun Microsystems bought it,
and then Oracle bought Sun Microsystems, so Oracle currently owns MySQL.
MySQL is an Oracle-supported Relational Database Management System (RDBMS) based on
structured query language. MySQL supports a wide range of operating systems, most famous of those
include Windows, Linux & UNIX. Although it is possible to develop a wide range of applications with
MySQL, it is only used for web applications & online publishing. It is a fundamental part of an open-
source enterprise known as Lamp.
What is the Lamp?
The Lamp is a platform used for web development. The Lamp uses Linux, Apache, MySQL, and PHP as
an operating system, web server, database & object-oriented scripting language. And hence
abbreviated as LAMP.
Once we finished this setup, it will open the MySQL Workbench screen. Now, we can double click on
the newly created connection to connect with the database server.
To read more information, click here.
ADVERTISEMENT
Select Tables sub-menu, right-click on it and select Create Table option. We can also click on create a
new table icon (shown in red rectangle) to create a table. It will open the new popup screen where we
need to fill all the details to create a table. Here, we will enter the table name and column details.
After entering the details, click on the Apply button and then the Finish button to complete the table
creation.
To read more information, click here.
49) What is the difference between the heap table and the temporary table?
Heap tables:
Heap tables are found in memory that is used for high-speed storage temporarily. They do not allow
BLOB or TEXT fields.
Heap tables do not support AUTO_INCREMENT.
Indexes should be NOT NULL.
Temporary tables:
The temporary tables are used to keep the transient data. Sometimes it is beneficial in cases to hold
temporary data. The temporary table is deleted after the current client session terminates.
Main differences:
The heap tables are shared among clients, while temporary tables are not shared.
Heap tables are just another storage engine, while for temporary tables, you need a special privilege
(create temporary table).
59) What is the difference between UNIX timestamps and MySQL timestamps?
Actually, both Unix timestamp and MySQL timestamp are stored as 32-bit integers, but MySQL
timestamp is represented in the readable format of YYYY-MM-DD HH:MM:SS format.
60) How to display the nth highest salary from a table in a MySQL query?
Let us take a table named the employee.
To find Nth highest salary is:
select distinct(salary)from employee order by salary desc limit n-1,1
if you want to find 3rd largest salary:
select distinct(salary)from employee order by salary desc limit 2,1
73) Write a query to select all teams that won either 1, 3, 5, or 7 games.
SELECT team_name FROM team WHERE team_won IN (1, 3, 5, 7);
85) Which command is used to view the content of the table in MySQL?
The SELECT command is used to view the content of the table in MySQL.
Explain Access Control Lists.
An ACL is a list of permissions that are associated with an object. MySQL keeps the Access Control Lists
cached in memory, and whenever the user tries to authenticate or execute a command, MySQL checks
the permission required for the object, and if the permissions are available, then execution completes
successfully.
90) What is the difference between primary key and candidate key?
To identify each row of a table, we will use a primary key. For a table, there exists only one primary
key.
A candidate key is a column or a set of columns, which can be used to uniquely identify any record in
the database without having to reference any other data.
Real-Life Problems
Prep for Target Roles
Create My Plan
2. How to add users in MySQL?
You can add a User by using the CREATE command and specifying the necessary credentials. For
example:
CREATE USER ‘testuser’ IDENTIFIED BY ‘sample password’;
Real-Life Problems
Detailed reports
Attempt Now
8. How to Delete Data From a MySQL Table?
In MySQL, the DELETE statement is used to delete records from a table:
DELETE FROM table_name
WHERE column_name = value_name
9. How to create an Index in MySQL?
In MySQL, there are different index types, such as a regular INDEX, a PRIMARY KEY, or a FULLTEXT
index. You can achieve fast searches with the help of an index. Indexes speed up performance by
either ordering the data on disk so it's quicker to find your result or, telling the SQL engine where to go
to find your data.
Example: Adding indexes to the history table:
ALTER TABLE history ADD INDEX(author(10));
ALTER TABLE history ADD INDEX(title(10));
ALTER TABLE history ADD INDEX(category(5));
ALTER TABLE history ADD INDEX(year);
DESCRIBE history;
10. How do you remove a column from a database?
You can remove a column by using the DROP keyword:
ALTER TABLE classics DROP pages;
11. How do you Insert Data Into MySQL?
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
If we want to add values for all the columns of the table, we do not need to specify the column names
in the SQL query. However, the order of the values should be in the same order as the columns in the
table. The INSERT INTO syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
12. How do you create a table using MySQL?
Use the following to create a table using MySQL:
CREATE TABLE history (
author VARCHAR(128),
title VARCHAR(128),
type VARCHAR(16),
year CHAR(4)) ENGINE InnoDB;
Q17). What is the most common key that can be applied to almost all databases.
One of the most common key that could be applied to almost all databases is called a Primary Key and
there is only one Primary key in one table. Primary key is an unique identifier like driver license
number, or phone no. together with area code, etc. A RDBMS should have just one primary key.
Q18). If multiple columns have to be used as a Primary key, what is it called?
When you want to use multiple columns as a primary key, then it is called a Candidate Key. Here’s a
comprehensive guide on what is SQL candidate key. In a table a composite key is a candidate key
which contains 2 or more attributes, i.e., columns that simultaneously identifies a table row or an
entity’s occurrence.
On the contrary, a compound key is a composite key for which every attribute that forms a key is a
foreign key distinctly.
Q19). If we are using the Primary key from any other table, then what is it called?
When you’re using a primary key from any other table, then it is called a Foreign key, and it is used to
maintain referential Integrity. A foreign key is a column or a set of columns utilized to develop a link
between the data in 2 database tables to monitor the data that could be saved in a foreign key
database.
Q20). What are the drawbacks of using a File Processing System?
The following are the drawbacks of the File Processing System:
Inconsistency and redundancy of data
Data access is difficult.
Isolation of data
Data security.
It is not feasible to have concurrent access.
Issues with security.
Refer to our SQL tutorial and get an overview of SQL Server, Microsoft's relational database platform.
Learn how to connect to an SQL Server database and perform basic operations such as creating tables,
indexes, and stored procedures.
Q21). What Do The "Integrity Rules" Mean?
Database integrity is determined by two rules.
The entity integrity states, "The value of the primary key cannot be NULL".
Referential Integrity states, "The Foreign Key value can either be NULL or the Primary Key value of
another relation.”
Q22). What's the difference between extension and intention?
The number of tuples in a table at any time is an extension. This is time sensitive. Intention is a
constant value that specifies the table's name, structure, and restrictions.
Q23). How would you describe System R and its subsystems?
It is a prototype, and its goal was to show that a Relational System can be built that can be used in a
real-world setting to address real-world issues, with a performance at least equivalent to that of
existing systems.
It has two subsystems. They are
Research Storage and
System Relational Data System
Q24). What is the difference between the data structure of System R and Relational Structure?
Domains aren't supported.
It is optional to enforce candidate key uniqueness.
It is optional to enforce entity integrity.
There is no requirement for referential integrity.
Q25). How can you tell the difference between logical and physical data independence?
Physical Data Independence defines that Physical data changes should not influence logical data.
Whereas logical data independence defines that modifications at the logical level should have an
impact on the view level.
Test your knowledge of SQL by taking our SQL Quiz and grab the best opportunity for your career.
Q26). How can you distinguish between ELT and ETL in DBMS?
Data is processed by ETL on a separate server, whereas ELT processes data within the data warehouse.
Raw data is not moved into the data warehouse via ETL; instead, raw data is sent directly to the data
warehouse using ELT.
Q27). How do you define an Object Oriented Model in a database management system?
The foundation of this concept is a collection of objects. Within an object, values are stored in instance
variables. A collection of code that operates on an object is also known as an object. Certain sections
of code are referred to as methods.
Are you preparing for your upcoming database interview questions? Check out our top DBMS
interview questions and answers for freshers and experienced.
Q28). Distinguish between an entity type and an entity set.
An entity type is a group of things with similar attributes. Whereas, an entity set is a collection of all
entities in the database that belong to a specific entity type.
Q29). How can you define the degree of a relation?
The degree of a relation is defined as the no of occurrences in 1 entity which is related to no of
occurrences in another entity. The following are the 3 degrees of relationships:
One-to-one relationship (1:1)
One-to-many relationship (1:M)
many-to-many relationship (M : N)
Q30). Describe the Record at a time procedure.
Each record from a group of records can be specified and retrieved using Low Level or Procedural
DML. Record-at-a-time retrieval is the name for this method.
Q31). Define the Set-at-a-time procedure.
The High level or Non-procedural DML can define and retrieve several records in a single DML
statement. This type of record retrieval is known as Set-at-a-time or Set-oriented.
Learn how to handle relational databases and gain a thorough understanding of SQL queries by
reading our comprehensive guide on what does SQL stands for.
Q32). How can you distinguish between Relational Algebra and Relational Calculus?
Relational algebra uses procedural query language. It comprises a collection of procedures that accept
one or two relations as input and output a new one. Whereas relational calculus is particularly
optimized for relational databases.
Q33). How do you define functional dependency?
X Y indicates a functional dependency between two sets of attributes X and Y that are subsets of R,
and it constrains the potential tuple that could result in a R relation state r.
The restriction is that if t1[X] = t2[X], then t1[Y] = t2[Y] for any two tuples t1 and t2 in r. This means
that the value of the X component of a tuple determines the value of the Y component.
Q34). Under what condition Functional Dependency F is said to be minimal?
In F, each right-hand side dependency has just one attribute.
We can't replace any dependency X A in F with a dependency Y A and still have a collection of
dependencies identical to F. We can't remove any of F's dependencies while maintaining an identical
set of dependencies.
Q35). Explain what a multivalued dependency is.
The constraint on any relation r of R is described by the multivalued dependence represented by X Y
stated on relation schema R, where X and Y are both subsets of R: If two tuples t1 and t2 exist in r with
the attributes t1[X] = t2[X], then t3 and t4 should likewise exist in r with the properties t1[X] = t2[X].
Q36). What do you understand by Lossless Join Property?
It ensures that misleading tuple formation does not occur with relation schemas after decomposition.
If you want to boost your SQL knowledge and advance your career, enrol in our online SQL server
training courses & get certified!
Q37). How can you describe Fully Functional Dependency?
It is based on the concept of total functional dependency, in which the dependent attributes are
evaluated by the deciding attributes. If removing any attribute A from X causes the dependency to
break, it is called a fully functional dependency.
Q38). What exactly is BCNF?
A relation schema R is in BCNF if it is in 3NF and meets the extra restriction that X must be a candidate
key for every FD X A.
Also, gain comprehensive knowledge about SQL Schema and find out how to create, alter and drop a
schema in SQL.
RDBMS Interview Questions and Answers for Experienced
Running through the highly awaited RDBMS interview questions is important for cracking your
interview and determining your existing preparation. Also, in-depth knowledge of RDBMS opens doors
to a lot of job opportunities in top MNCs like Pioneer, Bank of America, IBM, Accenture, and so on. So
let’s get started with the next section, where we’ve shared interview questions in RDBMS.
The list of RDBMS interview questions and answers for experienced candidates.
Q51). What is a Database?
A database is a logical, organized, and consistent collection of data that can be easily accessed,
managed, as well as managed. It is designed to let you create, insert and update the data efficiently.
Database mostly contains objects and tables, including records and fields.
Q52). What is RDBMS? How is it different from DBMS?
The abbreviation of Relational Database Management Systems, RDBMS, helps maintain table data
records and indices. It is the form of DBMS that utilizes the structure to find and access data
concerning the other pieces of data in the database. RDBMS is basically a system that allows you to
perform numerous operations like update, insert, delete, manipulate, and administrator a relational
database with minimal difficulties.
Q53). What are the different features of an RDBMS?
Name: Every relation in a relational database should contain a unique name.
Attributes: Each column in a relation is called an attribute.
Tuples: Each and every row in a relation is called a tuple. It also presents a collection of attribute
values.
Q54). What are the advantages of RDBMS?
Here is the list of major advantages of RDBMS:
It controls redundancy.
It can share data.
It can enforce integrity.
It can avoid inconsistencies.
Q55). Explain the different languages present in DBMS.
Here is the list of different languages present in DBMS:
DDL: DDL stands for Data Definition Language; it contains commands required to define the database.
DML: Data Manipulation Language contains commands required to manipulate the data available in
the database.
TCL: TCL or Transaction Control Language contains commands required to deal with the database
transaction.
DCL: Standing for Data Control Language, DCL contains commands required to deal with the user
permission and controls of the database.
Q56). What is an Index? Explain its different types.
An index is a performance-tuning method that allows the faster retrieval of records from the table. An
Index helps in creating an entry for every value. There are three types of SQL server indexes:
Unique Index: Unique index is applied automatically when the primary key is defined. It does not let
the field get duplicate values.
Clustered Index: Clustered Index reorders the physical order of the table and searches depending on
the key values. This type of index can have just one clustered index.
NonClustered Index: It does not modify the physical order of the table and maintains the logical order
of data. Each table can have 999 nonclustered indexes.
Q57). What is Database partitioning?
Database partitioning is about partitioning tables and indexing them into smaller pieces to maintain
and access the data at a better level. So, does table partitioning improve the performance of SQL
servers? Yes! This process decreases the price of storing a huge amount of data and improves
performance and manageability.
Q58). Explain the Data Dictionary.
It is a set of information explaining the content and structure of the tables and database objects. This
information controls, manipulates, and access the relationship between database elements.
Q59). What do you understand about Database Triggers?
Database Trigger is a set of commands that get executed when an event such as Before Insert, After
Insert, On Update, and On Delete of row occurs in a table.
Q60). Explain Codd’s 12 rules for an RDBMS.
An entity can be taken as an object or thing with independent existence. An entity set is a collection of
all entities within a database. Sometimes, if an entity set does not have all the necessary attributes to
define key constraints and other logical relationships, then it is termed as a weak entity set. If an
entity set has all the necessary attributes to define the primary key and other constraints, it is termed
a strong entity set.
Q61). What do you understand by the terms like DDL, VDL, SDL, and DSDL in RDMS?
DDL can be defined as the database schema that specifies a set of definitions through a special
language called DDL.
VDL gives information about views and their mapping with the conceptual schema.
SDL gives information about the internal schema and defines the relationship among two storage
schemas.
DSDL defines the storage structures or access methods utilized by databases.
Q62). What are the different relational operators that can be applied to a database?
A wider range of relational operators that can be applied to a database can be given as: SQL Server
operators.
A Union operator is used to combine multiple rows to avoid duplicate content.
An intersect operator is used for finding common elements within a row.
A Cartesian operator is used as a cross-join operator to apply on two relations.
A difference operator is used to identify the different values in multiple rows.
Q63). What is the significance of ACID properties for a database?
1. Atomicity
2. Consistency
3. Isolation
4. Durability
These four properties are considered highly important for any database. These properties make a
database easy to access and use. It is possible to share data among tables conveniently. Also, it
focuses on data accuracy and avoids redundancy.
Q64). How are DBMS and RDBMS different from each other? Give some meaningful differences.
DBMS tells about data storage and data creation. RDBMS explains relations among tables and data
values. DBMS operations can be used for a specific database, but RDBMS can work on multiple
databases together. Find more points of differences in how to differentiate between DBMS and
RDBMS.
Q65). When designing a database, how many relationships can you define?
When designing a database, three types of relationships can be defined. These are:
1. One to One
2. One to Many
3. Many to Many
Q66). As we know, there are various normalization forms. So, can you explain the difference
between 4NF and 5NF?
In the 4NF, it should satisfy the 3NF and not contain two or more views about an entity. In the 5NF, we
can reconstruct the information from small pieces of content so that they can be maintained with
maximum consistency.
Q67). One of system architects' biggest challenges is delivering maximum throughput so that
millions of transactions can be exceeded per second. So, how will you handle this challenge with
care? Justify your answer based on your previous work experience.
Whenever you are working on big data problems, it should be handled with care. Let us understand
the concept with three technical terms Data Ingestion, Transformations, Storage & Analytics.
Data Ingestion uses technologies like Apache Kafka and gracefully streamlines the data across
different targets. The second term is transformation, where data is reconstructed and transformed
into a meaningful real-time solution.
The last term is Storage & analytics, where No SQL database can be utilized to manage all data issues
and works on consistency problems eventually. Once you are done with it, these three features can
give you more flexibility, high throughput, and low-latency benefits. In brief, we should replace the
traditional batch-oriented approach with modern streaming solutions. If you are a beginner, then you
can learn more about No SQL through a comprehensive No SQL tutorial for beginners.
Q68). How can views be named as Data independence standards?
A “view” is defined as a subset of a database or tables stored in it. It can be used to retrieve, delete, or
combine the data. Each View can be taken as a separate table and accessed for the application. When
changes are made to a specific VIEW, it will not impact others. This is the reason why VIEWS should be
learned first to understand the concept of Data Independence in detail.
Q69). What is a Weak and Strong Entity Set according to your past experiences?
An entity can be taken as an object or thing with independent existence. An entity set is a collection of
all entities within a database. Sometimes, if an entity set does not have all the necessary attributes to
define key constraints and other logical relationships, then it is termed a weak entity set. If an entity
set has all the necessary attributes to define the primary key and other constraints, it is termed a
strong entity set.
Q70). Explain the terms ‘Record’, ‘Field’, and ‘Table’ in terms of database.
Record: It refers to a collection of values of a specific entity.
Field: This is an area within a record which is reserved for specific data.
Table: This is also a collection of records but specific types.
Q71). What is the difference between Cluster and Non-Cluster Index?
There is a major difference between cluster and non-cluster indexes. Clustered indexes make changes
in the table and reorder how records are stored there. Nonclustered indexes also make changes in the
data stored in the tablet, but it makes a completely different object within the table.
Q72). What do you understand by ‘Atomicity’ and ‘Aggregation’?
Atomicity: It is the condition where all the transaction's actions are performed or none. This means if
there is an incomplete transaction, the DBMS will undo the pending transactions' impacts.
Aggregation: It expresses the relationship with the entities’ collection and their relationship.
Q73). What are all types of user-defined functions?
There are three types of user-defined functions.
Scalar Functions in SQL
Inline Tablet value Functions
Multi-Statement Valued Functions
Q74). What is Online Transaction Processing (OLTP)?
OLTP is used to manage transaction-based applications; it is used for data entry, data retrieval, and
data processing. It makes data management efficient. The purpose of the OLTP system is to serve real-
time transactions.
Q75). Name the different data models that are available for database systems.
Here is the list of three different data models that are available for various purpose of database
systems:
Relational Model
Network Model
Hierarchical Model
Q76). What are Union, minus, and Interact commands?
Union: It combines the outputs of two tables, eliminating the duplicate rows from the tables. Use SQL
union all operators.
Minus: It returns rows from the first query but not from the second query. When you match records
of the first and the second query and other rows, you can see the query as a result set.
Intersect: It is used to return rows that both queries return.
Q77). Explain character manipulation functions. Explains its different types in SQL.
Character manipulation functions effectively extract, edit, format, or modify in some way a character
string. Character manipulation functions can be used to manipulate char. Strings. Different types of
character manipulation functions are as follows:
CONCAT, SUBSTR, INSTR, LPAd, RPAD, TRIM and REPLACE.
Different types of SQL:
Trim: The SQL trim helps to get rid of the leading and trailing characters from a character string. Learn
more about what is the order of operation with LTRIM/RTRIM/ISNULL in SQL server.
Translate: Translate replaces a sequence of characters in a string with another sequence of characters.
It replaces one character at a time.
Q78). Explain the Primary Key and Composite Key.
The primary key is the combination of fields that uniquely specify a row. It is a unique key that has an
implicit NOT NULL constraint. It means its values cannot be NULL.
The form of the candidate key is referred to as a composite key, a set of columns that uniquely figure
out every brown in the tablet.
Also, know why Oracle is the perfect choice for the success of an organization; holding an Oracle
Database Certification will help you validate your proficiency & grow your career in this field.
Q79). What do you mean by cardinality and its types?
Cardinality is defined as its equivalence class under equinumerosity. Simply, it is described as a
fundamental relationship between two entities or objects. There are three types of cardinalities- one-
to-one, one-to-many, and many-to-many.
Q80). What do you understand about B-Trees?
It basically represents the data structure in the form of a tree for external memory that reads and
writes large data blocks. It is generally used in databases and file systems where all the insertions,
deletions, sorting, etc., are done in logarithmic time.
Q81). Explain the functionality of the DML Compiler.
The work of a DML compiler is to convert the DML statements into a query language that the query
evaluation engineer can understand and process. The DML Compiler is needed since the DML is a
family of syntax elements that are quite similar to the other programming language that needs
compilation. That is why compiling the code in a language the query evaluation engine can understand
is important.
Q82). How can you distinguish between OLAP and OLTP?
Online transaction processing is referred to as OLTP, whereas online analytical processing is called
OLAP. OLTP stands for online database modification, while OLAP stands for online database query
response.
Q83). What is the use of the NVL() function?
Null values can be replaced with default values using the NVL function. If the first parameter is null,
the function returns the second parameter's value. If the first parameter is anything other than null, it
is ignored. This function is only accessible in Oracle; SQL and MySQL are not supported.
Check out our top SQL server interview questions and answers to prepare well for your upcoming SQL
developer interviews.
Q84). Distinguish between Rank() and DenseRank().
Here are the differences between DENSE_RANK vs RANK functions in SQL.
The rank of each row within your sorted partition is determined by the RANK() function in the result
set. The DENSE RANK() method assigns a unique rank to each row inside a partition based on the
provided column value, with no gaps.
Q85). What do you understand by NoSQL?
NoSQL databases are designed for certain data models, such as graphs, documents, key-pairs, and
wide-column tables. Unlike relational databases, they feature flexible schemas. NoSQL databases are
popular because of their ease of use, functionality, and scalability. Unlike SQL databases, they can be
expanded horizontally across hundreds or thousands of servers.
Did Al set to grow in SQL? To help you navigate through the journey successfully, here is a guide on
How to Become a SQL Professional.
Q86). What do you understand by Concurrency Control?
Concurrency control is a database management system process that ensures that concurrent activities
do not clash.
Q87). What are various database locks and their types?
Locks are commonly used to ensure that only one user/session can modify a certain piece of data.
There are different types of database locks:
Shared Lock - When a request for a shared lock on a table is approved, the table becomes read-only.
Other read operations can share this lock, allowing them to read the table simultaneously.
Exclusive Lock - When an operation seeks an exclusive lock on a table, and it is granted, it has
exclusive permission to write to the table. Other activities will be prevented if they request access to
the locked table.
Q88). What do you understand by Data Warehousing?
Data Warehouse is the process of gathering data from several sources (extracting, converting, and
loading) and storing it in a single database. The data warehouse can be considered a central repository
where data flows from transactional systems and other relational databases.
Q89). What do you understand by lock escalation?
Lock escalation occurs when a system combines numerous locks into a single higher-level lock, usually
to free up resources taken up by many fine-grained locks.
Q90). What do you understand by lock contention?
Lock contention arises when numerous operations request an exclusive lock on the same table.
Operations must wait in a queue in this situation. If you have ongoing lock contention, you must divide
those data blocks further so multiple processes can gain exclusive lock simultaneously.
Q91). What do you understand by hashing, and what are its advantages?
Hashing is a search method. A method of mapping keys to values. Hash functions take a string of
characters and turn it into a fixed-length value that may be used as an index to find the original
element.
Advantages of hashing:
It can be used to index and retrieve entries from a database in real-time, which is quicker than
conventional search methods.
It is an ideal data structure for point look-up.
Q92). What are the best practices to improve query performance?
The best practices to improve query performance are:
Multiple joins in a single query should be avoided.
Instead of using sub-queries, use joins.
For regularly used data and more complicated searches, utilize stored procedures.
To limit the size of your results, use WHERE expressions.
Q93). What do you understand by the term ‘Write Ahead Log’ in DBMS?
The Write Ahead Log is a database system approach for maintaining the atomicity and durability of
writes. The WAL's main principle is that before we make any actual changes to the database state, we
must first log the whole set of activities we want to be atomic and durable for storage.
Q94). What does ALIAS stand for?
A table or column may be given an ALIAS name. Use this alias name in the WHERE clause to identify
the table or column. Aliases are put to use in order to assign a table, or a column, a temporary name.
They’re usually used for making column names more eBay to read.
Alias exists only for till the duration of that SQL query.
Q95). What do Scalar and Aggregate Functions do?
To assess mathematical calculations and return single values, we employ aggregate functions. From a
table's columns, one can compute this. Based on the input value, scalar functions return a single value.
Q96). Define Phantom Deadlock.
Phantom deadlock detection refers to the situation when a deadlock does not actually exist but is still
detected by deadlock detection techniques as a result of a delay in the propagation of local
information.
Q97). What is a Checkpoint?
The inconsistent state is before the checkpoint, which is the point at which all the logs are
permanently recorded on the storage drive. The system can restart from the checkpoint in the event
of crashes, saving time and effort.
Q98). What is Database Partitioning?
Database partitioning, or data partitioning, applies to the process of breaking the data present in the
application’s table into distinct partitions. You can easily store, manage and access these data
partitions independently.
In order to manage and access the data at a finer level, database partitioning involves dividing tables
and indexes into smaller sections. Here‘s a guide on how to order and partition by multiple columns.
Q99). Why is Database Partitioning Important?
The benefits of database splitting include increased manageability and query performance.
It makes routine administrative duties easier.
It serves as a vital building block for systems with very high availability needs.
It enables access to a significant portion of a single partition.
Q100). Establish stored procedures.
A stored procedure is a group of pre-compiled SQL queries that, when run, represent a program that
accepts input, processes it, and outputs the results.
In other words, a stored procedure is a group of SQL statements with allocated name, that are saved
in a RDBMS as a set, so that it could be recycled and shared using several programs.
Q101). Explain the differences between the commands “DELETE,” “TRUNCATE,” and “DROP.”
The data can be recovered using the COMMIT and ROLLBACK statements after running the "DELETE"
action.
Following the completion of the "TRUNCATE" operation, the statements "COMMIT" and "ROLLBACK"
cannot be used to recover the deleted data.
Use the' DROP' command to remove a table or key, such as the primary key or foreign key. Find more
points of difference between DELETE vs TRUNCATE SQL here.
Q102). What is black box testing for databases?
A software testing technique called "black box testing" involves testing the functionality of software
programs without being aware of the internal code structure, implementation specifics, or internal
paths. Black Box Testing is a sort of software testing that is only motivated by software requirements
and specifications and focuses on the input and output of software applications. An alternative term
for it is behavioral testing.
Q103). Why is Oracle the most popular relational database?
Relational databases interview questions frequently include Oracle because it is the most widely used
RDBMS. Its fully scalable relational database architecture accounts for its popularity. Oracle database
products provide customers with versions that are both high-performing and economical.
The Oracle database provides a built-in network component that enables network communications. As
a result, it has become the preferred option for leading international corporations that manage and
process data across wide and local area networks.
Q104). Recursive stored procedure: what is it?
A stored process that continuously invokes itself until it encounters a boundary condition
Programmers can reuse the same code multiple times thanks to this recursive function or process.
Q105). What kinds of collation sensitivity are there?
The following is a list of collation sensitivity variations.
Case Sensitivity: A, A, and B, B
Accent Perception.
Japanese Kana characters, or Kana Sensitivity.
Single-byte and double-byte characters that are sensitive to width.
Q106). What are local and global variables and their differences?
Local variables are those that can be utilized or already exist within a function. They cannot be
referred to or used since the other functions are unaware of them. Every time that function is invoked,
variables can be created.
The variables that can be used or are present throughout the entire program are known as global
variables. No two variables that have been declared globally may be utilized in functions. When that
function is called repeatedly, global variables cannot be generated.
Q107). What are Constraints?
SQL constraints are used to limit the table's data type options. It can be supplied when the table
statement is being created or modified. The list of restrictions includes UNIQUE PRIMARY KEY,
FOREIGN KEY, NOT NULL CHECK BY DEFAULT
Q108). How are views and data independence related?
The view is a fictitious table kept active so that users can view their data even if it doesn't exist.
It comes from the fundamental table. The view directly reflects the file and is kept in the data
dictionary.
Views do not reflect base table updating or reconstruction.
As it occurs at the logical level and not the physical level, it is related to logical data independence.
Q109). What is 1NF in the DBMS?
1NF is known as the First Normal Form.
The domain of an attribute should only have atomic values in this kind of normalization, which is the
simplest. The purpose of this is to eliminate any duplicate columns from the table.
Q110). What does a SQL CLAUSE mean?
This is a crucial RDBMS question and answer.
This is used in conjunction with SQL queries to retrieve specified data based on user requirements and
SQL-defined constraints. This is particularly useful for selecting specific records from the entire set of
records. Find more information about SQL having clause functions to learn more about SQL clauses.
Q111). What are the uses of DBMS?
Following are some of the uses of DBMS:
Authentication and authorization configuration.
Simple to set up user accounts, mention access policies, and change limitations and access scopes.
Offers data backups.
Performance tuning.
Data recovery.
Q112). What are RDBMS examples? And main components of REDBMS
A few examples of RDBMS include - Oracle, Microsoft SQLServer, MySQL, and PostgreSQL. RDBMS
consists of numerous components like - tables, records, attributes, instances, schemas, keys, etc.
Q113). What is the difference between Extension and Intention?
Extension - Refers to the total no of tuples in a database at any given time and is completely
dependent on the time.
Intension - It doesn’t depend on the time and explains the database’s name, configuration, and
restrictions.
Q114). What is a Buffer Manager in RDBMS?
In a relational database management system, a buffer manager enables relational tasks, heap files,
access methods to read/write, allocate and de-allocate pages, etc. These tasks are performed on disc
pages by fundamental database class objects, which the buffer manager appeals to.
Q115). Describe a NULL Value.
Understanding the dissimilarities between NULL and other values, like zero or fields with spaces. In a
database, a NULL value is in a field containing no values. At the time of constructing a record, a field
with a NULL value shows that it is empty.
Learn SQL Server in the Easiest Way
Learn from the videos
Learn anytime anywhere
Pocket-friendly mode of learning
Complimentary eBook available
Buy Self-learning at Discounted Price