SQL Interview Questions

Master your interview preparation with comprehensive Q&A covering all difficulty levels

Master SQL Interviews for QA Database Testing

Why SQL Interviews Matter: QA engineers who can write SQL are worth 30-50% more than those who can't. Companies need QA engineers who can directly verify database state, set up test data, and investigate test failures at the database level. SQL knowledge separates junior from senior QA engineers.

Key Topics Interviewers Ask:

  • JOINs (Inner, Left, Right, Full): How data relationships work. Critical for complex queries
  • WHERE vs HAVING: Filtering rows vs filtering groups — misunderstanding this is a red flag
  • GROUP BY & Aggregate Functions: COUNT, SUM, AVG, MAX/MIN with proper grouping
  • Subqueries & CTEs: Writing complex nested queries for data verification
  • Indexes & Performance: Why indexes matter, when to use them
  • Transactions & ACID: Understanding data consistency in testing

Real-World Testing Context: Interviewers don't expect you to be a DBA. They expect you to write queries that answer testing questions: "Did this user's profile update correctly?" "What's the order count for this account?" "Are there duplicate records?". Always frame answers in testing context, not database administration.

Common Interview Mistakes:

  • ❌ Confusing INNER JOIN with LEFT JOIN (you must know the difference)
  • ❌ Not understanding the difference between NULL and empty string
  • ❌ Using SELECT * in production (bad habit, but show you know why)
  • ❌ Not mentioning indexing when discussing query optimization

SQL Interview Questions - Beginner Level

Q 1

What is SQL?

SQL (Structured Query Language) is language for managing relational databases. Used for CRUD operations, querying, updating, deleting data. Standard language across databases.

(StructuredQueryLanguage)language
Q 2

What is a database?

Organized collection of structured data stored in tables. Accessed/managed using database management systems (DBMS). Example: MySQL, PostgreSQL, SQL Server, Oracle.

Organizedcollectionstructureddata
Q 3

What is a table in SQL?

Collection of rows and columns. Rows represent records, columns represent attributes. Example: Users table with id, name, email columns.

CollectionrowscolumnsRows
Q 4

What are primary keys?

Unique identifier for each row. Cannot be NULL, must be unique. Example: id INT PRIMARY KEY

UniqueidentifiereachCannot
Q 5

What are foreign keys?

Reference to primary key in another table. Maintains referential integrity. Example: FOREIGN KEY (user_id) REFERENCES Users(id)

Referenceprimaryanothertable
Q 6

What is data type in SQL?

Defines type of data column can hold: INT, VARCHAR, DATE, BOOLEAN, DECIMAL. Ensure data integrity.

Definestypedatacolumn
Q 7

What is the SELECT statement?

Retrieves data from table. Basic syntax: SELECT column_name FROM table_name WHERE condition;

RetrievesdatatableBasic
Q 8

What is the WHERE clause?

Filters rows based on condition: SELECT * FROM Users WHERE age > 18; Can use operators: =, !=, <, >, <=, >=, LIKE, IN, BETWEEN.

Filtersrowsbasedcondition
Q 9

What is the INSERT statement?

Adds new rows to table: INSERT INTO Users (name, email) VALUES ('John', 'john@email.com');

AddsrowstableINSERT
Q 10

What is the UPDATE statement?

Modifies existing rows: UPDATE Users SET email='new@email.com' WHERE id=1;

ModifiesexistingrowsUPDATE
Q 11

What is the DELETE statement?

Removes rows from table: DELETE FROM Users WHERE id=1; Use WHERE to avoid deleting all data.

RemovesrowstableDELETE
Q 12

What is DISTINCT keyword?

Removes duplicates from results: SELECT DISTINCT city FROM Users;

RemovesduplicatesresultsSELECT
Q 13

What is ORDER BY clause?

Sorts results: SELECT * FROM Users ORDER BY name ASC; (ASC ascending, DESC descending)

SortsresultsSELECTUsers
Q 14

What is LIMIT clause?

Restricts number of rows returned: SELECT * FROM Users LIMIT 10; Returns first 10 rows.

Restrictsnumberrowsreturned
Q 15

What is OFFSET clause?

