0% found this document useful (0 votes)
5 views88 pages

Mysql Viva

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 88

MySQL is a Free open-source Relational Database Management System(RDMS) that stores data in a

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:

Tired of interviewing candidates to find the best developers?


Hire top vetted developers within 4 days.
Hire Now
Intermediate MySQL interview questions and answers
1.
How do you use the GROUP_CONCAT() function in MySQL?
The GROUP_CONCAT() function in MySQL is an aggregate function used to concatenate non-NULL
values from a column into a single string, with an optional separator. It's particularly useful when you
want to combine multiple rows' values into a single row in the context of a GROUP BY clause or a
grouped result.
Here's the syntax for the GROUP_CONCAT() function:
GROUP_CONCAT(expression [SEPARATOR separator])
expression: The column or expression whose values you want to concatenate.
separator: An optional string used to separate the concatenated values. If not specified, a comma (,) is
used as the default separator.
2.
What is a pivot table, and how do you create one in MySQL?
A pivot table is a data processing technique used to summarize, aggregate, or reorganize data from a
larger dataset in a tabular format. It allows you to transform rows into columns, typically used to
display data in a more compact and easily understandable way. MySQL does not have a built-in pivot
table feature, but you can create one using SQL queries.
To create a pivot table in MySQL, you can use a combination of aggregate functions like SUM, COUNT,
or AVG along with GROUP BY and CASE statements.
For example, let's say you have a sales table with the following columns: product_id, category,
sales_date, and amount. To create a pivot table that shows the total sales for each category, grouped
by month, you can use the following query:
This query groups the data by year and month, then calculates the total sales amount for each
category, pivoting the category rows into separate columns for a more readable presentation.
3.
How do you use the LIKE operator in MySQL?
The LIKE operator in MySQL is used to search for a specified pattern in a column. It is often utilized in
conjunction with the WHERE clause to filter rows based on partial matches in a string column. The two
wildcard characters used with the LIKE operator are % and _.
 % represents zero, one, or multiple characters.
 _ represents a single character.
Here are some examples of using the LIKE operator:
 Find rows where the name column starts with 'John':

 Find rows where the email column ends with '@example.com':

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:

 Define the query to populate the materialized view table:

 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:

Also read: Using MySQL with Python


41.
What is the MySQL shell, and how do you use it?
The MySQL Shell is an advanced client and code editor for MySQL that provides an interactive,
scriptable interface for working with databases. It features command history, autocompletion, syntax
highlighting, and can be used to issue SQL queries, manage database schema and data, and execute
administrative tasks. The MySQL Shell supports multiple programming languages, including JavaScript,
Python, and SQL.
To use the MySQL Shell, follow these steps:
 Install and launch the MySQL Shell
 Establish a connection to the MySQL server
 Switch to a specific language if needed
 Execute commands and queries
 Exit the MySQL Shell
42.
What is the MySQL Information Schema, and how do you use it?
The MySQL Information Schema is a database that contains meta-information about the structure and
configuration of the MySQL server instance, its databases, and objects such as tables, columns,
indexes, constraints, etc. It's a virtual database, meaning the data is not stored on disk but is
dynamically generated on-the-fly when queried.
The Information Schema consists of read-only views (INFORMATION_SCHEMA.TABLES,
INFORMATION_SCHEMA.COLUMNS, etc.) that provide various details about the server and its objects.
To use the MySQL Information Schema, you'll query these views using standard SQL SELECT
statements, just like any other table. For instance:
List all databases:

List all tables in a database:


Get information about columns in a specific table:

Find all indexes in a table:

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:

Import data into the destination table:


 Using MySQL Workbench MySQL Workbench provides a graphical interface and advanced tools for
data migration, including schema and data transfer between different MySQL servers and databases.
MySQL Workbench is appropriate for more complex migration tasks, including those involving changes
to the table structure and data transformations.
 Using custom scripts In some cases, you might need to write custom scripts using programming
languages (e.g., Python, PHP, or Java) to handle more specific data migration scenarios. These scripts
can utilize MySQL connectors to connect to both source and target databases, retrieve data, apply
transformations, and then insert data into the target database.
 ETL tools Extract, Transform, Load (ETL) tools are specifically designed to handle large-scale data
migration and transformation tasks. These tools, such as Apache NiFi, Talend, or Microsoft SQL Server
Integration Services (SSIS), provide a wide range of advanced features to manage the entire data
migration process, including pre- and post-migration tasks.
During data migration, it's essential to maintain data integrity, handle exceptions, and monitor the
process closely. Additionally, thorough testing should be conducted after the migration to ensure that
the data has been correctly transferred and transformed before deploying the new system in
production.
4.
How do you use MySQL with cloud-based services, such as Amazon RDS or Google Cloud SQL?
MySQL can be deployed and managed using various cloud-based services, including Amazon RDS
(Relational Database Service) and Google Cloud SQL. These cloud services make it easy to set up,
operate, scale, and maintain MySQL databases in the cloud.
Here's a brief overview of how to use MySQL with Amazon RDS and Google Cloud SQL:
Amazon RDS:
Create an RDS Instance: Sign in to the AWS Management Console, navigate to the RDS service, and
create an RDS instance by selecting MySQL as the database engine. Configure instance specifications,
storage settings, security groups, and other options as needed.
Connect to the RDS Instance: Once the RDS instance is provisioned, note the endpoint URL, port,
database username, and password. Use this information to connect to the RDS instance using any
MySQL client, such as MySQL Workbench or the MySQL command line.
Example (using MySQL command line):

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.

2) In which language MySQL has been written?


MySQL is written in C and C++, and its SQL parser is written in yacc.

3) What are the technical specifications of MySQL?


MySQL has the following technical specifications -
 Flexible structure
 High performance
 Manageable and easy to use
 Replication and high availability
 Security and storage management
 Drivers
 Graphical Tools
 MySQL Enterprise Monitor
 MySQL Enterprise Security
 JSON Support
 Replication & High-Availability
 Manageability and Ease of Use
 OLTP and Transactions
 Geo-Spatial Support

4) What is the difference between MySQL and SQL?


SQL is known as the standard query language. It is used to interact with the database like MySQL.
MySQL is a database that stores various types of data and keeps it safe.
A PHP script is required to store and retrieve the values inside the database.
ADVERTISEMENT
ADVERTISEMENT
SQL is a computer language, whereas MySQL is a software or an application
SQL is used for the creation of database management systems whereas MySQL is used to enable data
handling, storing, deleting and modifying data
5) 5. What is the difference between the database and the table?
There is a major difference between a database and a table. The differences are as follows:
 Tables are a way to represent the division of data in a database while the database is a collection of
tables and data.
 Tables are used to group the data in relation to each other and create a dataset. This dataset will be
used in the database. The data stored in the table in any form is a part of the database, but the
reverse is not true.
 A database is a collection of organized data and features used to access them, whereas the table is a
collection of rows and columns used to store the data.

6) Why do we use the MySQL database server?


First of all, the MYSQL server is free to use for developers and small enterprises.
MySQL server is open source.
MySQL's community is tremendous and supportive; hence any help regarding MySQL is resolved as
soon as possible.
MySQL has very stable versions available, as MySQL has been in the market for a long time. All bugs
arising in the previous builds have been continuously removed, and a very stable version is provided
after every update.
The MySQL database server is very fast, reliable, and easy to use. You can easily use and modify the
software. MySQL software can be downloaded free of cost from the internet.

7) What are the different tables present in MySQL?


There are many tables that remain present by default. But, MyISAM is the default database engine
used in MySQL. There are five types of tables that are present:
 MyISAM
 Heap
 Merge
 INNO DB
 ISAM

8) How to install MySQL?


Installing MySQL on our system allows us to safely create, drop, and test web applications without
affecting our live website's data. There are many ways to use MySQL on our system, but the best way
is to install it manually. The manual installation allows us to learn more about the system and provides
more control over the database. To see the installation steps of MySQL in Windows goes to the below
link:
https://www.javatpoint.com/how-to-install-mysql
Manual installation of MySQL has several benefits:
 Backing up, reinstalling, or moving databases from one location to another can be achieved in a
second.
 It provides more control to how and when MySQL server starts and closes.
 We can install MySQL anywhere, like in a portable USB drive.

9) How to check the MySQL version?


We can check the MySQL version on Linux using the below command:
1. mysql -v
If we use the MySQL in windows, opening the MySQL command-line tool displayed the version
information without using any flags. If we want to know more about the server information, use the
below statement:
1. SHOW VARIABLES LIKE "%version%";
It will return the output as below:
In this output, we can see the additional version information about the installed MySQL software like
innodb_version, protocol_version, version_ssl_library, etc.

10) How to add columns in MySQL?


A column is a series of cells in a table that stores one value for each row in a table. We can add
columns in an existing table using the ALTER TABLE statement as follows:
1. ALTER TABLE table_name
2. ADD COLUMN column_name column_definition [FIRST|AFTER existing_column];
To read more information, click here.

11) How to delete a table in MySQL?


We can delete a table in MySQL using the Drop Table statement. This statement removes the
complete data of a table, including structure and definition from the database permanently.
Therefore, it is required to be careful while deleting a table. After using the statement, we cannot
recover the table in MySQL. The statement is as follows:
1. DROP TABLE table_name;
To read more information, click here.

12) How to add foreign keys in MySQL?


The foreign key is used to link one or more tables together. It matches the primary key field of another
table to link the two tables. It allows us to create a parent-child relationship with the tables. We can
add a foreign key to a table in two ways:
 Using the CREATE TABLE Statement
 Using the ALTER TABLE Statement
Following is the syntax to define a foreign key using CREATE TABLE OR ALTER TABLE statement:
1. [CONSTRAINT constraint_name]
2. FOREIGN KEY [foreign_key_name] (col_name, ...)
3. REFERENCES parent_tbl_name (col_name,...)
To read more information, click here.

13) How to connect to the MySQL database?


