Interview prep

Top 20 SQL Interview Questions for Freshers

Top 20 SQL interview questions for freshers with short answers, tested queries, results and follow-up traps, plus a quick SQL MCQ set for viva practice.

20QUESTIONSQWHERE vs HAVING?AWHERE filters rows, HAVING groups
  • Interview
  • SQL
  • Data Analytics
  • Freshers

Quick answer: The most useful SQL interview questions for freshers cover keys, NULL, WHERE vs HAVING, joins, GROUP BY, subqueries, CTEs, window functions, duplicates, second highest salary, normalisation, indexes, views and transactions. Learn a 30-second answer for each, then practise writing the query by hand on a small table and explaining the result.

SQL interview questions are asked for data analyst, developer, testing and support roles. For freshers, interviewers usually check three things: do you know the meaning, can you write the query, and can you explain why it works?

This page has 20 questions. Each one starts with a 30-second answer that you can say aloud. Queries come with results from the same two small tables, so you can check them by hand. They were run in SQLite and use common SQL that also works in MySQL 8 and PostgreSQL, unless noted.

The practice tables

departments

dept_id dept_name
1 Tech
2 Sales
3 HR

employees

emp_id name dept_id salary manager_id
1 Asha 1 90000 NULL
2 Ravi 1 70000 1
3 Meena 2 60000 1
4 Kiran 2 50000 3
5 Divya 1 70000 1
6 Suresh NULL 40000 3

Notice the special cases: Suresh has no department, HR has no employees, Asha has no manager, and two people earn 70000. Good practice data always has cases like these.

SQL interview questions on basics and keys

Q1. What is SQL, and how is it different from MySQL?

30-second answer: SQL is the language used to work with data in relational databases. MySQL is a database system that understands SQL. PostgreSQL, Oracle and SQL Server are other systems that use SQL with small differences.

Think of SQL as the language and MySQL as one product that speaks it.

SQL commands are often grouped like this:

Group Purpose Examples
DDL Define structure CREATE, ALTER, DROP, TRUNCATE
DML Change data INSERT, UPDATE, DELETE
DQL Read data SELECT
DCL Control access GRANT, REVOKE
TCL Control transactions COMMIT, ROLLBACK

Q2. What is the difference between a primary key, a unique key and a foreign key?

30-second answer: A primary key identifies each row, so it is unique and cannot be NULL. A unique key stops repeated values but usually allows NULL. A foreign key points to a key in another table and keeps the link valid.

emp_id is a primary key. An email column could be unique. employees.dept_id is a foreign key to departments.dept_id, so the database can refuse a department that does not exist.

Interview note: "Can a table have two primary keys?" No. It can have only one primary key, but that key may use two or more columns. This is called a composite key.

Q3. What is NULL, and why does = NULL not work?

30-second answer: NULL means a missing or unknown value. It is not zero and not an empty string. Comparing anything with NULL using = gives unknown, so you must use IS NULL or IS NOT NULL.

SELECT name FROM employees WHERE dept_id IS NULL;
name
Suresh

With dept_id = NULL, the query would return no rows.

Q4. What is the difference between DELETE, TRUNCATE and DROP?

30-second answer: DELETE removes selected rows or all rows. TRUNCATE removes all rows but keeps the table. DROP removes the table itself, along with its data.

Command Can use WHERE? Table remains?
DELETE Yes Yes
TRUNCATE No Yes
DROP No No

TRUNCATE is usually faster than deleting every row.

Common mistake: Saying "TRUNCATE can never be rolled back". It depends on the database. MySQL commits it automatically. PostgreSQL lets you roll it back inside a transaction. SQLite has no TRUNCATE command.

Q5. What are constraints in SQL?

30-second answer: Constraints are rules that protect data. Common ones are NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK and DEFAULT. The database rejects a change that breaks a rule.

CREATE TABLE courses (
    course_id INTEGER PRIMARY KEY,
    title     VARCHAR(80) NOT NULL UNIQUE,
    seats     INTEGER DEFAULT 27 CHECK (seats > 0)
);

DEFAULT is slightly different. It fills a value when you do not give one. In the example, seats become 27 if you leave them out.

A good answer gives a reason: an app may have bugs, but the database still stops bad data.