Skips rows: SELECT * FROM Users LIMIT 10 OFFSET 5; Skips first 5, returns next 10.

SkipsrowsSELECTUsers
Q 16

What are aggregate functions?

COUNT(), SUM(), AVG(), MIN(), MAX(). Example: SELECT COUNT(*) FROM Users;

COUNT()SUM()AVG()MIN()
Q 17

What is GROUP BY clause?

Groups rows by column: SELECT city, COUNT(*) FROM Users GROUP BY city; Shows count per city.

GroupsrowscolumnSELECT
Q 18

What is HAVING clause?

Filters groups: SELECT city, COUNT(*) FROM Users GROUP BY city HAVING COUNT(*) > 5;

FiltersgroupsSELECTcity
Q 19

What are joins?

Combine rows from multiple tables. Types: INNER, LEFT, RIGHT, FULL. Example: SELECT * FROM Users INNER JOIN Orders ON Users.id = Orders.user_id;

Combinerowsmultipletables
Q 20

What is INNER JOIN?

Returns matching rows from both tables: SELECT * FROM Users INNER JOIN Orders ON Users.id = Orders.user_id;

Returnsmatchingrowsboth
Q 21

What is LEFT JOIN?

Returns all rows from left table + matching from right: SELECT * FROM Users LEFT JOIN Orders ON Users.id = Orders.user_id;

Returnsrowslefttable
Q 22

What is RIGHT JOIN?

Returns all rows from right table + matching from left: SELECT * FROM Users RIGHT JOIN Orders ON Users.id = Orders.user_id;

Returnsrowsrighttable
Q 23

What is FULL JOIN?

Returns all rows from both tables: SELECT * FROM Users FULL OUTER JOIN Orders ON Users.id = Orders.user_id;

Returnsrowsbothtables
Q 24

What is CROSS JOIN?

Cartesian product of two tables. Returns all combinations: SELECT * FROM Users CROSS JOIN Orders;

CartesianproducttablesReturns
Q 25

What are subqueries?

Query within query: SELECT * FROM Users WHERE id IN (SELECT user_id FROM Orders);

QuerywithinquerySELECT
Q 26

What is LIKE operator?

Pattern matching: SELECT * FROM Users WHERE name LIKE 'J%'; (% wildcard for any chars, _ for single char)

PatternmatchingSELECTUsers
Q 27

What is IN operator?

Check membership: SELECT * FROM Users WHERE city IN ('NYC', 'LA', 'SF');

CheckmembershipSELECTUsers
Q 28

What is BETWEEN operator?

Range check: SELECT * FROM Users WHERE age BETWEEN 20 AND 30;

RangecheckSELECTUsers
Q 29

What are NULL values in SQL?

Unknown or missing data. Use IS NULL or IS NOT NULL: SELECT * FROM Users WHERE phone IS NULL;

UnknownmissingdataNULL
Q 30

What are string functions?

CONCAT(), SUBSTRING(), LENGTH(), UPPER(), LOWER(), TRIM(). Example: SELECT UPPER(name) FROM Users;

CONCAT()SUBSTRING()LENGTH()UPPER()
Q 31

What are numeric functions?

ABS(), ROUND(), CEIL(), FLOOR(), POWER(). Example: SELECT ROUND(price, 2) FROM Products;

ABS()ROUND()CEIL()FLOOR()
Q 32

What are date functions?

NOW(), DATE(), EXTRACT(), DATE_ADD(), DATE_DIFF(). Example: SELECT NOW() FROM dual;

NOW()DATE()EXTRACT()DATE_ADD()
Q 33

What is ALTER TABLE?

Modify table structure: ALTER TABLE Users ADD COLUMN phone VARCHAR(10);

ModifytablestructureALTER
Q 34

What is CREATE TABLE?

Create new table: CREATE TABLE Users (id INT PRIMARY KEY, name VARCHAR, email VARCHAR(100));

CreatetableCREATETABLE
Q 35

What is DROP TABLE?

Delete entire table: DROP TABLE Users; Removes table and data.

DeleteentiretableDROP
Q 36

What is constraint?

Rules for data: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT.

RulesdataNULLUNIQUE
Q 37

What is NOT NULL constraint?