MySQL allows us to connect with the database server in mainly two ways:
Using Command-line Tool
We can find the command-line client tool in the bin directory of the MySQL's installation folder. To
invoke this program, we need to navigate the installation folder's bin directory and type the below
command:
1. mysql
Next, we need to run the below command to connect to the MySQL Server:
1. shell>mysql -u root -p
Finally, type the password for the selected user account root and press Enter:
1. Enter password: ********
After successful connection, we can use the below command to use the:
1. USE database_name;
Using MySQL Workbench
We can make a connection with database using MySQL Workbench, simply clicking the plus (+) icon or
navigating to the menu bar -> Database -> Connect to Database, the following screen appears. Now,
you need to fill all the details to make a connection:

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.

14) How to change the MySQL password?


We can change the MySQL root password using the below statement in the new notepad file and save
it with an appropriate name:
1. ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';
Next, open a Command Prompt and navigate to the MySQL directory. Now, copy the following folder
and paste it in our DOS command and press the Enter key.
1. C:\Users\javatpoint> CD C:\Program Files\MySQL\MySQL Server 8.0\bin
Next, enter this statement to change the password:
1. mysqld --init-file=C:\\mysql-notepadfile.txt
Finally, we can log into the MySQL server as root using this new password. After launches the MySQL
server, it is to delete the C:\myswl-init.txt file to ensure the password change.
To read more information, click here.

15) How to create a database in MySQL Workbench?


To create a new database in MySQL Workbench, we first need to launch the MySQL Workbench and
log in using the username and password. Go to the Navigation tab and click on the Schema menu.
Right-click under the Schema menu and select Create Schema or click the database icon (red
rectangle), as shown in the following screen.
A new popup screen appears where we need to fill all the details. After entering the details, click on
the Apply button and then the Finish button to complete the database creation.
To read more information, click here.

16) How to create a table in MySQL Workbench?


Launch the MySQL Workbench and go to the Navigation tab and click on the Schema menu where all
the previously created databases are shown. Select any database and double click on it. It will show
the sub-menus where we need to select the Tables option.

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.

17) How to change the table name in MySQL?


Sometimes our table name is non-meaningful. In that case, we need to change or rename the table
name. MySQL provides the following syntax to rename one or more tables in the current database:
ADVERTISEMENT
1. mysql> RENAME old_table TO new_table;
If we want to change more than one table name, use the below syntax:
1. RENAME TABLE old_tab1 TO new_tab1,
2. old_tab2 TO new_tab2, old_tab3 TO new_tab3;
To read more information, click here.

18) How to change the database name in MySQL?


Sometimes we need to change or rename the database name because of its non-meaningful name. To
rename the database name, we need first to create a new database into the MySQL server. Next,
MySQL provides the mysqldump shell command to create a dumped copy of the selected database
and then import all the data into the newly created database. The following is the syntax of using
mysqldump command:
1. mysqldump -u username -p "password" -R oldDbName > oldDbName.sql
Now, use the below command to import the data into the newly created database:
1. mysql -u username -p"password" newDbName < oldDbName.sql
19) How to import a database in MySQL?
Importing database in MySQL is a process of moving data from one place to another place. It is a very
useful method for backing up essential data or transferring our data between different locations. For
example, we have a contact book database, which is essential to keep it in a secure place. So we need
to export it in a safe place, and whenever it lost from the original location, we can restore it using
import options.
ADVERTISEMENT
In MySQL, we can import a database in mainly two ways:
 Command Line Tool
 MySQL Workbench
To read more information for importing databases, click here.

20) How to change the column name in MySQL?


While creating a table, we have kept one of the column names incorrectly. To change or rename an
existing column name in MySQL, we need to use the ALTER TABLE and CHANGE commands together.
The following are the syntax used to rename a column in MySQL:
1. ALTER TABLE table_name
2. CHANGE COLUMN old_column_name new_column_name column_definition [FIRST|AFTER existing
_column];
Suppose the column's current name is S_ID, but we want to change this with a more appropriate title
as Stud_ID. We will use the below statement to change its name:
1. ALTER TABLE Student CHANGE COLUMN S_ID Stud_ID varchar(10);

21) How to delete columns in MySQL?


We can remove, drop, or delete one or more columns in an existing table using the ALTER TABLE
statement as follows:
1. ALTER TABLE table_name DROP COLUMN column_name1, column_name2....;
To read more information, click here.

22) How to insert data in MySQL?


We can insert data in a MySQL table using the INSERT STATEMENT. This statement allows us to insert
single or multiple rows into a table. The following is the basic syntax to insert a record into a table:
1. INSERT INTO table_name ( field1, field2,...fieldN )
2. VALUES ( value1, value2,...valueN );
If we want to insert more than one rows into a table, use the below syntax:
1. INSERT INTO table(field1, field2,...fieldN)
2. VALUES
3. (value1, value 2, ...),
4. (value1, value2, ...),
5. ...
6. (value1, value2, ...);
To read more information, click here.

23) How to delete a row in MySQL?


We can delete a row from the MySQL table using the DELETE STATEMENT within the database. The
following is the generic syntax of DELETE statement in MySQL to remove one or more rows from a
table:
1. DELETE FROM table_name WHERE Condition_specified;
It is noted that if we have not specified the WHERE clause with the syntax, this statement will remove
all the records from the given table.
To read more information, click here.
ADVERTISEMENT
24) How to join two tables in MySQL?
We can connect two or more tables in MySQL using the JOIN clause. MySQL allows various types of
JOIN clauses. These clauses connect multiple tables and return only those records that match the
same value and property in all tables. The following are the four easy ways to join two or more tables
in MySQL:
 Inner Join
 Left Join
 Right Join
 Cross Join
To read more information, click here.

25) How to join three tables in MySQL?


Sometimes we need to fetch data from three or more tables. There are two types available to do
these types of joins. Suppose we have three tables named Student, Marks, and Details.
Let's say Student has (stud_id, name) columns, Marks has (school_id, stud_id, scores) columns, and
Details has (school_id, address, email) columns.
1. Using SQL Join Clause
This approach is similar to the way we join two tables. The following query returns result from three
tables:
1. SELECT name, scores, address, email FROM Student s
2. INNER JOIN Marks m on s.stud_id = m.stud_id
3. INNER JOIN Details d on d.school_id = m.school_id;
2. Using Parent-Child Relationship
It is another approach to join more than two tables. In the above tables, we have to create a parent-
child relationship. First, create column X as a primary key in one table and as a foreign key in another
table. Therefore, stud_id is the primary key in the Student table and will be a foreign key in the Marks
table. Next, school_id is the primary key in the Marks table and will be a foreign key in the Details
table. The following query returns result from three tables:
1. SELECT name, scores, address, email
2. FROM Student s, Marks m, Details d
3. WHERE s.stud_id = m.stud_id AND m.school_id = d.school_id;
To read more information about the foreign key, click here.

26) How to update the table in MySQL?


We can update existing records in a table using the UPDATE statement that comes with the SET and
WHERE clauses. The SET clause changes the values of the specified column. The WHERE clause is
optional, which is used to specify the condition. This statement can also use to change values in one or
more columns of a single row or multiple rows at a time. Following is a generic syntax of UPDATE
command to modify data into the MySQL table:
1. UPDATE table_name
2. SET field1=new-value1, field2=new-value2, ...
3. [WHERE Clause]
To read more information, click here.

27) What is MySQL Workbench?


MySQL Workbench is a unified visual database designing or GUI tool used for working on MySQL
databases. It is developed and maintained by Oracle that provides SQL development, data migration,
and comprehensive administration tools for server configuration, user administration, backup, etc. We
can use this Server Administration to create new physical data models, E-R diagrams, and SQL
development. It is available for all major operating systems. MySQL provides supports for it from
MySQL Server version v5.6 and higher.
It is mainly available in three editions, which are given below:
 Community Edition (Open Source, GPL)
 Standard Edition (Commercial)
 Enterprise Edition (Commercial)
To read more information, click here.

28) How to drop the primary key in MySQL?


MySQL primary key is a single or combination of the field used to identify each record in a table
uniquely. A primary key column cannot be null or empty. We can remove or delete a primary key from
the table using the ALTER TABLE statement. The following syntax is used to drop the primary key:
1. ALTER TABLE table_name DROP PRIMARY KEY;
To read more information, click here.

29) How to create a Stored Procedure in MySQL?


A stored procedure is a group of SQL statements that we save in the database. The SQL queries,
including INSERT, UPDATE, DELETE, etc. can be a part of the stored procedure. A procedure allows us
to use the same code over and over again by executing a single statement. It stores in the database
data dictionary.
We can create a stored procedure using the below syntax:
ADVERTISEMENT
1. CREATE PROCEDURE procedure_name [ (parameter datatype [, parameter datatype]) ]
2. BEGIN
3. Body_section of SQL statements
4. END;
This statement can return one or more value through parameters or may not return any result. The
following example explains it more clearly:
1. DELIMITER $$
2. CREATE PROCEDURE get_student_info()
3. BEGIN
4. SELECT * FROM Student_table;
5. END$$
To read more information, click here.

30) How to execute a stored procedure in MySQL?


We can execute a stored procedure in MySQL by simply CALL query. This query takes the name of the
stored procedure and any parameters we need to pass to it. The following is the basic syntax to
execute a stored procedure:
1. CALL stored_procedure_name (argument_list);
Let's understand it with this example:
1. CALL Product_Pricing (@pricelow, @pricehigh);
Here, a stored procedure named Product_Pricing calculates and returns the lowest and highest
product prices.

31) How to create a View in MySQL?


A view is a database object whose values are based on the base table. It is a virtual table created by a
query by joining one or more tables. It is operated similarly to the base table but does not contain any
data of its own. If any changes occur in the underlying table, the same changes reflected in the View
also.
Following is the general syntax of creating a VIEW in MySQL:
1. CREATE [OR REPLACE] VIEW view_name AS
2. SELECT columns
3. FROM tables
4. [WHERE conditions];
To read more information, click here.
32) How to create a Trigger in MySQL?
A trigger is a procedural code in a database that automatically invokes whenever certain events on a
particular table or view in the database occur. It can be executed when records are inserted into a
table, or any columns are being updated. We can create a trigger in MySQL using the syntax as
follows:
1. CREATE TRIGGER trigger_name
2. [before | after]
3. {insert | update | delete}
4. ON table_name [FOR EACH ROW]
5. BEGIN
6. --variable declarations
7. --trigger code
8. END;
To read more information, click here.

