If you have an SQL interview coming up, you already know the feeling — the syllabus is huge, every company asks something slightly different, and it's hard to know where to draw the line baetween "nice to know" and "will definitely be asked." This guide is built to remove that guesswork. It walks through 100 of the most commonly asked SQL interview questions, from basic definitions that freshers get asked in their very first technical round, all the way to execution plans and locking behavior that senior engineers are expected to explain confidently.
Whether you're a student preparing for your first job, a fresher applying to data or backend roles, or an experienced professional brushing up before a switch, these SQL interview questions cover what actually gets asked in 2026 — not just textbook theory. Along the way, you'll find query examples, sample tables, comparison tables between MySQL, PostgreSQL, SQL Server, and Oracle, and a few coding exercises you can try on your own. If you want a place to actually run these queries and test yourself against other learners, platforms like HelloEngineers let you practice SQL problems, take mock interviews, and compare notes with other engineers preparing for the same roles.
Why SQL Interview Questions Still Matter in 2026
SQL isn't going anywhere. Even with the rise of NoSQL databases, vector stores, and AI-assisted querying tools, almost every backend, data, and analytics role still expects you to write clean, efficient SQL by hand. Interviewers ask SQL interview questions not because they want you to recite definitions, but because SQL reveals how you think about data — how you structure a query, how you reason about performance, and how you avoid mistakes that could lock a production table or return wrong results.
That's why this list doesn't stop at "what is a primary key." It goes deep into joins, subqueries, CTEs, window functions, transactions, and optimization — the areas where candidates usually lose points not because they don't know SQL, but because they can't explain it clearly under pressure.
How This Guide Is Organized
To make this easy to study section by section, the 100 SQL interview questions are grouped into topic clusters:
- Basic SQL concepts for freshers
- DDL, DML, DCL, and TCL commands
- Constraints — primary key, foreign key, unique key
- Joins — INNER, LEFT, RIGHT, FULL
- GROUP BY, HAVING, ORDER BY, and aggregate functions
- Subqueries and correlated subqueries
- CTEs and recursive queries
- Views, indexes, and stored procedures
- Normalization and denormalization
- Transactions, ACID properties, locks, and concurrency
- Window and ranking functions
- Query optimization and execution plans
- Database security
Each answer is written to be interview-ready: short enough to say out loud in 30–60 seconds, but detailed enough to show real understanding.
Sample Database Tables Used in This Guide
A few questions below reference these two simple tables. Keep them in mind as you read through the examples.
Employees
| emp_id | emp_name | dept_id | salary | manager_id |
|---|---|---|---|---|
| 1 | Aditi | 10 | 55000 | NULL |
| 2 | Rahul | 10 | 48000 | 1 |
| 3 | Meera | 20 | 62000 | 1 |
| 4 | Sanjay | 20 | 45000 | 3 |
| 5 | Priya | 30 | 71000 | 1 |
Departments
| dept_id | dept_name |
|---|---|
| 10 | Engineering |
| 20 | Sales |
| 30 | Marketing |
Basic SQL Interview Questions (For Freshers)
These are the SQL interview questions almost every fresher gets asked in the first round. Get comfortable with them before moving to anything advanced.
1. What is SQL?
SQL (Structured Query Language) is a standard language used to create, manage, and manipulate relational databases. It lets you define tables, insert and update data, retrieve information with queries, and control access to that data.
2. What is a database?
A database is an organized collection of structured data stored electronically so it can be easily accessed, managed, and updated. Relational databases organize this data into tables made up of rows and columns.
3. What is RDBMS?
RDBMS stands for Relational Database Management System. It's software that manages relational databases, enforcing relationships between tables through keys and supporting SQL as the query language. MySQL, PostgreSQL, SQL Server, and Oracle are all RDBMS products.
4. What are the different types of SQL commands?
SQL commands fall into five categories: DDL (Data Definition Language), DML (Data Manipulation Language), DCL (Data Control Language), TCL (Transaction Control Language), and DQL (Data Query Language, mainly SELECT).
5. What is a primary key?
A primary key uniquely identifies each row in a table. It cannot contain NULL values, and a table can have only one primary key, though that key can span multiple columns (composite key).
6. What is a foreign key?
A foreign key is a column (or set of columns) in one table that references the primary key of another table. It enforces referential integrity by ensuring the referenced value actually exists.
7. What is the difference between CHAR and VARCHAR?
CHAR is a fixed-length data type that pads unused space, while VARCHAR is variable-length and only stores the actual number of characters entered. VARCHAR is generally more storage-efficient for variable text.
8. What is a NULL value in SQL?
NULL represents missing, unknown, or inapplicable data. It is not the same as zero or an empty string, and comparisons with NULL always return unknown, which is why you use IS NULL instead of = NULL.
9. What is the difference between SQL and MySQL?
SQL is a language used to interact with relational databases. MySQL is a specific RDBMS product that implements SQL, along with its own extensions and storage engines.
10. What is a query in SQL?
A query is a request for data or action against a database, most commonly written using SELECT, INSERT, UPDATE, or DELETE statements.
11. What is the SELECT statement used for?
SELECT retrieves data from one or more tables. You can filter rows with WHERE, sort results with ORDER BY, and combine data from multiple tables using joins.
12. What is the difference between WHERE and HAVING?
WHERE filters individual rows before any grouping happens, while HAVING filters groups after GROUP BY has been applied. You cannot use aggregate functions in WHERE, but you can in HAVING.
13. What is the difference between DELETE, TRUNCATE, and DROP?
DELETE removes specific rows using a WHERE clause and can be rolled back. TRUNCATE removes all rows quickly and resets identity counters but generally cannot target specific rows. DROP removes the entire table structure along with its data.
14. What are aggregate functions in SQL?
Aggregate functions perform a calculation across a set of rows and return a single value. Common examples are COUNT(), SUM(), AVG(), MIN(), and MAX().
15. What is the difference between UNION and UNION ALL?
UNION combines results from two queries and removes duplicate rows, which requires extra processing. UNION ALL combines results without removing duplicates, making it faster when you know duplicates aren't a concern.
SQL Interview Questions on DDL, DML, DCL, and TCL
16. What is DDL in SQL? DDL, or Data Definition Language, includes commands that define or modify database structure — CREATE, ALTER, DROP, and TRUNCATE.
17. What is DML in SQL? DML, or Data Manipulation Language, includes commands that manipulate the data inside tables — INSERT, UPDATE, and DELETE.
18. What is DCL in SQL? DCL, or Data Control Language, controls access permissions in the database. GRANT gives users specific privileges, and REVOKE takes them away.
19. What is TCL in SQL? TCL, or Transaction Control Language, manages transactions within a database. COMMIT saves changes permanently, ROLLBACK undoes uncommitted changes, and SAVEPOINT marks a point you can roll back to without undoing the entire transaction.
20. What is the difference between CREATE and ALTER? CREATE builds a new database object, such as a table or view, from scratch. ALTER modifies an existing object's structure, for example adding or dropping a column.
21. How do you add a column to an existing table?
ALTER TABLE Employees ADD email VARCHAR(100);
22. How do you rename a table in SQL?
-- MySQL / PostgreSQL
ALTER TABLE Employees RENAME TO Staff;
-- SQL Server
EXEC sp_rename 'Employees', 'Staff';
23. What is the purpose of the GRANT and REVOKE commands? GRANT assigns specific privileges (such as SELECT, INSERT, or UPDATE) to a database user or role. REVOKE removes those previously granted privileges, tightening access when it's no longer needed.
24. What happens if you run DELETE without a WHERE clause? Every row in the table gets deleted, but the table structure remains intact and the operation can typically be rolled back if it's inside a transaction that hasn't committed yet.
25. Can DDL commands be rolled back? In most databases, DDL commands like CREATE, ALTER, and DROP auto-commit immediately, so they usually cannot be rolled back. PostgreSQL is a notable exception — it supports transactional DDL, meaning you can roll back schema changes within a transaction.
SQL Constraints Interview Questions (Primary Key, Foreign Key, Unique Key)
26. What are constraints in SQL? Constraints are rules enforced on table columns to maintain data accuracy and integrity. Common constraints include NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT.
27. What is the difference between a primary key and a unique key? A primary key does not allow NULL values and there can be only one per table. A unique key can allow one NULL value (in most databases) and a table can have multiple unique keys.
28. What is a composite key? A composite key is a primary key made up of two or more columns that together uniquely identify a row, even though no single column can do so on its own.
29. What is a CHECK constraint? A CHECK constraint restricts the values allowed in a column based on a condition. For example, CHECK (salary > 0) ensures salary can never be zero or negative.
30. What is a DEFAULT constraint? A DEFAULT constraint automatically assigns a specified value to a column when no value is provided during an INSERT.
31. What happens when you try to insert a duplicate value into a primary key column? The database rejects the insert and raises a constraint violation error, because primary key values must be unique across every row.
32. Can a foreign key reference a non-primary key column? Yes, but only if that column has a unique constraint. Foreign keys require the referenced column to guarantee uniqueness, whether it's the primary key or a separate unique key.
33. What is referential integrity? Referential integrity ensures relationships between tables stay consistent — a foreign key value must always match an existing value in the referenced table, or be NULL if allowed.
SQL Joins Interview Questions
Joins come up in nearly every SQL interview, often with a practical query to write on a whiteboard or shared editor.
34. What is a JOIN in SQL?
A JOIN combines rows from two or more tables based on a related column, typically a foreign key linking to a primary key.
35. What is an INNER JOIN?
INNER JOIN returns only the rows that have matching values in both tables.
SELECT e.emp_name, d.dept_name
FROM Employees e
INNER JOIN Departments d ON e.dept_id = d.dept_id;
36. What is a LEFT JOIN?
LEFT JOIN returns all rows from the left table, along with matching rows from the right table. If there's no match, columns from the right table return NULL.
SELECT e.emp_name, d.dept_name
FROM Employees e
LEFT JOIN Departments d ON e.dept_id = d.dept_id;
37. What is a RIGHT JOIN?
RIGHT JOIN returns all rows from the right table, along with matching rows from the left table, filling in NULL where there's no match. It's the mirror image of a LEFT JOIN.
38. What is a FULL OUTER JOIN?
FULL OUTER JOIN returns all rows from both tables, matching where possible and filling in NULL where a match doesn't exist on either side. MySQL doesn't support FULL OUTER JOIN natively — it's usually simulated with a UNION of LEFT and RIGHT joins.
39. What is a self join?
A self join joins a table to itself, typically used to compare rows within the same table — for example, finding each employee's manager from the same Employees table.
SELECT e.emp_name AS employee, m.emp_name AS manager
FROM Employees e
LEFT JOIN Employees m ON e.manager_id = m.emp_id;
40. What is a CROSS JOIN?
A CROSS JOIN produces the Cartesian product of two tables — every row from the first table combined with every row from the second. It's used rarely, mostly when you deliberately need all possible combinations.
41. What is the difference between JOIN and UNION?
JOIN combines columns from multiple tables side by side based on a related key. UNION combines rows from multiple queries that share the same column structure, stacking results vertically instead of horizontally.
42. How would you find employees who don't belong to any department?
SELECT e.emp_name
FROM Employees e
LEFT JOIN Departments d ON e.dept_id = d.dept_id
WHERE d.dept_id IS NULL;
GROUP BY, HAVING, ORDER BY, and Aggregate Functions
43. What does GROUP BY do?
GROUP BY arranges rows that share a value in specified columns into summary groups, usually so you can apply aggregate functions to each group separately.
SELECT dept_id, AVG(salary) AS avg_salary
FROM Employees
GROUP BY dept_id;
44. How is HAVING different from WHERE, with an example?
WHERE filters rows before grouping; HAVING filters groups after aggregation.
SELECT dept_id, COUNT(*) AS emp_count
FROM Employees
GROUP BY dept_id
HAVING COUNT(*) > 1;
45. What does ORDER BY do, and what's the default sort order?
ORDER BY sorts the result set by one or more columns. The default order is ascending (ASC); use DESC for descending order.
46. Can you use column aliases in ORDER BY?
Yes, most databases allow you to sort by a column alias defined in the SELECT clause, which makes queries more readable.
47. What is the difference between COUNT(*) and COUNT(column_name)?
COUNT(*) counts all rows, including those with NULL values in any column. COUNT(column_name) counts only the rows where that specific column is not NULL.
48. Can you use multiple aggregate functions in one query?
Yes. For example:
SELECT dept_id, COUNT(*) AS emp_count, AVG(salary) AS avg_salary, MAX(salary) AS top_salary
FROM Employees
GROUP BY dept_id;
49. What is the correct order of execution in an SQL query?
Logically, SQL executes in this order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. This is different from the order you write the clauses in, which trips up a lot of candidates.
50. Can GROUP BY be used without an aggregate function?
Yes, though it's unusual. GROUP BY without an aggregate function behaves similarly to SELECT DISTINCT, returning unique combinations of the grouped columns.
Subqueries and Correlated Subqueries
51. What is a subquery?
A subquery is a query nested inside another query, used to return data that the outer query then uses for filtering, comparison, or calculation.
SELECT emp_name
FROM Employees
WHERE salary > (SELECT AVG(salary) FROM Employees);
52. What is a correlated subquery?
A correlated subquery references a column from the outer query, so it runs once for every row processed by the outer query, rather than just once overall.
SELECT e.emp_name
FROM Employees e
WHERE e.salary > (
SELECT AVG(salary) FROM Employees e2 WHERE e2.dept_id = e.dept_id
);
53. What is the difference between a subquery and a correlated subquery?
A regular subquery executes independently and only once. A correlated subquery depends on the outer query's current row and re-executes for each row, which usually makes it slower on large datasets.
54. What is the difference between EXISTS and IN?
EXISTS checks whether a subquery returns any rows and stops as soon as it finds one match, which makes it efficient for large datasets. IN compares a value against a full list returned by the subquery, and can behave unpredictably if that list contains NULLs.
55. Can a subquery return multiple columns?
Yes, but how it's used matters. A subquery used with = must return a single value; subqueries used with IN, ANY, or ALL can return multiple rows in a single column, and subqueries in the FROM clause can return multiple columns and rows.
56. What is a scalar subquery?
A scalar subquery returns exactly one row and one column, so it can be used anywhere a single value is expected, such as in a SELECT list or a WHERE comparison.
Common Table Expressions (CTEs) and Recursive Queries
57. What is a CTE in SQL?
A Common Table Expression, defined with the WITH keyword, is a temporary named result set you can reference within a single query. It improves readability compared to deeply nested subqueries.
WITH DeptAvg AS (
SELECT dept_id, AVG(salary) AS avg_sal
FROM Employees
GROUP BY dept_id
)
SELECT e.emp_name, d.avg_sal
FROM Employees e
JOIN DeptAvg d ON e.dept_id = d.dept_id;
58. What is the difference between a CTE and a subquery?
A CTE is defined once at the top of the query using WITH and can be referenced multiple times within that query, while a subquery is written inline and typically has to be repeated if you need it more than once. CTEs are generally easier to read and debug.
59. What is a recursive CTE?
A recursive CTE references itself to process hierarchical or recursive data, such as an organizational chart. It has an anchor member (base case) and a recursive member that repeats until no more rows are returned.
WITH RECURSIVE OrgChart AS (
SELECT emp_id, emp_name, manager_id, 1 AS level
FROM Employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.emp_id, e.emp_name, e.manager_id, o.level + 1
FROM Employees e
JOIN OrgChart o ON e.manager_id = o.emp_id
)
SELECT * FROM OrgChart;
60. Where would you use a recursive CTE in real life?
Common use cases include traversing employee-manager hierarchies, category trees in e-commerce, bill-of-materials structures, and any parent-child relationship of unknown depth.
61. Does every database support CTEs?
Most modern databases do — MySQL (8.0+), PostgreSQL, SQL Server, and Oracle all support CTEs, though the exact recursive syntax differs slightly (for example, Oracle uses WITH ... AS combined with CONNECT BY as an alternative for hierarchical queries).
Views, Indexes, and Stored Procedures
62. What is a view in SQL?
A view is a virtual table based on the result of a stored SELECT query. It doesn't store data itself (unless it's a materialized view) but simplifies complex queries and can restrict access to specific columns or rows.
CREATE VIEW HighEarners AS
SELECT emp_name, salary FROM Employees WHERE salary > 50000;
63. What is a materialized view?
A materialized view stores the actual query result physically on disk and needs to be refreshed periodically. It trades some data freshness for much faster read performance, which is useful for expensive aggregate queries.
64. What is an index in SQL?
An index is a database object that speeds up data retrieval by creating a fast lookup structure, similar to a book's index, at the cost of extra storage and slower writes.
65. What is the difference between a clustered and a non-clustered index?
A clustered index determines the physical order of data in the table, and a table can have only one. A non-clustered index is a separate structure that points back to the actual data, and a table can have several.
66. When should you avoid creating too many indexes?
Indexes speed up SELECT queries but slow down INSERT, UPDATE, and DELETE operations because the index has to be updated too. On tables with heavy write activity, over-indexing can hurt overall performance.
67. What is a stored procedure?
A stored procedure is a precompiled collection of SQL statements saved in the database that can be executed by calling its name, often with input and output parameters.
CREATE PROCEDURE GetEmployeesByDept (IN deptId INT)
BEGIN
SELECT * FROM Employees WHERE dept_id = deptId;
END;
68. What is the difference between a stored procedure and a function?
A stored procedure may or may not return a value and can perform actions like INSERT or UPDATE; it's called using CALL or EXEC. A function must return a single value and can typically be used directly inside a SELECT statement.
69. What is a trigger in SQL?
A trigger is a block of SQL code that runs automatically in response to a specific event — such as INSERT, UPDATE, or DELETE — on a table.
CREATE TRIGGER trg_salary_check
BEFORE INSERT ON Employees
FOR EACH ROW
BEGIN
IF NEW.salary < 0 THEN
SET NEW.salary = 0;
END IF;
END;
70. What are the advantages and risks of using triggers?
Triggers enforce business rules automatically and keep related tables in sync without relying on application code. The risk is that overusing them can make behavior harder to trace, since changes happen silently in the background and can slow down write operations.
Normalization and Denormalization
71. What is normalization?
Normalization is the process of organizing tables to reduce data redundancy and improve data integrity, typically by breaking large tables into smaller, related ones.
72. What are the common normal forms?
- 1NF: Eliminates repeating groups; every column holds atomic values.
- 2NF: Meets 1NF and removes partial dependency on a composite key.
- 3NF: Meets 2NF and removes transitive dependency, so non-key columns depend only on the primary key.
- BCNF: A stricter version of 3NF that handles certain edge cases involving overlapping candidate keys.
73. What is denormalization, and why would you use it?
Denormalization intentionally introduces some redundancy by combining tables, usually to improve read performance in reporting or analytics systems where join-heavy queries become a bottleneck.
74. What's the trade-off between normalization and denormalization?
Normalization reduces redundancy and keeps data consistent but often requires more joins, which can slow down read-heavy queries. Denormalization speeds up reads but increases storage and the risk of data inconsistency, since the same information may exist in multiple places.
75. Give a practical example of when denormalization makes sense.
A reporting dashboard that aggregates millions of rows every few seconds often performs better against a denormalized, flattened table than against a fully normalized schema requiring five or six joins per query.
Transactions, ACID Properties, Locks, and Concurrency
76. What is a transaction in SQL?
A transaction is a sequence of one or more SQL operations executed as a single logical unit of work — either all of them succeed, or none of them do.
77. What are the ACID properties?
- Atomicity: All operations in a transaction complete, or none do.
- Consistency: A transaction moves the database from one valid state to another, respecting all rules and constraints.
- Isolation: Concurrent transactions don't interfere with each other's intermediate states.
- Durability: Once committed, changes persist even after a system failure.
78. What is the difference between COMMIT and ROLLBACK?
COMMIT permanently saves all changes made during the current transaction. ROLLBACK undoes all changes made since the last COMMIT (or SAVEPOINT), restoring the previous state.
79. What is a deadlock?
A deadlock happens when two or more transactions each hold a lock the other needs, and neither can proceed. Most database systems automatically detect deadlocks and roll back one of the transactions to break the cycle.
80. What are the common transaction isolation levels?
| Isolation Level | Dirty Read | Non-Repeatable Read | Phantom Read |
|---|---|---|---|
| Read Uncommitted | Possible | Possible | Possible |
| Read Committed | Prevented | Possible | Possible |
| Repeatable Read | Prevented | Prevented | Possible |
| Serializable | Prevented | Prevented | Prevented |
81. What is the difference between optimistic and pessimistic locking?
Pessimistic locking assumes conflicts are likely and locks data as soon as it's read, blocking other transactions until it's released. Optimistic locking assumes conflicts are rare, lets transactions proceed without locking, and checks for conflicts only at commit time.
82. What is a dirty read?
A dirty read occurs when a transaction reads data that another transaction has changed but not yet committed. If that other transaction rolls back, the first transaction ends up having read data that never really existed.
83. What is concurrency control, and why does it matter?
Concurrency control is the set of mechanisms — locks, isolation levels, and versioning — that a database uses to let multiple transactions run at the same time without corrupting data or producing inconsistent results.
Window Functions and Ranking Functions
Window functions are a favorite topic in experienced-level SQL interview questions, especially for data analyst and data engineer roles.
84. What is a window function?
A window function performs a calculation across a set of rows related to the current row, defined by an OVER() clause, without collapsing the result into a single row the way GROUP BY does.
SELECT emp_name, dept_id, salary,
AVG(salary) OVER (PARTITION BY dept_id) AS dept_avg
FROM Employees;
85. What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER()? ROW_NUMBER() assigns a unique sequential number to each row, even for ties. RANK() gives tied rows the same rank but skips the next rank number(s). DENSE_RANK() also gives tied rows the same rank but doesn't skip any numbers afterward.
SELECT emp_name, salary,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
FROM Employees;
86. What does PARTITION BY do inside a window function?
PARTITION BY divides the result set into groups (partitions), and the window function is applied separately within each partition, similar in spirit to GROUP BY but without merging rows into a summary.
87. How would you find the second-highest salary using a window function?
SELECT emp_name, salary FROM (
SELECT emp_name, salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM Employees
) t
WHERE rnk = 2;
88. What is the LAG() and LEAD() function used for?
LAG() retrieves a value from a previous row, and LEAD() retrieves a value from a following row, within the same result set — commonly used for comparing a row to the one before or after it, like month-over-month growth.
89. What is the difference between a window function and an aggregate function used with GROUP BY?
An aggregate function with GROUP BY collapses multiple rows into one summary row per group. A window function keeps every individual row in the output while still letting you see aggregated values alongside it.
90. Can you use window functions in the WHERE clause directly?
No. Because window functions are evaluated after WHERE in the logical query order, you can't filter directly on them in the same query. You need to wrap the query in a subquery or CTE and filter in the outer query instead.
SQL Optimization, Query Performance Tuning, and Execution Plans
91. What is an execution plan?
An execution plan shows how the database engine intends to run a query — which indexes it will use, the join order, and the estimated cost of each step. Reading execution plans is one of the most practical skills for query tuning.
-- PostgreSQL / MySQL
EXPLAIN SELECT * FROM Employees WHERE dept_id = 10;
-- SQL Server
SET SHOWPLAN_ALL ON;
92. What are common causes of slow SQL queries?
Missing or unused indexes, SELECT * pulling unnecessary columns, functions applied to indexed columns in WHERE clauses, poorly written joins, outdated statistics, and fetching far more rows than the application actually needs.
93. How do you optimize a slow-running query?
Start by checking the execution plan for full table scans, add indexes on columns used in WHERE, JOIN, and ORDER BY clauses, avoid SELECT *, rewrite correlated subqueries as joins where possible, and make sure table statistics are up to date.
94. What is query caching, and does it always help?
Query caching stores the result of a query so repeated identical requests can be served faster without re-executing the query. It helps for read-heavy, rarely changing data, but can add overhead or serve stale results on tables that update frequently.
95. What is the N+1 query problem?
The N+1 problem happens when an application runs one query to fetch a list of records, then runs a separate query for each record to fetch related data — resulting in N+1 total queries instead of one efficient join or batched query.
96. What is the difference between a full table scan and an index scan?
A full table scan reads every row in a table to find matches, which is slow on large tables. An index scan uses an index to jump directly to relevant rows, which is much faster when the index matches the query's filter conditions.
Database Security Interview Questions
97. What is SQL injection, and how do you prevent it?
SQL injection is an attack where malicious SQL code is inserted into an input field and executed by the database. It's prevented mainly by using parameterized queries or prepared statements instead of concatenating raw user input into SQL strings.
98. What is the principle of least privilege in database security?
It means giving each user or application account only the minimum permissions needed to do its job — for example, a reporting tool should have read-only access, not the ability to DROP tables.
99. What is the difference between authentication and authorization in a database context?
Authentication verifies who a user is, typically through a username and password. Authorization determines what that authenticated user is allowed to do, such as which tables they can read or modify.
100. What is data encryption at rest versus in transit?
Encryption at rest protects data stored on disk, so it stays unreadable if the storage is accessed directly. Encryption in transit (typically via TLS/SSL) protects data as it moves between the application and the database server, so it can't be intercepted on the network.
MySQL vs PostgreSQL vs SQL Server vs Oracle: Key Syntax Differences
Interviewers sometimes ask about database-specific syntax, especially if the job description names a specific RDBMS. Here's a quick comparison of common differences.
| Feature | MySQL | PostgreSQL | SQL Server | Oracle |
|---|---|---|---|---|
| Limit rows | LIMIT 10 | LIMIT 10 | TOP 10 or OFFSET/FETCH | FETCH FIRST 10 ROWS ONLY |
| Auto-increment | AUTO_INCREMENT | SERIAL / GENERATED AS IDENTITY | IDENTITY(1,1) | GENERATED AS IDENTITY / sequences |
| String concatenation | CONCAT(a, b) | `a | borCONCAT()` | |
| FULL OUTER JOIN | Not supported natively | Supported | Supported | Supported |
| Recursive CTE keyword | WITH RECURSIVE | WITH RECURSIVE | WITH (recursive by default) | WITH + CONNECT BY alternative |
| Current date/time | NOW() | NOW() / CURRENT_TIMESTAMP | GETDATE() | SYSDATE |
Knowing these differences matters more for experienced roles, but even freshers benefit from being aware that "standard SQL" still has vendor-specific quirks in practice.
Practical SQL Coding Exercises for Interview Practice
Reading through SQL interview questions only gets you so far — writing queries under time pressure is a different skill. Try these on the sample tables above before checking a solution:
- Write a query to find the top 3 highest-paid employees in each department.
- Find departments that have an average salary above the company-wide average salary.
- Write a query to identify duplicate rows in a table based on a specific column.
- Find employees who earn more than their manager.
- Write a recursive query to display the full reporting chain for a given employee.
- Find the second-highest salary in each department without using LIMIT or TOP.
- Write a query that pivots department-wise salary totals into columns instead of rows.
If you want instant feedback instead of guessing whether your query is right, HelloEngineers has practice problems modeled closely on real interview rounds, along with a community where you can compare your solution approach with other engineers preparing for similar interviews.
Company Career Pages, Resume, and Interview Tips
Knowing SQL is half the job. Getting through the actual hiring process is the other half. Here's what tends to matter beyond the technical round.
Making the Most of Company Career Pages
Most mid-size and large companies post SQL-related openings — data analyst, backend developer, database administrator, BI engineer — directly on their own career pages before or alongside job boards. A few habits help here:
- Check company career pages weekly rather than relying only on job board alerts, since some roles get filled internally before they're widely advertised.
- Read the actual job description carefully for the specific database mentioned (PostgreSQL vs SQL Server vs Oracle) and tailor your prep accordingly.
- Set up alerts on career pages of 8–10 target companies instead of applying broadly and generically everywhere.
- Note recurring keywords across postings — if "window functions" or "query optimization" shows up repeatedly, that's a strong signal for what to prioritize in prep.
Resume Tips for SQL Roles
- List specific SQL skills instead of just writing "SQL" — mention joins, window functions, query optimization, or stored procedures if you've genuinely used them.
- Quantify impact where possible: "Optimized a reporting query, reducing runtime from 40s to 3s" is far stronger than "Wrote SQL queries."
- Name the actual databases you've worked with (MySQL, PostgreSQL, SQL Server, Oracle) rather than a vague "databases" line.
- Keep project descriptions focused on outcomes — what the query or database change actually enabled — not just a list of tables you touched.
Interview Tips That Actually Help
- Talk through your thought process while writing a query, even if you're unsure. Interviewers usually care more about reasoning than a perfect first attempt.
- If a question is ambiguous (which is common with SQL interview questions), ask a clarifying question before writing code — it shows you think about edge cases.
- Practice writing SQL without autocomplete at least a few times before the interview, since many rounds still happen on a whiteboard or plain text editor.
- When asked to optimize a query, mention indexes, execution plans, and avoiding SELECT * — these are the details interviewers listen for.
- Don't just memorize answers to common SQL interview questions; be ready to explain the "why" behind each one, since follow-up questions are common.
Common Application Mistakes to Avoid
- Applying with a generic resume that doesn't mention the specific SQL dialect or tools listed in the job posting.
- Skipping the practical, hands-on prep and only reading theory — most interviews include at least one live query-writing exercise.
- Not asking about the team's actual tech stack (which RDBMS, ORM, or BI tools they use) before or during the interview.
- Ignoring behavioral prep entirely — SQL interview questions are usually just one part of a broader interview loop that also checks communication and problem-solving.
- Waiting until the night before to practice recursive queries, window functions, or execution plans, which are exactly the topics that need repetition to feel natural.
Frequently Asked Questions (FAQs)
1. How many SQL interview questions should I prepare before an interview? There's no fixed number, but working through 80–100 well-chosen SQL interview questions across all major topics — joins, subqueries, CTEs, window functions, and optimization — gives most candidates solid coverage for both fresher and experienced-level interviews.
2. Are SQL interview questions different for freshers and experienced professionals? Yes. Freshers are usually tested on basics — SELECT, joins, constraints, and simple aggregate functions. Experienced professionals are expected to go deeper into query optimization, execution plans, transactions, isolation levels, and system design involving databases.
3. Which SQL topics are asked most frequently in interviews? Joins, GROUP BY with HAVING, subqueries, window functions, and normalization show up in almost every SQL interview, regardless of company or seniority level.
4. Do I need to know all four databases — MySQL, PostgreSQL, SQL Server, and Oracle? No. Focus on the database mentioned in the job description. Core SQL concepts transfer across all of them; only the syntax for things like pagination or auto-increment tends to differ.
5. How important are window functions in SQL interviews? Very important for data analyst, data engineer, and BI roles. Ranking functions like RANK(), DENSE_RANK(), and ROW_NUMBER() are asked frequently enough that they deserve dedicated practice time.
6. What is the best way to practice SQL before an interview? Practice writing queries by hand against sample datasets, then check your logic against a working database. Platforms like HelloEngineers are useful here since they combine practice problems with peer discussion, so you're not just guessing whether your answer is correct.
7. Is it necessary to memorize SQL syntax exactly? Not word for word, but you should be comfortable enough to write correct, working queries without heavy autocomplete support, since many interviews still involve live coding.
8. What's a good way to explain query optimization in an interview? Walk through your process: check the execution plan, look for full table scans, verify indexes exist on filtered and joined columns, avoid SELECT *, and confirm statistics are current. Interviewers want to see a process, not just a memorized answer.
9. Are stored procedures and triggers commonly asked about? Yes, especially for backend and database administrator roles. Even if you don't write them often, you should be able to explain what they are, when to use them, and their trade-offs.
10. How do I explain ACID properties clearly in an interview? Use a simple example, like a bank transfer: atomicity ensures both the debit and credit happen or neither does; consistency ensures balances stay valid; isolation ensures concurrent transfers don't interfere; durability ensures the transfer survives a crash once committed.
11. What's the difference between a technical SQL round and a case-study round? A technical round usually involves writing specific queries against given tables. A case-study round might ask you to design a schema, discuss normalization trade-offs, or explain how you'd optimize a slow-performing system end to end.
12. Should I learn NoSQL as well, or focus only on SQL? For most SQL-focused roles, mastering SQL well is enough. Some job postings do mention NoSQL familiarity as a bonus, so check the specific listing on the company's career page before deciding how much time to invest there.
13. How long does it typically take to prepare for SQL interviews? It varies by starting point, but most candidates with some SQL background can get interview-ready in 2–4 weeks of focused daily practice, especially when combining question review with hands-on query writing.
14. What should I do if I get stuck on a query during a live interview? Say your thinking out loud, break the problem into smaller steps (filter first, then group, then join), and don't stay silent for too long. Interviewers generally give more credit for a structured approach than a perfect but silent answer.
15. Do companies ask about database security in SQL interviews? For backend and DBA roles, yes — SQL injection prevention, least-privilege access, and encryption basics come up fairly often. For analyst-focused roles, it's asked less frequently but is still worth knowing at a conceptual level.
16. Is it worth learning execution plans in depth? For anything beyond entry-level roles, yes. Being able to read an execution plan and explain why a query is slow is one of the clearest signals of real, hands-on SQL experience.
Final Thoughts
SQL interview questions can feel endless when you're studying from scattered notes, but the core topics repeat far more than they seem to at first — joins, subqueries, aggregate functions, window functions, transactions, and optimization cover the vast majority of what actually gets asked. Work through these 100 questions a few times, write the queries yourself instead of just reading the answers, and practice explaining your reasoning out loud.
If you want structured practice alongside other candidates preparing for the same kind of interviews, HelloEngineers is worth checking out — it's built around exactly this: practicing SQL problems, running mock interviews, and getting feedback from other engineers instead of preparing in isolation. Combine that hands-on practice with the resume and application tips above, and you'll walk into your next SQL interview a lot more prepared than most candidates in the room.





