Top MySQL Interview Questions & Answers

Top 18 MySQL interview questions: What is MySQL, primary key vs unique key, INNER vs LEFT JOIN, WHERE vs HAVING, NULL, duplicate records, second highest marks, indexes, transactions and top N queries.

How to select Top 10 records in MySQL?

MySQL does not have the TOP keyword of SQL Server. Use LIMIT with ORDER BY.

SELECT name, marks
FROM students
ORDER BY marks DESC
LIMIT 10;

This returns the 10 students with the highest marks. With only 6 rows in the table, it returns all of them, from the highest marks to the lowest. Without ORDER BY the rows that you get are not guaranteed. See MySQL LIMIT.

Write a MySQL query to select students with less than 50% marks

The examples use the students table from our MySQL tutorial: id, name, city, marks, course_id.

SELECT * FROM students WHERE marks < 50;
Tutorials Class - Output Window
id name city marks course_id
6 Neha Mumbai 45 2

If the marks are out of 100, then marks below 50 are below 50 percent. Use <= to include 50. See MySQL WHERE.

Write a MySQL query to select students with marks between 70 and 80

The examples use the students table from our MySQL tutorial: id, name, city, marks, course_id.

SELECT * FROM students WHERE marks BETWEEN 70 AND 80;
Tutorials Class - Output Window
id name city marks course_id
3 John Pune 78 1

BETWEEN includes 70 and 80 themselves. It is the same as marks >= 70 AND marks <= 80. See IN, BETWEEN and IS NULL.

What is MySQL?

MySQL is a free and open source relational database management system (RDBMS). It stores data in tables (rows and columns), and you work with the data using SQL.

SELECT name, marks FROM students WHERE marks > 80;

It is used by many websites, including WordPress, and works with PHP, Python, Java, Node.js and other languages. See MySQL Introduction.

What is the difference between SQL and MySQL?

PointSQLMySQL
What it isA language (standard) for databasesA database management system (software)
Used forWriting queriesStoring data and running queries
ExamplesSELECT, INSERTMySQL, PostgreSQL, SQL Server and Oracle are products that all use SQL

You write SQL, and MySQL runs it. Each product adds small differences to the standard language.

What is a primary key in MySQL?

A primary key is a column (or group of columns) that uniquely identifies each row. It cannot be NULL and cannot repeat. A table can have only one primary key.

CREATE TABLE students (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50) NOT NULL
);

A primary key also gets an index automatically, so searches by it are fast. See MySQL Constraints.

What is a foreign key in MySQL?

A foreign key is a column in one table that points to the primary key of another table. It links the two tables and stops wrong values.

CREATE TABLE students (
  id INT PRIMARY KEY,
  name VARCHAR(50),
  course_id INT,
  FOREIGN KEY (course_id) REFERENCES courses(id)
);

Now a student cannot get a course_id that does not exist in courses, and a course that has students cannot be deleted by mistake. The tables must use InnoDB. See MySQL JOINs.

What is the difference between DELETE, TRUNCATE and DROP?

CommandRemovesWHERE?Can be rolled back?
DELETEChosen rowsYesYes, inside a transaction
TRUNCATEAll rows, table stays. Counter restartsNoNo
DROPThe table (structure and data)NoNo
DELETE FROM students WHERE id = 6;
TRUNCATE TABLE students;
DROP TABLE students;

TRUNCATE is faster than DELETE without WHERE. See DELETE and DROP TABLE.

What is the difference between WHERE and HAVING?

The examples use the students table from our MySQL tutorial: id, name, city, marks, course_id.

PointWHEREHAVING
FiltersRowsGroups
RunsBefore GROUP BYAfter GROUP BY
Aggregate functionsNot allowedAllowed
SELECT city, COUNT(*) AS students
FROM students
WHERE marks > 50
GROUP BY city
HAVING COUNT(*) > 1;
Tutorials Class - Output Window
city students
Delhi 2

First WHERE removes Neha (45). Then the rows are grouped by city. Only Delhi has more than one student left. See GROUP BY and HAVING.

What is the difference between INNER JOIN and LEFT JOIN?