33) How to clear screen in MySQL?


If we use MySQL in Windows, it is not possible to clear the screen before version 8. At that time, the
Windows operating system provides the only way to clear the screen by exiting the MySQL command-
line tool and then again open MySQL.
After the release of MySQL version 8, we can use the below command to clear the command line
screen:
1. mysql> SYSTEM CLS;

34) How to create a new user in MySQL?


A USER in MySQL is a record in the USER-TABLE. It contains the login information, account privileges,
and the host information for MySQL account to access and manage the databases. We can create a
new user account in the database server using the MySQL Create User statement. It provides
authentication, SSL/TLS, resource-limit, role, and password management properties for the new
accounts.
The following is the basic syntax to create a new user in MySQL:
1. CREATE USER [IF NOT EXISTS] account_name IDENTIFIED BY 'password';
To read more information, click here.

35) How to check USERS in MySQL?


If we want to manage a database in MySQL, it is required to see the list of all user's accounts in a
database server. The following command is used to check the list of all users available in the database
server:
1. mysql> SELECT USER FROM mysql.user;
To read more information, click here.

36) How to import a CSV file in MySQL?


MySQL allows us to import the CSV (comma separated values) file into a database or table. A CSV is a
plain text file that contains the list of data and can be saved in a tabular format. MySQL provides the
LOAD DATA INFILE statement to import a CSV file. This statement is used to read a text file and import
it into a database table very quickly. The full syntax to import a CSV file is given below:
1. LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/filename.csv'
2. INTO TABLE tablename
3. FIELDS TERMINATED BY ','
4. OPTIONALLY ENCLOSED BY '"'
5. LINES TERMINATED BY '\r\n'
6. IGNORE 1 ROWS;
To read more information, click here.
37) How to insert Date in MySQL?
MySQL allows us to use the INSERT STATEMENT to add the date in MySQL table. MySQL provides
several data types for storing dates such as DATE, TIMESTAMP, DATETIME, and YEAR. The default
format of the date in MySQL is YYYY-MM-DD. Following is the basic syntax to insert date in MySQL
table:
1. INSERT INTO table_name (column_name, column_date) VALUES ('DATE: Manual Date', '2008-7-04');
If we want to insert a date in the mm/dd/yyyy format, it is required to use the below statement:
1. INSERT INTO table_name VALUES (STR_TO_DATE(date_value, format_specifier));

38) How to check database size in MySQL?


MySQL allows us to query the information_schema.tables table to get the information about the
tables and databases. It will return the information about the data length, index length, collation,
creation time, etc. We can check the size of the database on the server using the below syntax:
1. SELECT table_schema AS 'Database Name',
2. SUM(data_length + index_length) 'Size in Bytes',
3. ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) 'Size in MB'
4. FROM information_schema.tables
5. WHERE table_schema = 'testdb'
6. GROUP BY table_schema;
It will return the output as follows:
If we want to check the size of the table in a specific database, use the following statement:
1. SELECT table_name AS 'Table Name',
2. ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'Size in MB'
3. FROM information_schema.TABLES
4. WHERE table_schema = 'testdb'
5. ORDER BY (data_length + index_length) DESC;
It will return the output as follows:

39) How does indexing works in MySQL?


Indexing is a process to find an unordered list into an ordered list. It helps in maximizing the query's
efficiency while searching on tables in MySQL. The working of MySQL indexing is similar to the book
index.
Suppose we have a book and want to get information about, say, searching. Without indexing, it is
required to go through all pages one by one, until the specific topic was not found. On the other hand,
an index contains a list of keywords to find the topic mentioned on pages. Then, we can flip to those
pages directly without going through all pages.

40) Who owns MySQL?


MySQL is the most popular free and open-source database software which comes under the GNU
General Public License. In the beginning, it was owned and sponsored by the Swedish company MySQL
AB. Now, it is bought by Sun Microsystems (now Oracle Corporation), who is responsible for managing
and developing the database.
To read more information, click here.

41) How to view the database in MySQL?


Working with the MySQL server, it is a common task to view or list the available databases. We can
view all the databases on the MySQL server host using the following command:
1. mysql> SHOW DATABASES;
To read more information, click here.

42) How to set auto increment in MySQL?


Auto Increment is a constraint that automatically generates a unique number while inserting a new
record into the table. Generally, it is used for the primary key field in a table. In MySQL, we can set the
value for an AUTO_INCREMENT column using the ALTER TABLE statement as follows:
1. ALTER TABLE table_name AUTO_INCREMENT = value;

43) How to find the second highest salary in MySQL?


MySQL uses the LIMIT keyword, which can be used to limit the result set. It will allow us to get the first
few rows, last few rows, or range of rows. It can also be used to find the second, third, or nth highest
salary. It ensures that you have use order by clause to sort the result set first and then print the output
that provides accurate results. The following query is used to get the second highest salary in MySQL:
1. SELECT salary
2. FROM (SELECT salary FROM employees ORDER BY salary DESC LIMIT 2) AS Emp ORDER BY salary LIMIT
1;
There are some other ways to find the second highest salary in MySQL, which are given below:
This statement uses subquery and IN clause to get the second highest salary:
1. SELECT MAX(salary)
2. FROM employees
3. WHERE salary NOT IN ( SELECT Max(salary) FROM employees);
This query uses subquery and < operator to return the second highest salary:
1. SELECT MAX(salary) From employees
2. WHERE salary < ( SELECT Max(salary) FROM employees);

44) What is the difference between TRUNCATE and DELETE in MySQL?


 TRUNCATE is a DDL command, and DELETE is a DML command.
 It is not possible to use Where command with TRUNCATE QLbut you can use it with DELETE command.
 TRUNCATE cannot be used with indexed views, whereas DELETE can be used with indexed views.
 The DELETE command is used to delete data from a table. It only deletes the rows of data from the
table while truncate is a very dangerous command and should be used carefully because it deletes
every row permanently from a table.

45) How many Triggers are possible in MySQL?


There are only six Triggers allowed to use in the MySQL database.
1. Before Insert
2. After Insert
3. Before Update
4. After Update
5. Before Delete
6. After Delete

46) What is the heap table?


Tables that are present in memory is known as HEAP tables. When you create a heap table in MySQL,
you should need to specify the TYPE as HEAP. These tables are commonly known as memory tables.
They are used for high-speed storage on a temporary basis. They do not allow BLOB or TEXT fields.

47) What is BLOB and TEXT in MySQL?


BLOB is an acronym that stands for a large binary object. It is used to hold a variable amount of data.
There are four types of the BLOB.
1. TINYBLOB
2. BLOB
3. MEDIUMBLOB
4. LONGBLOB
The differences among all these are the maximum length of values they can hold.
TEXT is a case-insensitive BLOB. TEXT values are non-binary strings (character string). They have a
character set, and values are stored and compared based on the collation of the character set.
There are four types of TEXT.
1. TINYTEXT
2. TEXT
3. MEDIUMTEXT
4. LONGTEXT

48) What is a trigger in MySQL?


A trigger is a set of codes that executes in response to some events.

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).

50) What is the difference between FLOAT and DOUBLE?


FLOAT stores floating-point numbers with accuracy up to 8 places and allocate 4 bytes. On the other
hand, DOUBLE stores floating-point numbers with accuracy up to 18 places and allocates 8 bytes.

51) What are the advantages of MySQL in comparison to Oracle?


1. MySQL is a free, fast, reliable, open-source relational database while Oracle is expensive, although
they have provided Oracle free edition to attract MySQL users.
2. MySQL uses only just under 1 MB of RAM on your laptop, while Oracle 9i installation uses 128 MB.
3. MySQL is great for database enabled websites while Oracle is made for enterprises.
4. MySQL is portable.

52) What are the disadvantages of MySQL?


1. MySQL is not so efficient for large scale databases.
2. It does not support COMMIT and STORED PROCEDURES functions version less than 5.0.
3. Transactions are not handled very efficiently.
4. The functionality of MySQL is highly dependent on other addons.
5. Development is not community-driven.

53) What is the difference between CHAR and VARCHAR?


1. CHAR and VARCHAR have differed in storage and retrieval.
2. CHAR column length is fixed, while VARCHAR length is variable.
3. The maximum no. of character CHAR data types can hold is 255 characters, while VARCHAR can hold
up to 4000 characters.
4. CHAR is 50% faster than VARCHAR.
5. CHAR uses static memory allocation, while VARCHAR uses dynamic memory allocation.

54) What is the difference between MySQL_connect and MySQL_pconnect?


Mysql_connect:
1. It opens a new connection to the database.
2. Every time you need to open and close the database connection, depending on the request.
3. Opens page whenever it is loaded.
Mysql_pconnect:
1. In Mysql_pconnect, "p" stands for persistent connection, so it opens the persistent connection.
2. The database connection cannot be closed.
3. It is more useful if your site has more traffic because there is no need to open and close connection
frequently and whenever the page is loaded.

55) What does "i_am_a_dummy flag" do in MySQL?


The "i_am_a_dummy flag" enables the MySQL engine to refuse any UPDATE or DELETE statement to
execute if the WHERE clause is not present. Hence it can save the programmer from deleting the
entire table my mistake if he does not use WHERE clause.

56) How to get the current date in MySQL?


To get current date, use the following syntax:
1. SELECT CURRENT_DATE();

57) What are the security alerts while using MySQL?


Install antivirus and configure the operating system's firewall.
Never use the MySQL Server as the UNIX root user.
Change the root username and password Restrict or disable remote access.

58) How to change a password for an existing user via mysqladmin?


Mysqladmin -u root -p password "newpassword".

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

61) What is the MySQL default port number?


MySQL default port number is 3306.

62) What is REGEXP?