Column must have value: CREATE TABLE Users (name VARCHAR NOT NULL);

Columnmusthavevalue
Q 38

What is UNIQUE constraint?

All values unique in column: CREATE TABLE Users (email VARCHAR(100) UNIQUE);

valuesuniquecolumnCREATE
Q 39

What is DEFAULT constraint?

Default value if not specified: CREATE TABLE Users (status VARCHAR(10) DEFAULT 'active');

DefaultvaluespecifiedCREATE
Q 40

What is CHECK constraint?

Validates data: CREATE TABLE Users (age INT CHECK (age >= 18));

ValidatesdataCREATETABLE
Q 41

What is index in SQL?

Speeds up queries: CREATE INDEX idx_name ON Users(name); Slows down INSERT/UPDATE but speeds SELECT.

SpeedsqueriesCREATEINDEX
Q 42

What are transaction ACID properties?

Atomicity (all or nothing), Consistency (valid state), Isolation (independent), Durability (persistent).

Atomicity(allnothing)Consistency
Q 43

What is COMMIT and ROLLBACK?

COMMIT saves changes. ROLLBACK undoes changes. Example: START TRANSACTION; ... COMMIT; or ROLLBACK;

COMMITsaveschangesROLLBACK
Q 44

What is UNION operator?

Combine results from two queries: SELECT name FROM Users UNION SELECT name FROM Customers;

CombineresultsqueriesSELECT
Q 45

What is UNION ALL?

UNION with duplicates: SELECT name FROM Users UNION ALL SELECT name FROM Customers;

UNIONduplicatesSELECTname
Q 46

What is EXCEPT/MINUS operator?

Returns rows from first query not in second: SELECT id FROM Users EXCEPT SELECT id FROM BannedUsers;

Returnsrowsfirstquery
Q 47

What is INTERSECT operator?

Returns rows in both queries: SELECT id FROM Users INTERSECT SELECT id FROM Subscribers;

Returnsrowsbothqueries
Q 48

What is self-join?

Join table with itself: SELECT a.name, b.name FROM Users a, Users b WHERE a.manager_id = b.id;

JointableitselfSELECT
Q 49

What is CREATE INDEX?

Create index for faster queries: CREATE INDEX idx_email ON Users(email);

Createindexfasterqueries
Q 50

What is explain plan in SQL?

Shows query execution plan. Example: EXPLAIN SELECT * FROM Users WHERE id = 1; Helps optimize queries.

Showsqueryexecutionplan

SQL Interview Questions - Intermediate Level

Q 51

What are window functions?

Aggregate over partitions without grouping: SELECT name, salary, ROW_NUMBER() OVER (ORDER BY salary DESC) as rank FROM Users;

Aggregateoverpartitionswithout
Q 52

What is PARTITION BY clause?

Divide rows into groups: SELECT dept, name, AVG(salary) OVER (PARTITION BY dept) FROM Users;

Dividerowsintogroups
Q 53

What are ranking functions?

ROW_NUMBER(), RANK(), DENSE_RANK(). ROW_NUMBER gives unique, RANK/DENSE_RANK handle ties.

ROW_NUMBER()RANK()DENSE_RANK()ROW_NUMBER
Q 54

What is CTE (Common Table Expression)?

Temporary named result set: WITH temp AS (SELECT * FROM Users WHERE active=1) SELECT * FROM temp;

Temporarynamedresulttemp
Q 55

What is recursive CTE?

CTE referencing itself. Useful for hierarchical data: WITH RECURSIVE temp AS (...) SELECT * FROM temp;

referencingitselfUsefulhierarchical
Q 56

What are views?

Virtual table from query: CREATE VIEW ActiveUsers AS SELECT * FROM Users WHERE active=1; SELECT * FROM ActiveUsers;

VirtualtablequeryCREATE
Q 57

What are stored procedures?

Reusable SQL code: CREATE PROCEDURE GetUsers() BEGIN SELECT * FROM Users; END; CALL GetUsers();

ReusablecodeCREATEPROCEDURE
Q 58

What are triggers?

Automatic code on table events: CREATE TRIGGER update_timestamp BEFORE UPDATE ON Users FOR EACH ROW SET NEW.updated_at = NOW();