JOINReturns
INNER JOINOnly the rows that match in both tables
LEFT JOINAll rows of the left table, and the matching rows of the right table (NULL if none)
SELECT s.name, c.course_name
FROM students s
LEFT JOIN courses c ON s.course_id = c.id
WHERE s.id IN (1, 5)
ORDER BY s.id;
Tutorials Class - Output Window
name course_name
Robin Python
Vikram NULL

Vikram has no course. With INNER JOIN he would not appear at all. See MySQL JOINs.

What is the difference between CHAR and VARCHAR in MySQL?

PointCHAR(n)VARCHAR(n)
LengthFixed. Always n characters, paddedVariable, up to n characters
SpaceAlways nOnly the text length (plus 1 or 2 bytes)
Best forValues of the same length: country code, PINNames, emails, titles
country_code CHAR(2),       -- IN, US, UK
name         VARCHAR(100)    -- any name up to 100 characters

Use VARCHAR for most text. See MySQL Data Types.

What is an index in MySQL?

An index helps MySQL find rows quickly, without reading every row of the table, like the index of a book helps you find a page.

CREATE INDEX idx_city ON students (city);

EXPLAIN SELECT * FROM students WHERE city = 'Delhi';
  • Use indexes on columns used in WHERE, JOIN and ORDER BY.
  • Indexes use space and make INSERT, UPDATE and DELETE a little slower, so do not index everything.

See MySQL Indexes.

What is the difference between UNION and UNION ALL?

PointUNIONUNION ALL
DuplicatesRemovedKept
SpeedSlower (has to find duplicates)Faster
SELECT city FROM students
UNION
SELECT city FROM students;       -- 4 rows

SELECT city FROM students
UNION ALL
SELECT city FROM students;       -- 12 rows

Both queries must have the same number of columns. See MySQL UNION.

What is a transaction in MySQL? Explain ACID

A transaction is a group of statements that are saved together (COMMIT) or cancelled together (ROLLBACK). It needs the InnoDB engine.

START TRANSACTION;
UPDATE accounts SET balance = balance - 200 WHERE id = 1;
UPDATE accounts SET balance = balance + 200 WHERE id = 2;
COMMIT;
ACIDMeaning
AtomicityAll or nothing
ConsistencyData stays valid
IsolationTransactions do not disturb each other
DurabilitySaved data survives a crash

See MySQL Transactions.

What is the difference between primary key and unique key?

PointPrimary keyUnique key
NULL allowedNoYes (it allows NULL values)
How many per tableOneMany
PurposeIdentifies each rowStops duplicate values in a column, like email
CREATE TABLE users (
  id INT PRIMARY KEY,
  email VARCHAR(100) UNIQUE
);

See MySQL Constraints.

How to find the second highest marks in MySQL?

The examples use the students table from our MySQL tutorial: id, name, city, marks, course_id.

-- 1. with a subquery
SELECT MAX(marks) AS second_highest
FROM students
WHERE marks < (SELECT MAX(marks) FROM students);

-- 2. with LIMIT and OFFSET
SELECT DISTINCT marks
FROM students
ORDER BY marks DESC
LIMIT 1 OFFSET 1;
Tutorials Class - Output Window
second_highest
88

The highest marks are 92 (Maria), so the second highest is 88 (Asha). For the Nth highest, change the OFFSET to N – 1. See Subqueries.

How to find duplicate records in a MySQL table?

The examples use the students table from our MySQL tutorial: id, name, city, marks, course_id.

SELECT city, COUNT(*) AS total
FROM students
GROUP BY city
HAVING COUNT(*) > 1;
Tutorials Class - Output Window
city total
Delhi 2
Mumbai 2

Delhi and Mumbai appear in two rows each. To see the full duplicate rows, join this result back with the table. To prevent duplicates in the future, add a UNIQUE constraint. See GROUP BY and HAVING.

What is NULL in MySQL? Is NULL the same as 0 or an empty string?

NULL means “no value” or “unknown”. It is not zero and not an empty string.

SELECT NULL = NULL, NULL IS NULL, 0 IS NULL, '' IS NULL;
Tutorials Class - Output Window
NULL = NULL NULL IS NULL 0 IS NULL ” IS NULL
NULL 1 0 0

NULL = NULL gives NULL (not true). Always use IS NULL and IS NOT NULL. Aggregate functions ignore NULL, and COALESCE(column, 0) replaces NULL with a value.