REGEXP is a pattern match using a regular expression. The regular expression is a powerful way of
specifying a pattern for a sophisticated search.
Basically, it is a special text string for describing a search pattern. To understand it better, you can
think of a situation of daily life when you search for .txt files to list all text files in the file manager. The
regex equivalent for .txt will be .*\.txt.

63) How many columns can you create for an index?


You can a create maximum of 16 indexed columns for a standard table.

64) What is the difference between NOW() and CURRENT_DATE()?


NOW() command is used to show current year, month, date with hours, minutes, and seconds while
CURRENT_DATE() shows the current year with month and date only.

65) What is the query to display the top 20 rows?


SELECT * FROM table_name LIMIT 0,20;

66) Write a query to display the current date and time?


If you want to display the current date and time, use -
SELECT NOW();
If you want to display the current date only, use:
SELECT CURRENT_DATE();

67) What is the save point in MySQL?


A defined point in any transaction is known as savepoint.
SAVEPOINT is a statement in MySQL, which is used to set a named transaction savepoint with the
name of the identifier.

68) What is SQLyog?


SQLyog program is the most popular GUI tool for admin. It is the most popular MySQL manager and
admin tool. It combines the features of MySQL administrator, phpMyadmin, and others. MySQL front
ends and MySQL GUI tools.

69) How do you backup a database in MySQL?


It is easy to back up data with phpMyAdmin. Select the database you want to backup by clicking the
database name in the left-hand navigation bar. Then click the export button and make sure that all
tables are highlighted that you want to back up. Then specify the option you want under export and
save the output.

70) What are the different column comparison operators in MySQL?


The =, <>, <=, <, >=, >, <<, >>, < = >, AND, OR or LIKE operator are the comparison operators in MySQL.
These operators are generally used with SELECT statement.

71) Write a query to count the number of rows of a table in MySQL.


SELECT COUNT user_id FROM users;

72) Write a query to retrieve a hundred books starting from 20th.


SELECT book_title FROM books LIMIT 20, 100;

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);

74) What is the default port of MySQL Server?


The default port of MySQL Server is 3306.
75) How is the MyISAM table stored?
MyISAM table is stored on disk in three formats.
 '.frm' file : storing the table definition
 '.MYD' (MYData): data file
 '.MYI' (MYIndex): index file

76) What is the usage of ENUMs in MySQL?


ENUMs are string objects. By defining ENUMs, we allow the end-user to give correct input as in case
the user provides an input that is not part of the ENUM defined data, then the query won't execute,
and an error message will be displayed which says "The wrong Query". For instance, suppose we want
to take the gender of the user as an input, so we specify ENUM('male', 'female', 'other'), and hence
whenever the user tries to input any string any other than these three it results in an error.
ENUMs are used to limit the possible values that go in the table:
For example:
CREATE TABLE months (month ENUM 'January', 'February', 'March'); INSERT months VALUES ('April').

77) What are the advantages of MyISAM over InnoDB?


MyISAM follows a conservative approach to disk space management and stores each MyISAM table in
a separate file, which can be further compressed if required. On the other hand, InnoDB stores the
tables in the tablespace. Its further optimization is difficult.

78) What are the differences between MySQL_fetch_array(), MySQL_fetch_object(),


MySQL_fetch_row()?
Mysql_fetch_object is used to retrieve the result from the database as objects, while
mysql_fetch_array returns result as an array. This will allow access to the data by the field names.
For example:
Using mysql_fetch_object field can be accessed as $result->name.
Using mysql_fetch_array field can be accessed as $result->[name].
Using mysql_fetch_row($result) where $result is the result resource returned from a successful query
executed using the mysql_query() function.
Example:
1. $result = mysql_query("SELECT * from students");
2. while($row = mysql_fetch_row($result))
3. {
4. Some statement;
5. }

79) What is the difference between mysql_connect and mysql_pconnect?


Mysql_connect() is used to open a new connection to the database, while mysql_pconnect() is used to
open a persistent connection to the database. It specifies that each time the page is loaded,
mysql_pconnect() does not open the database.

80) What is the use of mysql_close()?


Mysql_close() cannot be used to close the persistent connection. However, it can be used to close a
connection opened by mysql_connect().

81) What is MySQL data directory?


MySQL data directory is a place where MySQL stores its data. Each subdirectory under this data
dictionary represents a MySQL database. By default, the information managed my MySQL = server
mysqld is stored in the data directory.

82) How do you determine the location of MySQL data directory?


The default location of MySQL data directory in windows is C:\mysql\data or C:\Program Files\MySQL\
MySQL Server 5.0 \data.

83) What is the usage of regular expressions in MySQL?


In MySQL, regular expressions are used in queries for searching a pattern in a string.
 * Matches 0 more instances of the string preceding it.
 + matches one more instances of the string preceding it.
 ? Matches 0 or 1 instances of the string preceding it.
 . Matches a single character.
 [abc] matches a or b or z
 | separates strings
 ^ anchors the match from the start.
 "." Can be used to match any single character. "|" can be used to match either of the two strings
 REGEXP can be used to match the input characters with the database.
Example:
The following statement retrieves all rows where column employee_name contains the text 1000
(example salary):
1. Select employee_name
2. From employee
3. Where employee_name REGEXP '1000'
4. Order by employee_name

84) What is the usage of the "i-am-a-dummy" flag in MySQL?


In MySQL, the "i-am-a-dummy" flag makes the MySQL engine to deny the UPDATE and DELETE
commands unless the WHERE clause is present.

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.

86) What is InnoDB?


InnoDB is a storage database for SQL. The ACID-transactions are also provided in InnoDB and also
includes support for the foreign key. Initially owned by InnobaseOY now belongs to Oracle Corporation
after it acquired the latter since 2005.

87) What is ISAM?


It is a system for file management developed by IBM, which allows records to access sequentially or
even randomly.

88) How can we run batch mode in MySQL?


To perform batch mode in MySQL, we use the following command:
1. mysql;
2. mysql mysql.out;

89) What are federated tables?


Federated tables are tables that point to the tables located on other databases on some other server.

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.

91) What are the drivers in MySQL?


Following are the drivers available in MySQL:
 PHP Driver
 JDBC Driver
 ODBC Driver
 C WRAPPER
 PYTHON Driver
 PERL Driver
 RUBY Driver
 CAP11PHP Driver
 Ado.net5.mxz

92) What are DDL, DML, and DCL?


Majorly SQL commands can be divided into three categories, i.e., DDL, DML & DCL. Data Definition
Language (DDL) deals with all the database schemas, and it defines how the data should reside in the
database. Commands like CreateTABLE and ALTER TABLE are part of DDL.
Data Manipulative Language (DML) deals with operations and manipulations on the data. The
commands in DML are Insert, Select, etc.
Data Control Languages (DCL) are related to the Grant and permissions. In short, the authorization to
access any part of the database is defined by these.
Basic MySQL Interview Questions
1. What are the String Data Types in MySQL?
Type Name Meaning
CHAR fixed-length nonbinary(character) string
VARCHAR variable-length nonbinary string
BINARY fixed-length binary string
VARBINARY variable-length binary string
TINYBLOB Very small BLOB(binary large object)
BLOB Small BLOB
MEDIUMBLOB Medium-sized BLOB
LONGBLOB Large BLOB
TINYTEXT A very small nonbinary string
TEXT Small nonbinary string
MEDIUMTEXT Medium-sized nonbinary string
LONGTEXT Large nonbinary string
ENUM An enumeration; each column value is assigned, one enumeration member
SET A set; each column value is assigned zero or more set members
NULL in SQL is the term used to represent a missing value. A NULL value in a table is a
NULL value in a field that appears to be blank. This value is different than a zero value or a
field that contains spaces.

Create a free personalised study plan


Get into your dream companies with expert guidance

Real-Life Problems
Prep for Target Roles

Custom Plan Duration

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’;

3. What is BLOB in MySQL?


BLOB is an acronym that stands for a binary large object. It is used to hold a variable amount of data.
There are four types of BLOB:
 TINYBLOB
 BLOB
 MEDIUMBLOB
 LONGBLOB
A BLOB can hold a very large amount of data. For example - documents, images, and even videos. You
could store your complete novel as a file in a BLOB if needed.
You can download a PDF version of Mysql Interview Questions.
Download PDF

4. What are the Temporal Data Types in MySQL?


Type Name Meaning
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
Example: To select the records with an Order Date of "2018-11-11" from a table:
SELECT * FROM Orders WHERE OrderDate='2018-11-11'
5. What is MySQL?
MySQL is a database management system for web servers. It can grow with the website as it is highly
scalable. Most of the websites today are powered by MySQL.
6. What are the Numeric Data Types in MySQL?
MySQL has numeric data types for integer, fixed-point, floating-point, and bit values, as shown in the
table below. Numeric types can be signed or unsigned, except BIT. A special attribute enables the
automatic generation of sequential integer or floating-point column values, which is useful for
applications that require a series of unique identification numbers.
Type Name Meaning
TINYINT Very Small Integer
SMALLINT Small Integer
MEDIUMINT Medium-sized Integer
INT Standard Integer
BIGINT Large Integer
DECIMAL Fixed-point number
FLOAT Single-precision floating-point number
DOUBLE Double-precision floating-point number
Type Name Meaning
BIT Bit-field
7. How do you view a database in MySQL?
One can view all the databases on the MySQL server host using the following command:
mysql> SHOW DATABASES;

Advance your career with Mock Assessments


Real-world coding challenges for top company interviews

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;

Get Access to 250+ Guides with Scaler Mobile App!


Experience free learning content on the Scaler Mobile App
4.5
100K+
Play Store
13. How do you create a database in MySQL?
Use the following command to create a new database called ‘books’:
CREATE DATABASE books;
14. What are some of the common MySQL commands?
Command Action
ALTER To alter a database or table
BACKUP To back-up a table
\c To cancel Input
CREATE To create a database
DELETE To delete a row from a table
DESCRIBE To describe a table's columns
DROP To delete a database or table
EXIT(ctrl+c) To exit
GRANT To change user privileges
HELP (\h, \?) Display help
INSERT Insert data
LOCK Lock table(s)
QUIT(\q) Same as EXIT
RENAME Rename a Table
SHOW List details about an object
SOURCE Execute a file
STATUS (\s) Display the current status
TRUNCATE Empty a table
UNLOCK Unlock table(s)
UPDATE Update an existing record
USE Use a database
15. What are MySQL Database Queries?
A query is a specific request or a question. One can query a database for specific information and have
a record returned.
16. How can you interact with MySQL?
There are three main ways you can interact with MySQL:
 using a command line
 via a web interface
 through a programming language