Automaticcodetableevents
Q 59

What is normalization?

Organize data to reduce redundancy. Normal forms: 1NF, 2NF, 3NF, BCNF. Improve data integrity.

Organizedatareduceredundancy
Q 60

What is 1NF (First Normal Form)?

Atomic values only (no repeating groups). Each column has single value. Example: no arrays in cells.

Atomicvaluesonlyrepeating
Q 61

What is 2NF (Second Normal Form)?

1NF + all non-key columns depend on entire primary key. No partial dependencies.

non-keycolumnsdependentire
Q 62

What is 3NF (Third Normal Form)?

2NF + no transitive dependencies. Non-key columns depend only on primary key.

transitivedependenciesNon-keycolumns
Q 63

What is denormalization?

Combine tables for performance. Trade normalized design for query speed. Use carefully.

CombinetablesperformanceTrade
Q 64

What are scalar subqueries?

Subquery returning single value: SELECT name, (SELECT COUNT(*) FROM Orders WHERE user_id = Users.id) FROM Users;

Subqueryreturningsinglevalue
Q 65

What are correlated subqueries?

Subquery referencing outer query: SELECT * FROM Users u WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.user_id = u.id);

Subqueryreferencingouterquery
Q 66

What are derived tables?

Subquery in FROM clause: SELECT * FROM (SELECT * FROM Users WHERE active=1) t WHERE t.age > 18;

