Fundamental SQL Concepts - Interview Questions and Answers
A storage engine is the underlying software that handles how data is stored, retrieved, and managed in a database.
Storage Engine | Features | Use Case |
---|---|---|
InnoDB | Supports transactions, foreign keys, ACID compliance | Best for OLTP, banking, e-commerce |
MyISAM | Faster reads, no foreign keys, table-level locking | Good for analytics, search engines |
Memory | Stores data in RAM, very fast, non-persistent | Session data, temporary calculations |
CSV | Stores data in CSV files, no indexes | Data exchange, logs |
ARCHIVE | Highly compressed, supports only INSERT & SELECT | Archival storage |
NDB Cluster | Distributed, high-availability | Telecom, real-time applications |
SHOW TABLE STATUS WHERE Name = 'Orders';
ALTER TABLE Orders ENGINE = InnoDB;
InnoDB is best because it supports ACID compliance, transactions, and foreign keys.
It does not support transactions or foreign keys, leading to data integrity risks.
A primary key is a column (or set of columns) that uniquely identifies each record in a table.
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(255),
City VARCHAR(100)
);
A foreign key creates a relationship between two tables.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
If referential integrity is enforced:
- CASCADE - Deletes child records
- SET NULL - Sets child values to NULL
- RESTRICT - Prevents deletion
ON DELETE CASCADE;
ON DELETE SET NULL;
ON DELETE RESTRICT;
SET FOREIGN_KEY_CHECKS = 0; -- Disable
SET FOREIGN_KEY_CHECKS = 1; -- Enable
GRANT ALL PRIVILEGES ON mydatabase.* TO 'user1'@'localhost';
FLUSH PRIVILEGES;
REVOKE ALL PRIVILEGES ON mydatabase.* FROM 'user1'@'localhost';
GRANT SELECT ON mydatabase.* TO 'user1'@'localhost';
SHOW GRANTS FOR 'user1'@'localhost';
A character set (charset) defines how text is stored (e.g., utf8
, latin1
).
A collation defines sorting and comparison rules (e.g., utf8_general_ci
, utf8_unicode_ci
).
utf8_general_ci
- Faster, but less accurate sortingutf8_unicode_ci
- More accurate, supports multiple languages
SHOW CREATE DATABASE mydatabase;
ALTER TABLE Customers CHARACTER SET utf8 COLLATE utf8_unicode_ci;
utf8mb4_unicode_ci
? Supports Hindi, Tamil, Bengali, etc.
- ACID (Atomicity, Consistency, Isolation, Durability) ? Used in SQL databases.
- BASE (Basically Available, Soft state, Eventually consistent) ? Used in NoSQL databases.
START TRANSACTION;
UPDATE Accounts SET Balance = Balance - 500 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 500 WHERE AccountID = 2;
COMMIT;
An index improves query performance by creating a sorted structure for lookups.
CREATE INDEX idx_customer ON Orders(CustomerID);
A unique key prevents duplicate values but allows one NULL.
CREATE TABLE Employees (
EmployeeID INT UNIQUE,
Name VARCHAR(255)
);
Index Type | Description | Use Case |
---|---|---|
Clustered Index | Stores data physically sorted | Best for primary keys |
Non-Clustered Index | Stores a pointer to data | Best for frequent searches |
CREATE UNIQUE INDEX idx_unique ON Employees(Name, Department);
A deadlock occurs when two queries wait for each other to release locks.
Prevention: Lock tables in the same order
- Row-level locking (InnoDB) - Better performance
- Table-level locking (MyISAM) - Slower for concurrent writes
A transaction is a group of SQL queries executed as a single unit, ensuring data consistency.
Example: Transferring Rs.500 between two bank accounts
START TRANSACTION;
UPDATE Accounts SET Balance = Balance - 500 WHERE AccountID = 101;
UPDATE Accounts SET Balance = Balance + 500 WHERE AccountID = 102;
COMMIT; -- Saves the changes
If any query fails, use ROLLBACK
to cancel the transaction.
Property | Description |
---|---|
Atomicity | All queries succeed or none are applied |
Consistency | Data remains in a valid state before and after |
Isolation | Transactions do not affect each other |
Durability | Changes are saved permanently |
Command | Description |
---|---|
COMMIT | Saves all changes made in a transaction |
ROLLBACK | Undoes all changes made in a transaction |
Example:
START TRANSACTION;
DELETE FROM Employees WHERE EmployeeID = 5;
ROLLBACK; -- Restores the deleted row
A Savepoint allows partial rollbacks inside a transaction.
START TRANSACTION;
DELETE FROM Employees WHERE Department = 'HR';
SAVEPOINT SP1;
DELETE FROM Employees WHERE Department = 'IT';
ROLLBACK TO SP1; -- Undo IT deletions but keep HR deletions
COMMIT;
Lock Type | Description |
---|---|
Shared Lock (S-Lock) | Allows read but blocks write |
Exclusive Lock (X-Lock) | Blocks both read and write |
Row-Level Locking | Locks individual rows |
Table-Level Locking | Locks the entire table |
Example: Explicit table locking
LOCK TABLE Orders WRITE;
UPDATE Orders SET Status = 'Shipped' WHERE OrderID = 1001;
UNLOCK TABLES;
Always access tables in the same order
Use row-level locks instead of table-level locks
Keep transactions short
Example of Deadlock Prevention
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
START TRANSACTION;
UPDATE Accounts SET Balance = Balance - 500 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 500 WHERE AccountID = 2;
COMMIT;
An index is a performance optimization structure that speeds up searches.
CREATE INDEX idx_customer ON Orders(CustomerID);
Faster queries but slower INSERTs/UPDATEs
Index Type | Description |
---|---|
Primary Index | Automatically created for Primary Keys |
Unique Index | Ensures values are unique |
Clustered Index | Sorts data physically (only one per table) |
Non-Clustered Index | Stores a pointer to actual data |
Full-text Index | Used for searching text data efficiently |
Feature | Clustered Index | Non-Clustered Index |
---|---|---|
Data Storage | Stores data physically sorted | Stores pointers to data |
Speed | Faster for range queries | Faster for lookups |
Example | PRIMARY KEY (CustomerID) | CREATE INDEX idx_name ON Customers(Name); |
DROP INDEX idx_customer ON Orders;
Constraints enforce rules on data to maintain integrity.
Constraint | Purpose |
---|---|
PRIMARY KEY | Uniquely identifies records |
FOREIGN KEY | Ensures referential integrity |
UNIQUE | Ensures column values are unique |
NOT NULL | Prevents NULL values |
CHECK | Restricts column values |
ALTER TABLE Employees ADD CONSTRAINT chk_salary CHECK (Salary > 20000);
MyISAM - Faster reads, good for reporting.
ALTER TABLE Sales ENGINE = MyISAM;
InnoDB - Supports transactions, best for banking, finance.
Memory Engine - Stores data in RAM for faster access.
CREATE TEMPORARY TABLE TempUsers ENGINE=MEMORY AS SELECT * FROM Users;
Feature | InnoDB | MyISAM |
---|---|---|
Transactions | Yes | No |
Foreign Keys | Yes | No |
Locking | Row-Level | Table-Level |
Speed | Fast for writes | Fast for reads |
SHOW TABLE STATUS WHERE Name = 'Orders';
Use indexes
Avoid **SELECT ***
Use JOINs instead of subqueries
Use EXPLAIN to analyze queries
EXPLAIN SELECT * FROM Orders WHERE CustomerID = 5;
Stores query results in memory for faster retrieval.
SET GLOBAL query_cache_size = 1000000;
Feature | WHERE | HAVING |
---|---|---|
Used With | Columns | Aggregates |
Executes | Before GROUP BY | After GROUP BY |
SELECT City, AVG(Salary) FROM Employees GROUP BY City HAVING AVG(Salary) > 30000;
DELETE FROM Employees
WHERE EmployeeID NOT IN (
SELECT MIN(EmployeeID) FROM Employees GROUP BY Name, Department
);
OPTIMIZE TABLE Orders;
Tutorials
Random Blogs
- Python Challenging Programming Exercises Part 2
- The Ultimate Guide to Data Science: Everything You Need to Know
- Important Mistakes to Avoid While Advertising on Facebook
- Variable Assignment in Python
- 5 Ways Use Jupyter Notebook Online Free of Cost
- String Operations in Python
- Downlaod Youtube Video in Any Format Using Python Pytube Library
- Why to learn Digital Marketing?
- Datasets for Natural Language Processing
- How to Become a Good Data Scientist ?