17. What does a MySQL database contain?
A MySQL database contains one or more tables, each of which contains records or rows. Within these
rows are various columns or fields that contain the data itself.
18. What does SQL in MySQL stand for?
The SQL in MySQL stands for Structured Query Language. This language is also used in other databases
such as Oracle and Microsoft SQL Server. One can use commands such as the following to send
requests from a database:
SELECT title FROM publications WHERE author = ' J. K. Rowling’;
Note that SQL is not case sensitive. However, it is a good practice to write the SQL keywords in CAPS
and other names and variables in a small case.
You can check out this SQL Tutorial to learn more about SQL.
19. What do you mean by ‘databases’?
A database is a structured collection of data stored in a computer system and organized in a way to be
quickly searched. With databases, information can be rapidly retrieved.
20. What are some of the advantages of using MySQL?
 Flexibility: MySQL runs on all operating systems
 Power: MySQL focuses on performance
 Enterprise-Level SQL Features: MySQL had for some time been lacking in advanced features such as
subqueries, views, and stored procedures.
 Full-Text Indexing and Searching
 Query Caching: This helps enhance the speed of MySQL greatly
 Replication: One MySQL server can be duplicated on another, providing numerous advantages
 Configuration and Security
Intermediate MySQL Interview Questions
1. What are the types of relationships used in MySQL?
There are three categories of relationships in MySQL:
 One-to-One: Usually, when two items have a one-to-one relationship, you just include them as
columns in the same table.
 One-to-Many: One-to-many (or many-to-one) relationships occur when one row in one table is linked
to many rows in another table.
 Many-to-Many: In a many-to-many relationship, many rows in one table are linked to many rows in
another table. To create this relationship, add a third table containing the same key column from each
of the other tables
2. What are the MySQL clients and utilities?
Several MySQL programs are available to help you communicate with the server. For administrative
tasks, some of the most important ones are listed here:
• mysql—An interactive program that enables you to send SQL statements to the server and to view
the results. You can also use mysql to execute batch scripts (text files containing SQL statements).
• mysqladmin—An administrative program for performing tasks such as shutting down the server,
checking its configuration, or monitoring its status if it appears not to be functioning properly.
• mysqldump—A tool for backing up your databases or copying databases to another server.
• mysqlcheck and myisamchk—Programs that help you perform table checking, analysis, and
optimization, as well as repairs if tables become damaged. mysqlcheck works with MyISAM tables and
to some extent with tables for other storage engines. myisamchk is for use only with MyISAM tables.
3. What is the MySQL server?
The server, mysqld, is the hub of a MySQL installation; it performs all manipulation of databases and
tables.
4. How many Triggers are possible in MySQL?
There are six Triggers allowed to use in the MySQL database:
 Before Insert
 After Insert
 Before Update
 After Update
 Before Delete
 After Delete
5. What are MySQL Triggers?
A trigger is a task that executes in response to some predefined database event, such as after a new
row is added to a particular table. Specifically, this event involves inserting, modifying, or deleting
table data, and the task can occur either prior to or immediately following any such event.
Triggers have many purposes, including:
 Audit Trails
 Validation
 Referential integrity enforcement
6. How do you create and execute views in MySQL?
Creating a view is accomplished with the CREATE VIEW statement. As an example:
CREATE
[OR REPLACE]
[ALGORITHM = {MERGE | TEMPTABLE | UNDEFINED }]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
7. What are MySQL “Views”?
In MySQL, a view consists of a set of rows that is returned if a particular query is executed. This is also
known as a ‘virtual table’. Views make it easy to retrieve the way of making the query available via an
alias.
The advantages of views are:
 Simplicity
 Security
 Maintainability
Advanced MySQL Interview Questions
1. What are Transaction Storage Engines in MySQL?
To be able to use MySQL’s transaction facility, you have to be using MySQL’s InnoDB storage engine
(which is the default from version 5.5 onward). If you are not sure which version of MySQL your code
will be running on, rather than assuming InnoDB is the default engine you can force its use when
creating a table, as follows.
2. What is Sharding in SQL?
The process of breaking up large tables into smaller chunks (called shards) that are spread across
multiple servers is called Sharding.
The advantage of Sharding is that since the sharded database is generally much smaller than the
original; queries, maintenance, and all other tasks are much faster.
3. What is Scaling in MySQL?
In MySQL, scaling capacity is actually the ability to handle the load, and it’s useful to think of load from
several different angles such as:
 Quantity of data
 Number of users
 User activity
 Size of related datasets
4. Can you explain the logical architecture of MySQL?
The top layer contains the services most network-based client/server tools or servers need such as
connection handling, authentication, security, and so forth.
The second layer contains much of MySQL’s brains. This has the code for query parsing, analysis,
optimization, caching, and all the built-in functions.
The third layer contains the storage engines that are responsible for storing and retrieving the data
stored in MySQL.

MySQL DBA Interview Questions


Q1. Can you tell the difference between Mysql_connect And Mysql_pconnect?
Used to open a new connection to a database.
You can open and close the database connection based on the
Mysql_connect
request.
Opens a page everytime the page is loaded.
Mysql_connect vs Mysql_pconnect
Mysql_pconnect Used to open a persistent connection in a database.
You cannot close the database connection.
There is no need to open and close a connection everytime a page is
loaded.
Q2. What is the default port for MySQL server?
MySQL Server’s default port is 3306. Apart from this, another standard default port for the SQL Server
in TCP/IP is 1433.
Q3. Can you tell what are the different set operations available in MySQL?
The various set operations available in MySQL are as follows:
 UNION – This operation returns all the distinct rows selected by a query
 UNION ALL – This operation returns all the rows selected by a query and also includes all duplicate
rows.
 MINUS – This operation returns all the distinct rows selected by the first query but does not select the
rows selected by the second query.
 INTERSECT – This operation returns all the distinct rows selected by both queries.
Refer to the below image:
Q4. Can you tell the order of SQL SELECT statement?
The order of SQL SELECT statement is as follows:
1SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY.
Q5. What is Database White Box Testing?
The Database Whitebox Testing deals with the tables, data model, schema and referential integrity
rules. It also deals with the triggers, logical views with database consistency and ACID properties.
Upskill for Higher Salary with SQL Certification training course

Course Name Upcoming Batches Fees


15th June,2024 (Weekend
SQL Certification Training ₹19,995
Batch)
Q6. What is Database Black Box Testing?
Database Black Box Testing deals with data mapping, data storing and retrieving. The Database Black
Box Testing is used for techniques such as Equivalence Partitioning and Boundary Value Analysis.
Q7. What is CTE?
An expression which consists of a temporary set of results defined in a SQL statement is said to be a
Common Table Expression(CTE).
Q8. What are the different tables present in Mysql?
There are mainly five types of tables present in MySQL. Out of all these database engines, the default
database engine used in MySQL is MyISAM. Refer below to know the five types of tables:
 MyISAM
 Heap
 Merge
 INNO DB
 ISAM
Q9. What is a Cursor?
Considered as a pointer to point to one row in a set of rows, a Cursor is nothing but a control which
enables traversal over the records in the table. So, the cursor is used for performing traversing actions
such as addition, retrieval, and removal of records in a database.
Q10. How can you test for NULL values in a database?
A NULL value is a field with no value present in that particular field. Since the NULL value cannot be
compared to any other NULL values, you cannot use the comparison operators such as =, <, or <>. To
compare the fields with NULL values, you have to use the IS NULL and IS NOT NULL operator.
Refer below for Syntax of IS NULL and IS NOT NULL.
1SELECT column_names FROM table_name WHERE column_name IS NULL;
2SELECT column_names FROM table_name WHERE column_name IS NOT NULL;
Q11. Can you elaborate on BLOB and TEXT in MySQL?
BLOB
BLOB(Binary Large Object) is used to hold a variable amount of data and holds up to 65,535 bytes of
data. The following are the four types of BLOB.
 TINYBLOB
 BLOB
 MEDIUMBLOB
 LONGBLOB
TEXT
TEXT is used to store string values and holds up to a maximum length of 65,535 characters. The
following are the four types of TEXT
 TINYTEXT
 TEXT
 MEDIUMTEXT
 LONGTEXT
Q12. Can you tell how can you display the Maximum salary in SQL?
To display the maximum salary in SQL, you can use the inbuilt function called MAX().
Q13. What is the difference between the NVL function, IFNULL function, and the ISNULL function?
The NVL function, IFNULL function, and the ISNULL function all of them are used to replace the NULL
value with another value. The ORACLE users use the NVL function, MySQL users use the IFNULL
function and the SQL servers use the ISNULL function
For example, let us say we have a column(column_3) which has NULL values.
So, if you run the below statement, the output you would get is a NULL value.
1SELECT column_1 * (column_2 + column_3) FROM Example_Table
Now, to overcome this, you can use the above three functions as follows:
1SELECT column_1 * (column_2 + NVL(column_3,0)) FROM Example_Table
2SELECT column_1 * (column_2 + IFNULL(column_3,0)) FROM Example_Table
3SELECT column_1 * (column_2 + ISNULL(column_3,0)) FROM Example_Table
Q14. What is the difference between GUI Testing and Database Testing?
GUI Testing Database Testing
Also known as User Interface Testing of Front-
Also known as Back-End Testing or Data Testing.
end Testing.
Deals with items that interact with users. Deals with items that are hidden from users.
Testers need not know SQL. Testers need to know SQL.
GUI Testing focuses on the outlook of the Database Testing focuses on the integrity of data in
application the front end with the data present in the back end
Q15. How To Display Nth Highest Salary From A Table In A Mysql Query?
Consider the table named “Employee”.
Now, to find the Nth salary consider the below statement.
1SELECT DISTINCT(salary) FROM employee ORDER BY salary DESC LIMIT n-1,1
So, if you want to find out the 7th largest salary, consider the below query.
1SELECT DISTINCT(salary) FROM employee ORDER BY salary DESC LIMIT 6,1
Now, let’s move on to the next set of questions, which is the PHP MySQL Interview Questions.
PHP MySQL Interview Questions
Q1. What is the command used to create a database using PHP and MySQL?
The command used to create a database using both PHP and MySQL is mysql_create_db(“Database
Name”).
Q2. Can you tell the difference between Mysql_fetch_object And Mysql_fetch_array?
Both of them are similar but vary with a single difference. Mysql_fetch_object return as object and
Mysql_fetch_array returns an array. This means that you cannot access the data by their offsets but
can only access through its fields names.
Q3: What are the ways in which you can retrieve data in the result set of MySQL using PHP?
The different ways in which you can retrieve data in the result set of MySQL using PHP are as follows:
 mysql_fetch_object: This constant fetches a result row as an object.
 mysql_fetch_array: This constant fetches a result row as an associative array, numeric array or as