Questions on filtering and grouping

Q6. What is the order in which a SELECT query is processed?

30-second answer: The logical order is FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and then LIMIT. We write SELECT first, but it is processed later.

This explains why you usually cannot use a SELECT alias inside WHERE: the alias does not exist at that stage. You can use it in ORDER BY, which comes later. Some databases relax these rules, and the database may run the work in another way as long as the result is the same.

Q7. What is the difference between WHERE and HAVING?

30-second answer: WHERE filters rows before grouping. HAVING filters groups after grouping. Use HAVING for conditions on COUNT, SUM, AVG and other aggregates.

SELECT dept_id, COUNT(*) AS people
FROM employees
WHERE salary >= 50000
GROUP BY dept_id
HAVING COUNT(*) >= 2
ORDER BY dept_id;
dept_id people
1 3
2 2

First, WHERE removes Suresh because of his salary. The remaining people are grouped, and groups with two or more stay. Our GROUP BY and HAVING questions give more practice.

Q8. What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?

30-second answer: COUNT(*) counts rows. COUNT(column) counts rows where that column is not NULL. COUNT(DISTINCT column) counts different non-NULL values.

SELECT COUNT(*) AS all_rows,
       COUNT(dept_id) AS with_dept,
       COUNT(DISTINCT dept_id) AS different_depts
FROM employees;
all_rows with_dept different_depts
6 5 2

Six employees, five with a department, and two different departments in use.

Q9. What is the difference between UNION and UNION ALL?

30-second answer: Both stack the results of two queries. UNION removes duplicate rows. UNION ALL keeps every row and is usually faster because it does not check for duplicates.

SELECT dept_id FROM departments
UNION
SELECT dept_id FROM employees WHERE dept_id IS NOT NULL
ORDER BY dept_id;
dept_id
1
2
3

With UNION ALL, this would give eight rows: three from departments and five from employees. Both queries must have the same number of columns, with matching types.

Pro tip: If you know there are no duplicates, or you want to keep them, choose UNION ALL. Then explain your reason. Interviewers value the reason.

Q10. How do you show a result based on a condition?

30-second answer: Use CASE. It checks conditions from top to bottom and returns the value for the first true one. ELSE gives a value when none is true.

SELECT name,
       CASE WHEN salary >= 80000 THEN 'High'
            WHEN salary >= 60000 THEN 'Medium'
            ELSE 'Entry'
       END AS pay_band
FROM employees
ORDER BY emp_id;
name pay_band
Asha High
Ravi Medium
Meena Medium
Kiran Entry
Divya Medium
Suresh Entry

If you leave out ELSE and nothing matches, the result is NULL.

Questions on joins and subqueries

Q11. What are the types of joins?

30-second answer: INNER JOIN returns matching rows. LEFT JOIN keeps all left rows and adds matches. RIGHT JOIN keeps all right rows. FULL OUTER JOIN keeps all rows from both sides. CROSS JOIN makes every pair.

Join on our tables Rows Reason
employees INNER JOIN departments 5 Suresh has no match
employees LEFT JOIN departments 6 Suresh stays with NULL
employees RIGHT JOIN departments 6 HR stays with NULL
employees FULL OUTER JOIN departments 7 Both Suresh and HR stay
employees CROSS JOIN departments 18 6 multiplied by 3

MySQL does not have FULL OUTER JOIN. You can combine a left join and a right join with UNION, or use UNION ALL with care to avoid repeats. Read SQL joins explained for diagrams.

Q12. How do you find departments with no employees?

30-second answer: Use a LEFT JOIN from departments to employees and keep the rows where the employee key is NULL. NOT EXISTS is another good answer.

SELECT d.dept_name
FROM departments d
LEFT JOIN employees e ON e.dept_id = d.dept_id
WHERE e.emp_id IS NULL;
dept_name
HR

Interview note: A follow-up is "Why not NOT IN?" If the subquery returns a NULL, NOT IN can return no rows. Our employees table has a NULL department, so that trap would catch you here.

Q13. What is a self join? Show each employee with the manager's name.

30-second answer: A self join joins a table to itself. You use two aliases, as if there were two copies. Here, one copy is for the employee and the other is for the manager.

SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.emp_id = e.manager_id
ORDER BY e.emp_id;
employee manager
Asha NULL
Ravi Asha
Meena Asha
Kiran Meena
Divya Asha
Suresh Meena

An inner join would remove Asha because she has no manager.

Q14. What is the difference between a subquery and a correlated subquery?

30-second answer: A normal subquery can run on its own. A correlated subquery uses a value from the outer query, so it depends on the current outer row.

SELECT e.name, e.salary
FROM employees e
WHERE e.salary > (
    SELECT AVG(x.salary)
    FROM employees x
    WHERE x.dept_id = e.dept_id
)
ORDER BY e.name;
name salary
Asha 90000
Meena 60000

Tech's average is about 76667, so only Asha is above it. The Sales average is 55000, so Meena is above it. Suresh's department is NULL, so his subquery finds no rows and he is not shown.

Suresh also shows how NULL affects a match: NULL does not equal NULL in this comparison.

Q15. How do you find the second highest salary?

30-second answer: Find the maximum salary that is smaller than the highest salary. This works with ties because it looks for the next distinct value.

SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
second_highest
70000

If you need the people too, use DENSE_RANK() and keep rank 2. In our table, this gives Ravi and Divya. See other ways to find the second highest salary in SQL.

Questions on CTEs and window functions

Q16. What is the difference between ROW_NUMBER, RANK and DENSE_RANK?

30-second answer: ROW_NUMBER gives every row a different number. RANK gives ties the same number and then skips. DENSE_RANK gives ties the same number without skipping.

SELECT name, salary,
       ROW_NUMBER() OVER (ORDER BY salary DESC, emp_id) AS row_num,
       RANK()       OVER (ORDER BY salary DESC) AS rnk,
       DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees
ORDER BY salary DESC, emp_id;
name salary row_num rnk dense_rnk
Asha 90000 1 1 1
Ravi 70000 2 2 2
Divya 70000 3 2 2
Meena 60000 4 4 3
Kiran 50000 5 5 4
Suresh 40000 6 6 5

Look at Meena. RANK jumps to 4 because two people share 2. DENSE_RANK gives 3.

Interview note: "How is a window function different from GROUP BY?" GROUP BY joins rows into one row per group. A window function adds a value and keeps every row.

Q17. What is a CTE, and how do you use it to find duplicates?

30-second answer: A CTE, or common table expression, is a named result that exists for one statement. It starts with WITH and makes a long query easier to read.

This query finds salaries shared by more than one person:

WITH salary_counts AS (
    SELECT salary, COUNT(*) AS people
    FROM employees
    GROUP BY salary
)
SELECT salary, people
FROM salary_counts
WHERE people > 1;
salary people
70000 2

Shared salaries are fine, of course. In real work, you would group by a value that should be unique, such as email. Here WHERE works on people because the counting is already finished inside the CTE.

To remove duplicate rows, first decide which row to keep, such as the smallest ID. Check with SELECT before you run DELETE.

Questions on design and performance

Q18. What is normalisation? Explain 1NF, 2NF and 3NF.

30-second answer: Normalisation means arranging tables to reduce repeated data and update problems. 1NF has single values, 2NF removes partial dependency, and 3NF removes transitive dependency.

Form Simple rule Bad example
1NF One value in each cell phones = "901, 902"
2NF 1NF, and other columns depend on the whole key Student name in a table keyed by student and course
3NF 2NF, and other columns do not depend on each other Department name stored with each employee

If "Tech" is stored in 500 employee rows, a name change needs 500 updates. Keep it once in departments and store only dept_id.

Reports sometimes repeat data on purpose so that they are quicker to read. This is called denormalisation.

Q19. What is an index? What is the difference between an index and a view?

30-second answer: An index is a data structure that helps the database find rows faster. A view is a saved query that you can use like a table. An index helps speed; a normal view helps reuse, simplicity and access control.

CREATE INDEX idx_employees_dept ON employees (dept_id);

CREATE VIEW tech_team AS
SELECT emp_id, name
FROM employees
WHERE dept_id = 1;

Indexes are not free. They use storage and must be updated when data changes. So do not index every column. Choose columns that are often used to filter or join.

