Google News
logo
MySQL Interview Questions
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.
* 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
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
MySQL is not case sensitive. Its case-sensitivity relies on the underlying operating system as OS determines the case sensitivity of tables names and database. In windows, database and table names are not case sensitive but in the case of UNIX, it is case sensitive in nature. Especially on the UNIX host, database accepts the upper case and lower-case table names.
To write an optimized query in MySQL, below are some guidelines :
 
* Functions should not be used in predicates.
* At the beginning of predicates, do not use the wildcard symbols such as %.
* Use only needed columns in the SELECT clause.
* Always use the inner join option.
* Use of the “Order by” clause is necessary for SQL, in case of assuming the sorted results.
* Mysql_connect
* Used to open a new connection to a database.
* You can open and close the database connection based on the request.
* Opens a page everytime the page is loaded.
 
* 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.
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
 
 
 
* 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.
 
* 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
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.
* 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.
We can check the MySQL version on Linux using the below command :
 
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 :
 
SHOW VARIABLES LIKE "%version%";
These are most commonly used storage engine in MySQL are MyISAM and InnoDB.
 
Difference between MyISAM and InnoDB are given below :
* MyISAM does no longer support transactions, however InnoDB supports transactions.
* MyISAM helps Table-level Locking, however InnoDB supports Row-level Locking.
* MyISAM helps full-text search, however InnoDB does not.
* MyISAM designed for the need for speed but InnoDB designed for most performance.
* MyISAM does now not aid overseas keys, but InnoDB helps foreign keys.
* We can use commit and rollback with InnoDB however not in MyISAM.
* MyISAM does no longer assist ACID (Atomicity, Consistency, Isolation, and Durability) however InnoDB supports the ACID property.
* In the InnoDB table, the AUTO_INCREMENT field is a section of the index but now not in MyISAM.
* MyISAM stores its tables, data, and indexes in disk area the usage of a separate table name.FRM, desk name.MYD and table name. MYI however InnoDB stores its tables and indexes in a tablespace.
TRUNCATE
* It removes all rows from a table.
* It does not require a WHERE clause.
* Truncate cannot be used with indexed views.
* It is performance wise faster.

DELETE
* It removes Some or All rows from a table.
* A WHERE clause is used to remove particular rows according to the matched condition. All rows will be deleted when we did not use Where condition in Query.
* It removes rows one by at a time.
* It can be used with indexed views.

DROP
* It removes a table from the database.
* All table's rows, indexes, and privileges will also be removed when we used this command.
* The operation cannot be rolled back.
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 :
 
ALTER TABLE table_name     
    ADD COLUMN column_name column_definition [FIRST|AFTER existing_column];

 

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 :
 
DROP TABLE  table_name;

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 :
 
[CONSTRAINT constraint_name]    
    FOREIGN KEY [foreign_key_name] (col_name, ...)    
    REFERENCES parent_tbl_name (col_name,...)

 

We can change the MySQL root password using the below statement in the new notepad file and save it with an appropriate name:
 
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.
 
C:\Users\javatpoint> CD C:\Program Files\MySQL\MySQL Server 8.0\bin
 
Next, enter this statement to change the password:
 
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.
* Don't use "sp_" while creating a stored procedure.
* Don't use "*" while you are using the SELECT command. Also avoid unnecessary columns in SELECT clause.
* You can use table aliases while writing queries.
* Avoid the usage of the wildcard (%) at the starting of a predicate.
* DISTINCT and UNION need to be used solely if it is necessary.
The order of SQL SELECT statement is as follows:
 
SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY.

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.
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.
22 .
An expression which consists of a temporary set of results defined in a SQL statement is said to be a Common Table Expression(CTE).
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
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.
SELECT column_names FROM table_name WHERE column_name IS NULL;
SELECT column_names FROM table_name WHERE column_name IS NOT NULL;

 

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.
 
SELECT column_1 * (column_2 + column_3) FROM Example_Table