both.
 mysql_fetch_row: This constant gives us a result row as an enumerated array.
 mysql_fetch_assoc: This constant gives us a result row as an associative array.
Q4. Can you tell how many values can Set the function of MySQL to consider?
MySQL’s Set function can take a maximum of 64 values, but can also consider 0 values.
Q5. Can you tell the reasons for selecting Lamp(Linux, Apache, MySQL, PHP) instead of any other
combination of software programs, servers, and operating system?
The reason behind selecting Lamp stack is very simple. Linux, Apache, MySQL, PHP are open source
software. The security of the Linux operating system is much more than Windows. The Apache server
is a better server than others in the perspective of functionalities and security. MySQL is one of the
most popular open source databases is used with PHP to perform various functionalities.
Q6. Can you tell a way to know the number of days between the two given dates in PHP?
You can simply declare the two dates, and then use the strtotime function to subtract both the dates
and find the differences between the days in seconds.
Consider the below example.
date1 =’2018-09-15′;
date2 = ‘2018-10-15’;
days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);
Q7. Can you tell how to find the number of rows in a resultset using PHP?
You can use the mysql_num_rows function to find the number of rows in a resultset.
Consider the below example.
1output = mysql_query(sql, database_name);
2number_of_rows = mysql_num_rows(output);
3echo "The number of forws found are equal to: $number_of_rows";
Q8. What are the functions used to encrypt and decrypt the data present in MySQL?
The function used to encrypt the data is AES_ENCRYPT() and the function used to decrypt the data is
AES_DECRYPT().
Q9. If you wish to encrypt the username and password using PHP, how will you do that?
You can encrypt the username and password using the following functions respectively:
1SET USERNAME=USERNAME("Username");
2SET PASSWORD=PASSWORD(”Password”);
Q10. How can you increase the performance of MySQL SELECT query?
The SELECT statement is used to select data from a database and the data returned is stored in a
result table, called the result-set. The SELECT statement can be either individually used or can be used
with other statements such as ORDER BY, GROUP BY, and HAVING clause.
To increase the performance of a MySQL SELECT query, you can use the LIMIT clause to limit MySQL
from further search in a table, after collecting the required number of records. Apart from this, we can
also use the LEFT JOIN or the RIGHT JOIN to retrieve data from two or more tables.
Q11. Can you tell the difference between $message and $$message?
$message and $$message are both PHP variables. $message is used to store the variable data and $
$message is used to store the variable of a variable. So basically, data is stored in $message and $
$message is used to store the data that can be changed dynamically.
Q12. Write a program using the SELECT statement, While Loop.
You can write a program to select the students details from the student table and use the loop to just
print the name of students.
1example_query = mysql_query("SELECT * FROM 'students' WHERE 'student_id' = '1';");
2while(output = mysql_fetch_array(example_query))
3{
4echo output['Students_Name'];
5}
Q13. How can you take the backup and restore a MySQL database using PHP?
MySQL comes with a utility mysqldump to provide the database backup and restore. The command
you can use for backup and restore are as follows respectively.
1//To take the backup of database
2mysqldump database > backup -file.sql;
3//To restore the database
4mysqldump database < backup -file.sql;
You can also use the phpMyAdmin user interface to backup your database. If you wish to backup, the
database you just have to click on the “export” link on the phpMyAdmin main page.
Q14. Can you tell the difference between ereg_replace() and eregi_replace()?
ereg_replace and eregi_repalce() are regular expressions used to replace the matching characters. The
only difference between these functions are eregi_replace() function ignores the case distinction
when it matches alphabetic characters.
Q15. How to copy data from one server to another using PHP?
You can use the following three options:
Option 1: You can use the PHP Copy to move files from server to server. Refer to the syntax below:
1/* Copy the file from source url to server */
2$copy = copy( $remote_file_url, $local_file );
Option 2: You can use the PHP FTP to move files from server to server. Refer to the syntax below.
1/* Download $remote_file and save to $local_file */
2ftp_get($connect_it,$local_file,$remote_file,FTP_BINARY)
Option 3: You can use the ZIP and UNZIP Files option in PHP.
Now, let’s move on to the next set of questions, which is the Complex MySQL Interview Questions.
Complex MySQL Interview Questions
Q1. Can you tell few best practices to be followed for optimization in SQL?
The best practices to be followed for SQL optimizations depend on the individual to individual, but the
following list consists of the most popular practices that are advised to follow. Refer below.
 Try avoiding prefixing your stored procedure names with “sp_”.
 It is recommended to use the column list in INSERT statements.
 Preferably use the ANSI-Standard JOIN Clauses rather than the Old style clauses.
 While using SELECT statement, avoid using * queries.
 Do not use double quotes in T-SQL code.
 Try avoiding to use column numbers in the ORDER BY clause.
 Try using table aliases if your SQL statement involves more than a single source.
Q2. Can you tell what are various ways to create an index?
The various options to create an index are as follows:
 You can create an index using the T-SQL statements.
 You can use the SQL Server Management Studio. In this, you can browse to the table you need to
create an index and then right click on the Indexes node. Over here you have to choose the New Index
option.
 You can indirectly identify the index by defining the PRIMARY KEY and the UNIQUE constraint within
the CREATE TABLE or ALTER TABLE statement.
Q3. What is the difference between a Heap table and Temporary table?
Heap Table Temporary Table
Heap Table exists in the memory A temporary table is valid only during the session.
Heap Tables are shared among a various
Temporary tables are not shared among the clients.
number of clients.
Temporary tables need a special privilege to Heap Tables are storage engines which do not need
create tables. special privileges.
Q4. Why do you think it is advised to not to use GUID and CHARACTER columns as Clustered Index
arrays?
GUID columns affect the clustered index sorting performance as the nature of the random GUID value
generated is larger than the integer data types.
CHARACTER columns affect the sorting performance of the character data types, larger-size values,
non-increasing values, and non-static values which often tend to change. These values cannot be
compared as binary values, as the characters comparison mechanism depends on the used collection.
Q5. How can you handle the –secure-file-priv in MySQL?
–secure-file-priv option limits the MySQL Server from loading the directories using the LOAD DATA
INFILE.
If you wish to see the directory that has been configured then you may use the SHOW VARIABLES LIKE
“secure_file_priv”;
You have mainly two options to tackle:
 Either move your file to the directory specified by the secure-file-priv.
 Or you can disable secure-file-priv. You cannot disable this later on, and you have to remove it from
the start itself.
Q6. What is the difference between B-Tree and Hash Indexes?
B-Tree Hash Indexes
A B-Tree index can be used for column
A Hash-Index can be only used for equality
comparisons like =, >, <, >=, <= or BETWEEN
comparisons that use =, >=, <=.
operators.
B-Tree can be used to search the next entry in Hash Index cannot be used to search for the next
the order. entry in the order.
Any leftmost prefix of the key can be used to
Only whole keys are used to find a row.
find the rows.
Q7. Where is the MyISAM table stored?
Each and every MyISAM Table is stored on disk in the following three files:
 .frm file – Stores the table definition.
 .MYD file – A data file has an MYData extension.
 .MYI index file – The index file has an MYIndex extension.
Q8.State the differences between MongoDB and MySQL.
MongoDB MYSQL
An open source database that stores JSON like An open source relational database management
documents which vary in structure. system which stores relational data.
Each and every individual record are stored as Each and every individual record are stored as rows
documents. in a table.
Documents from a particular class or a group
A similar type of records are stored in a table.
are stored in a collection.
Q9. Identify what is wrong in the below query.
SELECT EmployeeID, AVG(Salary)
FROM EmployeeDetails
WHERE AVG(Salary) > 75
GROUP BY EmployeeID
The answer is quite simple. You cannot use the WHERE clause to restrict the groups. Instead of this,
you have to use the HAVING clause.
Your query should be as follows:
1SELECT EmployeeID, AVG(Salary)
2FROM EmployeeDetails
3HAVING AVG(Salary) > 75
4GROUP BY EmployeeID
Q10. What is Normalization and list the different types of normalization?
Normalization is the process of organizing data to avoid duplication and redundancy. There are many
successive levels of normalization. These are called normal forms. Each consecutive normal form
depends on the previous one. The first three normal forms are usually adequate.
 First Normal Form (1NF) – No repeating groups within rows
 Second Normal Form (2NF) – Every non-key (supporting) column value is dependent on the whole
primary key.
 Third Normal Form (3NF) – Dependent solely on the primary key and no other non-key (supporting)