A normal view does not store its result; it runs the query when used. Some databases also have materialised views, which do store the result. The view above can hide salary if users get access to the view but not to the table.

Q20. What is a transaction? Explain ACID.

30-second answer: A transaction is a group of steps treated as one unit. Either all changes are saved or none are. ACID stands for atomicity, consistency, isolation and durability.

Letter Meaning in a money transfer
Atomicity Debit and credit both happen, or neither does
Consistency Database rules stay true, such as no negative balance
Isolation Two transfers do not mix up each other's data
Durability After commit, the change survives a crash
CREATE TABLE accounts (
    account_id INTEGER PRIMARY KEY,
    balance    INTEGER CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 5000), (2, 1000);

BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 500 WHERE account_id = 2;
COMMIT;

After this, the balances are 4500 and 1500. If the second update fails, the program should call ROLLBACK, so that the money is not lost. MySQL also accepts START TRANSACTION instead of BEGIN.

SQL MCQ and SQL viva questions: a quick check

Try each SQL MCQ without scrolling down to the answers.

  1. Which clause filters groups? (a) WHERE (b) HAVING (c) ORDER BY
  2. Which count ignores NULL? (a) COUNT(*) (b) COUNT(col) (c) both
  3. Which key links two tables? (a) Foreign (b) Unique (c) Candidate
  4. Which one keeps duplicates? (a) UNION (b) UNION ALL (c) DISTINCT
  5. Which is a DDL command? (a) UPDATE (b) ALTER (c) INSERT
  6. What is NULL = NULL? (a) True (b) False (c) Unknown
  7. For values 10, 10, 5 in descending order, what is the RANK of 5? (a) 2 (b) 3 (c) 1
  8. Which join gives all left rows? (a) INNER (b) LEFT (c) CROSS
  9. Tables of 4 and 5 rows have how many CROSS JOIN rows? (a) 9 (b) 20 (c) 5
  10. Which word saves a transaction? (a) SAVE (b) COMMIT (c) END IF

Answers: 1b, 2b, 3a, 4b, 5b, 6c, 7b, 8b, 9b, 10b.

For SQL viva questions, be ready to say these in one line each: candidate key, composite key, referential integrity, cardinality and the meaning of RDBMS. Add one example from your lab project to each.

How to prepare for SQL interview questions for freshers

  1. Days 1 and 2: make the two practice tables and run all the queries here.
  2. Days 3 and 4: change the data and predict the new results.
  3. Days 5 and 6: write the join, grouping and salary queries on paper.
  4. Day 7: answer all 20 questions aloud, with one minute for each.

Then study common SQL mistakes and real SQL business examples. For more practice, use our SQL questions for freshers.

The Data Analytics with AI course has a full SQL phase, mock interviews and 5+ interview opportunities through a 60+ company network, subject to the placement policy and eligibility. It does not promise a job. Our data analytics course guide explains the complete path.

Frequently asked questions

Which SQL topics are most important for freshers?

Focus on joins, GROUP BY with HAVING, NULL handling, subqueries, keys and the second highest salary query. Then add CTEs and window functions, especially for data analyst roles.

How do I prepare for SQL viva questions?

Prepare a one-line meaning and one small example for each term. Keys, normal forms, joins, DELETE vs TRUNCATE and ACID are common viva topics. Practise speaking the answers, not only reading them.

Are SQL MCQs asked in placement tests?

Some online tests include them. They often check NULL, joins, the order of clauses, COUNT and the result of a short query. Understanding the concept helps more than memorising options.

Should I write SQL in MySQL or PostgreSQL style in an interview?

Use the one you know and tell the interviewer. Core queries are the same in both. Mention any feature that differs, such as date functions or limits.

How many days are needed to prepare for SQL interviews?

If you know the basics, one to two weeks of daily query practice can be enough for revision. If you are new to SQL, give yourself about four to six weeks and build a small project.


Want to practise SQL answers with a trainer? Book a free demo class for the Data Analytics with AI course, at our Madhapur campus or live online.

Found this useful? Share it: LinkedIn Facebook WhatsApp

Written by

Siva Prasad Galaba

Staff Engineer & Founder, CodeBegun

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaching the next generation to code the way the industry actually works.

Back to all articles
Chat with us