Now, to overcome this, you can use the above three functions as follows :
 
SELECT column_1 * (column_2 + NVL(column_3,0)) FROM Example_Table
SELECT column_1 * (column_2 + IFNULL(column_3,0)) FROM Example_Table
SELECT column_1 * (column_2 + ISNULL(column_3,0)) FROM Example_Table
CHAR_LENGTH  is character count whereas the LENGTH is byte count. The numbers are same for Latin characters but they are different for Unicode and other encodings.
Storage engines are called table types and data is stored in files using various techniques.
 
Technique involves :

* Indexing
* Storage mechanism
* Locking levels
* Capabilities and functions.
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.mxj
LIKE and REGEXP operators are used to express with ^ and %.
SELECT * FROM employee WHERE emp_name REGEXP "^b";
SELECT * FROM employee WHERE emp_name LIKE "%b";
Following are the differences between mysql_fetch_array and mysql_fetch_object:
 
mysql_fetch_array() : Returns a result row as an associated array or a regular array from database.
mysql_fetch_object :  Returns a result row as object from database.
SIX triggers are allowed in MySQL table. They are as follows :
 
* BEFORE INSERT
* AFTER INSERT
* BEFORE UPDATE
* AFTER UPDATE
* BEFORE DELETE and
* AFTER DELETE
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;
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;
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.
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
A foreign key is used to connect two tables. A FOREIGN KEY is a field (or assortment of it) in one table that alludes to the PRIMARY KEY in another table. The FOREIGN KEY requirement is utilised to forestall activities that would crush joins between tables.
 
To assign a foreign key, it is important to mention it while creating the table. It can be assigned by invoking the FOREIGN KEY query. Something like this :
 
FOREIGN KEY (Any_ID) REFERENCES Table_to_reference(Any_ID)
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)
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.
 
In MySQL, we can import a database in mainly two ways :
 
* Command Line Tool
* MySQL Workbench
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 :
 
ALTER TABLE table_name     
    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 :
ALTER TABLE Student CHANGE COLUMN S_ID Stud_ID varchar(10);  
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
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.
 
Using SQL Join Clause :
 
This approach is similar to the way we join two tables. The following query returns result from three tables :
SELECT name, scores, address, email FROM Student s   
INNER JOIN Marks m on s.stud_id = m.stud_id   
INNER JOIN Details d on d.school_id = m.school_id; 
 
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 :
SELECT name, scores, address, email   
FROM Student s, Marks m, Details d   
WHERE s.stud_id = m.stud_id AND m.school_id = d.school_id;
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 :
 
ALTER TABLE table_name  DROP PRIMARY KEY;
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 :
 
CALL stored_procedure_name (argument_list); 

Let's understand it with this example :
 
CALL Product_Pricing (@pricelow, @pricehigh);

Here, a stored procedure named Product_Pricing calculates and returns the lowest and highest product prices.
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 :
CREATE [OR REPLACE] VIEW view_name AS    
SELECT columns    
FROM tables    
[WHERE conditions];
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 :
LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/examplefile.csv'     
INTO TABLE tablename     
FIELDS TERMINATED BY ','    
OPTIONALLY ENCLOSED BY '"'    
LINES TERMINATED BY '\r\n'     
IGNORE 1 ROWS;
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 :

ALTER TABLE table_name AUTO_INCREMENT = value;
* 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.
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).
* 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.

* MySQL uses only just under 1 MB of RAM on your laptop, while Oracle 9i installation uses 128 MB.

* MySQL is great for database enabled websites while Oracle is made for enterprises.

* MySQL is portable.
* MySQL is not so efficient for large scale databases.
* It does not support COMMIT and STORED PROCEDURES functions version less than 5.0.
* Transactions are not handled very efficiently.
* The functionality of MySQL is highly dependent on other addons.
* Development is not community-driven.
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.
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.
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
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.
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.
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').
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):
Select employee_name    
From employee    
Where employee_name REGEXP '1000'    
Order by employee_name