column value.
Now, let us move on to the next set of questions which is the Tricky MySQL Interview Questions.
Tricky MySQL Interview Questions
Q1. Consider you have a composite index of three columns. Now, you have to provide the value of
two columns in the WHERE clause of a SELECT query. Do you think Index can be used for the
operation?
Usage of index completely depends on if you consider the primary index or not. Consider you have a
student table. Now, suppose if an Index is present on StudentID, StudentFirstName, and
StudentLastName then you can consider a query as follows:
1SELECT * FROM StudentDetails WHERE StudentID=3 and StudentFirstName='Jatin'
Now, if you consider that the above two columns in the query are the secondary index columns, then
the index will not be invoked. Else, if the above two columns contain the first column while creating an
index(i.e. the primary index), then the index will definitely be invoked.
In the above scenario, I have considered that StudentID and the StudentFirstName as primary
columns, so an Index will be used in this case.
Q2. Suppose you have to collect the first name, middle name and the last name of students from
the below table. But, you observe that there few missing values either in the first name, middle
name and the last name columns. How will you return the first non-null values?
StudentID FirstName MiddleName LastName
1 Rohit Kumar NULL
2 Sakshi Chowdhary NULL
3 NULL Yash Singhania
4 Akash NULL Kumar
5 Avinash NULL Daksh
You can use the COALESCE function to return the first non-null value from the table. Consider the
below query.
1SELECT StudentID, COALESCE(FirstName, MiddleName, LastName) as Name FROM StudentDetails;
Q3. Consider a scenario where you have two to three tables with thousand tuples in each of them.
Now, if you have to perform a JOIN operation between them will you choose to perform filtering of
rows or transforming of rows first.
The answer to this question is quite logical. If you have three tables with thousands of tuples in each
of them, then you are first supposed to filter the rows in those tables and then transform the table.
This would be beneficiary as if you transform the table, then the number of columns may increase
reducing the performance. Due to such performance issues, a lot of memory will be used and the
output will appear on your screen after quite a long wait of time.
Q4. How can you validate emails using a single query?
To validate emails you can use the regular expressions function (REGEXP_LIKE). Consider the below
query.
1SELECT
2Email
3FROM
4Employee
5where NOT REGEXP_LIKE(Email, ‘[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}’, ‘i’);
Q5. Consider a scenario where you have to send an email to a client from the SQL database. How do
you think you can achieve this task?
To send an email from the database, you can use the stored procedures. Follow the below procedure
to send the emails:
 Configure your SQL Server Mail account.
 Enable the database mail.
 Write a script to send an email. Refer below for the script.
1USE [YourDB]
2EXEC msdb.dbo.sp_send_dbmail
3@recipients = '[email protected]; [email protected];[email protected]
4@body = ' Sample Body Text',
5@subject = 'Example Email' ;
6GO
Q6. Consider you have the following three tables which have to be linked together.
Department(Ssn, EmployeeName, EmployeeAge..)
EmployeeContactDetails(Ssn, DepartmentID,desc,Ord)
EmployeeAddress(Ssn,DepartmentID, desc, Ord)
The problem statement is to select all the departments from the Department table, with the “desc”
field from the EmployeeContactDetails and EmployeeAddress where Ord=1. Now, you have to solve
this problem statement with a single query.
To solve this problem statement you can use the JOINS concept. You simply have to perform a JOIN on
the Department.Ssn and the DepartmentID in the other tables.
Now, if you are sure that the Ssn exists in all the three considered tables, then you can use the INNER
JOIN. Also, if you are not sure that you have matching rows, then you can use the LEFT JOIN. Consider
the below query.
1 SELECT d.Ssn,
2 d.EmployeeName,
3 c.desc ContactDetailsDesc,
4 a.desc AddressDetailsDesc
5 from Department d
6 inner join EmployeeContactDetails c
7 on d.id = c.DepartmentID
8 inner join address a
9 on d.id = a.DepartmentID
10where d.EmployeeName = 'abc'
11and c.ord = 1
12and a.ord = 1
Q7. If you are assigned a task, to find the information of PROCEDURES. What are the basic
commands that you will use to do so?
To check the procedures, you can consider the following query.
1SELECT * FROM SampleSource
2WHERE Type=’PROCEDURE’
3AND NAME IN (‘SP_CONNECTED_AGG’,’SP_UNCONNECTED_AGG’);
To find the procedures columns information, you can consider the following query.
SELECT OWNER, OBJECT_NAME, ARGUMENT_NAME, DATA_TYPE, IN_OUT from ALL_ARGUMENTS
1
order by OWNER, OBJECT_NAME, SEQUENCE;
Q8. Can you tell which of the following WHERE clauses is faster?
WHERE col * 4 < 16
WHERE col < 16 / 4
If we compare both the statements, then the second WHERE clause would be comparatively faster
than the first one. That is because, for the first statement, MYSQL would retrieve the value of ‘col’ for
each and every row, multiplied by four. After that, it would compare the result to 16. Also, in the first
case no Index can be used, and hence it makes it further slow.
Q9. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?
BETWEEN operator is used to display rows based on a range of values in a row whereas the IN
condition operator is used to check for values contained in a specific set of values.
Example of BETWEEN:
SELECT * FROM Students where ROLL_NO BETWEEN 10 AND
1
50;
Example of IN:
1SELECT * FROM students where ROLL_NO IN (8,15,25);
Q10. What are the different types of Collation Sensitivity?
Following are the different types of collation sensitivity:
 Case Sensitivity
 Kana Sensitivity
 Width Sensitivity
 Accent Sensitivity
So this brings us to the end of the MySQL Interview Questions blog. I hope this set of MySQL Interview
Questions will help you ace your job interview. All the best for your interview!
Apart from this MySQL Interview Questions Blog, if you want to get trained from professionals on this
technology, you can opt for a structured training from edureka! Click below to know more.
Check out this MySQL DBA Certification Training or SQL Training by Edureka, a trusted online learning
company with a network of more than 250,000 satisfied learners spread across the globe. This course
trains you on the core concepts & advanced tools and techniques to manage data and administer the
MySQL Database. It includes hands-on learning on concepts like MySQL Workbench, MySQL Server,
Data Modeling, MySQL Connector, Database Design, MySQL Command line, MySQL Functions etc. End
of the training you will be able to create and administer your own MySQL Database and manage data.
Got a question for us? Please mention it in the comments section of this “MySQL Interview Questions”
and we will get back to you as soon as possible.
Introduction
It's no secret that the present job market is extremely cutthroat, and overcoming the first obstacle of
job application could be a challenge in itself. Once you cross this first hurdle, the hard way toward
finding a new job career has now barely begun. The RDBMS field is among the highly competitive
fields, specifically because so many job hunters are vying for such limited job openings. You must be at
your best to emerge from the crest of the competitors. The easiest way to achieve this is to be well-
versed using RDBMS interview questions.
In this blog post, we’ll review the 117 RDBMS viva questions you will likely be asked during an
interview and how to answer them. Also, consider joining a credible data management courses to
sharpen your skill sets.
Let’s get started with the RDBMS questions and answers. This series of RDBMS basic interview
questions and RDBMS technical interview questions will cover in-depth information about relational
DBMS.
RDBMS Viva Questions and Answers For Beginners
RDBMS stand for a relational database management system that stores the data in tables, and you can
easily access it even through another database. It is the basis for sql, oracle, Microsoft Access, and IBM
DB2. excellent RDBMS knowledge is required for RDBMS-related job roles.
Below is a quick list of RDBMS interview questions and answers:
Q1). Give a quick idea of the term RDBMS.
RDBMS refers to storing or managing data across numerous database tables. The most advantageous
part of relational database management is that you can state relationships between various data
entries with the help of tables. These relationships can usually be expressed using values and not
pointers.
Q2). How will you define a relational database model?
It defines the relationship among different databases and how they are connected. When multiple
databases are connected, it creates flexibility and can be used within a software app as needed.
Q3). Tell me about RDBMS components.
Each relation in an RDBMS is given a “Name” that will be unique. In each relation, rows and columns
represent attributes, and rows are Tuples. Other RDBMS components include RDBMS table, tuple,
column, domain, schema and RDBMS constraints.
Name => Attriutes => Tuples
Q4). Give a quick idea of the term Normalization.
It is a data organization process where data is organized in such a way that it can minimize
redundancy. It divides the database into multiple tables and defines logical relationships among them.
Q5). Name different Normalization types that can be used with RDBMS.
Each has its objectives and purpose. So, you must understand them individually before implementing
them with the database. The following are the different normalization types:
 1NF (First Normal Form)
 2NF (Second Normal Form)
 3NF (Third Normal Form)
 BCNF (Boyce-Codd Normal Form)
 4NF (Fourth Normal Form)
1NF , 2NF, 3NF, 4NF, 5NF, BCNF, ONF, DKNF
Q6). Have you ever used a Stored procedure (SP) in RDBMS?
Yes, I know about the SPs and worked on them during my training. An SP is a group of SQL statements
that can be used together to act. It accepts input parameters to be used with different scenarios. SPs
are considered an added advantage to ensure a database's integrity.
Q7). Give me a quick idea of the E-R Model.
E-R model stands for entity-relationship model, which explains closely related things in a particular
knowledge domain. A fundamental ER model comprises of different entity types and mentions the
relationships which could exist among the entities.
It consists of entities and relational objects. Entities can be understood by the collection of attributes
in the database.
Q8). Tell me something about various data abstraction levels.
In RDBMS, data can be abstracted at three different levels. They are given below -.
Physical Level -> Logical Level -> View 1, View 2 & View 3
The physical level is available at the bottom, giving you a detailed idea of the data storage. The Logical
level at the next stage finds the logic among data tables and how to group similar data for easy access.
At the top, there is a view level that gives information about the complete database and various views
of a database.
Q9). Define the term trigger about the RDBMS.
It is a stored procedure that acts as soon as some event occurs. The programmers do not call events
but are invoked automatically as soon as edits are made systematically.
Check out how to create stored procedure & trigger in SQL server. Further, obtaining SQL Training
from JanBask Training will provide you access to various work prospects in database management and
administration.
Q10). What is a VIEW, and how will you define it?
A “view” is a subset of a database used to retrieve, delete, or combine the data. As soon as you edit a
view, the original data also changes in the table. Find out the difference between tables vs. views in
SQL by clicking here.
Q11). Do you have any idea of INDEX storage in RDBMS?
For creating pointers to the data, SQL server indexes are used. They help in finding rows in a table
quickly. Indexes can be defined for multiple columns together with a different name. Users cannot see
or access them but helps improve the database performance. For small tables, impacts can be
negligible. In the case of complex data tables, the impact of indices is clearly visible.
Q12). There are two types of indexes in RDBMS. Can you tell me their names and their significance?
Yes, there are two methods for index storage in RDBMS. These are given below.
 Clustered Indexes
 Non-clustered Indexes