SubqueryclauseSELECT(SELECT
Q 67

What is CASE statement?

Conditional logic: SELECT name, CASE WHEN age < 18 THEN 'Minor' ELSE 'Adult' END as status FROM Users;

ConditionallogicSELECTname
Q 68

What is COALESCE function?

Returns first non-NULL value: SELECT COALESCE(phone, email, 'No contact') FROM Users;

Returnsfirstnon-NULLvalue
Q 69

What is IFNULL/ISNULL function?

Replace NULL with value: SELECT IFNULL(phone, 'N/A') FROM Users; (MySQL/PostgreSQL: COALESCE)

ReplaceNULLvalueSELECT
Q 70

What are set operations?

UNION, INTERSECT, EXCEPT. Combine/compare results from multiple queries.

UNIONINTERSECTEXCEPTCombine/compare
Q 71

What is TRUNCATE statement?

Remove all rows from table (faster than DELETE): TRUNCATE TABLE Users; Cannot rollback in some DBs.

Removerowstable(faster
Q 72

What are user-defined functions?

Create custom functions: CREATE FUNCTION calcAge(birthDate) RETURNS INT BEGIN RETURN YEAR(NOW()) - YEAR(birthDate); END;

CreatecustomfunctionsCREATE
Q 73

What are string concatenation methods?

CONCAT() function or + operator. Example: CONCAT(first_name, ' ', last_name) or first_name + ' ' + last_name

CONCAT()functionoperatorExample
Q 74

What is JSON support in SQL?

Store/query JSON: JSON_EXTRACT(), JSON_CONTAINS(). Example: SELECT JSON_EXTRACT(data, '$.name') FROM Users;

Store/queryJSONJSON_EXTRACT()JSON_CONTAINS()
Q 75

What is full-text search?

Search text content efficiently: SELECT * FROM Articles WHERE MATCH(content) AGAINST('keyword');

Searchtextcontentefficiently
Q 76

What are column aliases?

Rename column in result: SELECT name AS user_name FROM Users;

RenamecolumnresultSELECT
Q 77

What are table aliases?

Rename table in query: SELECT u.name FROM Users u WHERE u.id = 1;

RenametablequerySELECT
Q 78

What is query optimization?

Improve query performance: use indexes, avoid SELECT *, optimize joins, use LIMIT. Analyze execution plans.

Improvequeryperformanceindexes
Q 79

What causes N+1 query problem?

Fetching parent, then child for each parent (inefficient). Solve with joins or batch queries.

Fetchingparentthenchild
Q 80

What is database locking?

Prevent concurrent modifications. Types: row lock, table lock. Can cause deadlocks.

PreventconcurrentmodificationsTypes
Q 81

What is deadlock in SQL?

Two transactions waiting on each other. Detect/resolve with SHOW ENGINE INNODB STATUS. Use timeouts.

transactionswaitingeachother
Q 82

What is table backup/restore?

Backup data: DUMP, BACKUP commands. Restore: RESTORE. Ensure data safety.

BackupdataDUMPBACKUP
Q 83

What is database replication?

Copy data to another server. Master-slave setup. Improves availability and load distribution.

Copydataanotherserver
Q 84

What are parameterized queries?

Prevent SQL injection: SELECT * FROM Users WHERE id = ?; Use placeholders instead of concatenation.

PreventinjectionSELECTUsers
Q 85

What is SQL injection?

Malicious SQL in user input. Example: input = "' OR '1'='1"; Prevent with parameterized queries.

MalicioususerinputExample
Q 86

What is GRANT and REVOKE?

Control permissions: GRANT SELECT ON Users TO user; REVOKE SELECT ON Users FROM user;

ControlpermissionsGRANTSELECT
Q 87

What are database schemas?

Organize tables into groups: CREATE SCHEMA myschema; CREATE TABLE myschema.Users (...);

Organizetablesintogroups
Q 88

What are sequences?

Generate unique numbers: CREATE SEQUENCE id_seq; Use in INSERT for auto-increment.

GenerateuniquenumbersCREATE
Q 89

What is database sharding?

Horizontal partitioning across servers. Each shard holds subset of data. Improves scalability.

Horizontalpartitioningacrossservers
Q 90

What are virtual columns?

Computed columns not stored physically: CREATE TABLE Users (age INT, birth_year INT, VIRTUAL year_age AS (YEAR(NOW()) - birth_year));

Computedcolumnsstoredphysically
Q 91

What is COLLATION in SQL?

Sorting/comparison rules: DEFAULT COLLATE utf8_general_ci; Affects case sensitivity.

Sorting/comparisonrulesDEFAULTCOLLATE
Q 92

What are CHECK constraints?

Validate column values: ALTER TABLE Users ADD CONSTRAINT chk_age CHECK (age >= 18);

ValidatecolumnvaluesALTER
Q 93

What is CASCADE delete?

Delete child records when parent deleted: FOREIGN KEY (parent_id) REFERENCES Parent(id) ON DELETE CASCADE;

Deletechildrecordswhen
Q 94

What are BEFORE and AFTER triggers?

BEFORE: execute before operation. AFTER: execute after operation. Example: BEFORE UPDATE, AFTER INSERT.

BEFOREexecutebeforeoperation
Q 95

What is query caching?

Store query results in memory for speed. Some DBs have native caching. Also application-level caching.

Storequeryresultsmemory
Q 96

What is query plan analysis?

Analyze EXPLAIN output. Identify slow queries, sequential scans, missing indexes. Optimize accordingly.

AnalyzeEXPLAINoutputIdentify
Q 97

What are temporary tables?

Tables that exist during session: CREATE TEMPORARY TABLE temp (...); Automatically dropped.

Tablesexistduringsession
Q 98

What is database clustering?

Multiple servers acting as one database. Improves availability and load balancing.

Multipleserversactingdatabase
Q 99

What is connection pooling?

Reuse database connections. Improves performance by reducing connection overhead.

ReusedatabaseconnectionsImproves
Q 100

What are database migrations?

Version-controlled schema changes. Tools: Flyway, Liquibase. Track all changes, enable rollback.

Version-controlledschemachangesTools

SQL Interview Questions - Advanced Level

101-150. Advanced Topics (abbreviated)

101-110: Advanced window functions (LAG, LEAD, FIRST_VALUE, LAST_VALUE), pivot tables, XML/JSON operations, custom aggregates. 111-120: Query tuning, index strategies (B-tree, Hash, Full-text), statistics and cost estimation, parallel query execution. 121-130: Distributed SQL, ACID/MVCC, transaction isolation levels (READ COMMITTED, REPEATABLE READ, SERIALIZABLE), consistency models. 131-140: Advanced triggers and stored procedures, event handling, database automation, resource management. 141-150: NoSQL vs SQL, polyglot persistence, cloud databases (AWS RDS, Azure SQL, Google Cloud SQL), blockchain databases, time-series databases.