Clustered indexes can give information about the physical storage of the data and non-clustered
indexes will give you an idea of logical ordering. Read an all-inclusive guide on the difference between
clustered vs non-clustered indexes.
Q13). How is RDBMS a preferable option over DBMS?
It minimizes redundancy, and integrity can be maintained. It maintains data consistency and allows
data sharing with other databases. It follows a set of rules to satisfy storage standards and maintains
security.
Q14). Tell me about the buffer manager.
A buffer manager in database management system is responsible for allocating buffer space in the
main memory in order to store temporary data. It transfers the data from third-party storage devices
to the memory and puts some data into the cache for easy access.
The buffer manager transfers the block address when a user requests specific data and the data block
is available in the table buffer in the primary memory.
Q15). Tell me about Keys and how they are valuable.
A key is a constraint added to a database to restrict data access requirements. These are important for
any database to maintain maximum data integrity.
If you are heading for the next MySql interview, check out our MySql interview questions and
Answers.
Q16). How many keys can be applied to a database?
Different types of keys can be applied to databases as needed. Here we have listed the names of
popular ones that are used frequently.
 Primary Key
 Candidate Key
 Super Key
 Foreign Key

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.

Q39). In what conditions a relation schema is in 3NF?


A relational model R is in 3NF if it is in 2NF, and one of the following is true for every FD X A.
 R's Super-key is X.
 R's most significant feature is A.
 If the primary key is transitively dependent on all non-prime attributes.
For more clarity, learn about database normalization 1NF, 2NF, 3NF, 4NF forms.
Q40). Explain Domain Key Natural Form.
The relation is considered to be in DKNF if all constraints and dependencies that should hold on the
constraint can be enforced by merely imposing the domain constraint and key constraint on the
relation.
Q41). Explain what partial, alternative, artificial, natural, and compound keys are.
A partial key is a set of qualities that may be used to distinguish weak entities belonging to the same
owner.
An Alternate Key is a Candidate Key other than the Primary Key. There are different types of SQL keys
and their examples and uses. You must know how to use them in database applications.
 Artificial Key: If there is no evident key, either standalone or compound, the final recourse is to invent
one by giving a unique number to each record or occurrence. This is called as creating an artificial key.
 Compound Key: When no single data element can uniquely identify occurrences inside a build, a
compound key is formed by combining many components to create a unique identifier for the
construct.
 Natural Key: When one of the data items included within a construct is utilized as the main key, the
natural key is used.
Q42). Define Query Optimization.
Query optimization is the process of determining an efficient execution plan for assessing a query with
the lowest estimated cost. The aim of query optimization is to identify a plan of execution that
minimizes the time needed to process a query.
Q43). Define Checkpoint in DBMS.
A checkpoint is a snapshot of the database management system's current state. By employing
checkpoints, DBMS can reduce the amount of work required upon restart in the event of many
crashes.
Q44). What do you understand about transparent database management systems?
It means a database management system should provide a transparent distribution to the user. In
other words, a transparent DBMS keeps the data hidden from the user. There are 4 kinds of database
transparencies: distribution, translation, performance and DBMS transparency.
Q45). Explain the Network and Hierarchical Schemas in Database Management Systems.
The Hierarchical Schema utilizes a tree-like structure to arrange data. Here are the components of a
hierarchical model:
 It consists of nodes connected by branches.
 The root node is the highest node in the tree.
 When many nodes emerge at the top level, these are called root segments.
 There is only one parent for each node.
 A parent may have several children.
Network Schema -
Network Schema is the hierarchical data model in its advanced form. It organizes data using directed
graphs rather than a tree structure. A child can have more than one parent in this situation. It makes
use of the two data structures known as Records and Sets.
The above figures can differentiate between hierarchical and network schema in DBMS.
Q46). Describe correlated subquery in DBMS.
For each row of an outer query, these are SQL subqueries that run. Each subquery is done just once
for each row in the outer query.
A correlated subquery in a database management system is a subquery that applies to a database
column that is not in the “FROM” clause. This database column could be in the Projection clause or
inside the WHERE clause. Mostly, correlated sub-queries decline performance.
Q47). Differentiate between hash join and merge join
When the projections of the connected tables are ordered on the join columns, a merge join is used.
Hash joins are slower and consume more memory than merge joins. A hash join is used when the
projections of the connected tables are not already sorted on the join columns.
Q48). How can you define a Deadlock condition?
Deadlock happens when two transactions wait for a locked resource or while another transaction is
held. Deadlocks can be avoided by enabling all transactions to acquire all locks at the same time.
Q49). Distinguish between A super key and a candidate key
A super key is a single key or a set of keys that helps identify a table record. Super keys can have one
or more properties, even if all of them aren't required for the records to be identified. A candidate key
is a subset of a Super Key that can identify records in a database using one or more attributes.
RDBMS Viva Interview Questions And Answers For Intermediate
When preparing for RDBMS job interviews, one of the most prominent ways to maximize your chances
of cracking the interview is anticipating RDBMS questions and answers.
Let’s examine the most frequently asked RDBMS intermediate-level interview questions and answers.
Q50). What are the various JOIN operations in SQL?
There are different types of SQL joins. The logical operation JOIN is used to get data from many tables.
Only when there is a logical link between two tables can it be used? Moreover, the JOIN operator uses
data from one table to extract data from another.

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

Q116). Describe The Three Levels Of Data Abstraction.


There are 3 levels of data abstraction:
 Physical level: The lowest level of data abstraction explains how data gets stored.
 Logical level: The next higher level of data abstraction explains what data is stored in the table and
what is the relationship between that data.
 View level: The highest level of data abstraction explains just part of the complete database.
Q117). What Is E-r Model?
This is one of the most commonly asked RDBMS important questions.
The e-r model is dependent on the real world that contains fundamental objects referred to a entities
and of the relationship between them. Entities are explained in a table by using a group of attributes.
Check Out Other Data Management Courses Offered by JanBask Training:
Course Title Details
Microsoft BI View Details
Data Analytics View Details
Oracle Database Admin View Details
Big Data Hadoop Master View Details
Conclusion
These Oracle RDBMS interview questions are designed as per the protocol of Oracle Inc.
The blog gives you a sound idea of RDBMS interview questions and answers that you may encounter
in your next interview. The discussion during interview questions on RDBMS always starts with basics
like RDBMS, Normalization, Triggers, Views, etc. After this, the interviewer will check your practical
knowledge through different examples. So, the blog is enough to practice theoretical RDBMS
concepts. To learn the practical aspects of RDBMS and how it is used by Companies, join our online
SQL server training program to master the concepts of databases from scratch! At JanBask Training,
and start exploring the world-class RDBMS systems now.
FAQs
Q1. What Is the Difference Between Dbms and Rdbms?
Ans:- DBMS stands for Database Management System, and RDBMS stands for Relational Database
Management System. RDBMS stores data in tables, whereas DBMS stores data as a file. Make sure to
get it right in your interview questions on dbms.
Q2. What is SQL in RDBMS?
Ans:- SQL is a standard database language, i.e., Structured Query Language in RDBMS which is used to
create, update, and retrieve data. These questions are a must when it comes to dbms viva questions.
One must be prepared for dbms viva questions and answers.
Q3. What Are the Types of Dbms?
Ans: The following are the types of DBMS:
 Hierarchical Database
 Network DBMS
 Relational DBMS
 Object-Oriented Relational DBMS
These are some of the common rdbms interview questions. One can opt for a data scientist course
online if they see a potential career in this field.
Q4. What Are the Main Components of Rdbms?
Ans:- An RDBMS comprises several components like - tables, records, attributes, instances, schemas,
keys, etc., which create a relational database. This is quite a common dbms viva question. Learn all
about rdbms full form in computer and the purpose of database systems via data scientist training.
Q5. What Does Rdbms Offer the Functions?
Ans:- RDBMS offers 4 major functions as follows −
 Security
 Accuracy
 Integrity
 Consistency
Q6. What Are Rdbms Examples?
Ans:- A few examples of RDBMS are- Oracle, Microsoft SQLServer, MySQL, and PostgreSQL.
Q7. What Is the Objective of the Online SQL Server Training?
Ans:- The major objective of our online SQL server training is to offer an SQL online course that
provides the experience same as offline classrooms and saves students time traveling to the physical
classes, including their finances, energy & time. Learn in depth about sql training by joining a data
science certification online.
Q8. What Skills Will I Learn Through This Online SQL Server Training?
Ans:- Following are the important skills you’ll learn through our comprehensive data management
courses.
 SQL Server, DDL, DML
 SQL Server Programming, Indexes, Functions
 SSIS Package Development and Deployment Procedures
 SSRS Report Design
 Formatting SSRS Report & Models
 Building SSAS Cubes, Power BI
Q9. What All Topics Will Be Covered in the Beginner’s Level Online SQL Server Training?
Ans:- Our online SQL server training covers topics from the basics of the SQL discipline to the
advanced level. The instructors will teach the following theoretical SQL concepts at the beginner level.
SQL Server, DDL, DML
 What is Structured Query Language, Version,
 SQL architecture, client/server relation, and database types
 Installations process
 Transaction logs-pdf, MDF, and pdf files
 Different types of data types
 What is a database, or table, and what Key factors to create databases/tables?
 DDL, DML, DCL, and TCL statements
 Insert record/data in tables
 Modify/Update the existing data.
 SQL Server Operators, Normalisation, and much more.
Q10. Can I Get a Free Demo Class?
Ans:- To present you with a quick roadmap of our online SQL server training program, we do provide a
free demo class. The goal of this class is to make you familiar with everything that we’ll cover in our
course. You can even opt for a data scientist course online.

You might also like