VibrantMinds Logo
VibrantMinds
Back to Blog
Oct 12, 2026 👁️ 101 Views

SQL Interview Questions and Answers for Freshers (With Examples)

If you are preparing for a developer, tester or data analyst interview, SQL interview questions for freshers are almost guaranteed to appear. SQL is the language used to read and change data in relational databases, so it shows up in Java, Python, testing and data roles alike. This guide walks through the questions interviewers ask most often, with clear answers, runnable queries and the exact results, so you can practise instead of memorising.

Everything here uses one small set of sample tables, shown below, so you can create them in MySQL or PostgreSQL and run every query yourself. You will find basics, joins, aggregates, NULL handling, popular practical questions such as the second-highest salary, and concepts like indexes, normalisation and transactions. A short preparation plan and a list of common mistakes close the guide.

 

Quick answer: The SQL topics freshers are tested on most are SELECT with WHERE, ORDER BY and GROUP BY, joins (INNER and LEFT), aggregate functions, subqueries, NULL handling, and practical questions such as the nth-highest salary and duplicate records. Practise each on a real database, not just on paper.

 

Explore VibrantMinds

VibrantMinds Technologies is a Pune-based IT training and recruitment company. Learn more about its courses and placement process, or visit the candidate portal.

vibrantminds.in   |   candidates.vibrantminds.in

What SQL Topics Do Interviewers Ask Freshers?

 

The exact depth depends on the role, but fresher interviews usually cover the same core areas:

•       Basics: what SQL is, DDL and DML commands, keys and constraints, DELETE vs TRUNCATE vs DROP, WHERE vs HAVING.

•       Joins: INNER, LEFT, RIGHT, FULL and self joins.

•       Aggregation: COUNT, SUM, AVG, MIN, MAX with GROUP BY and HAVING.

•       Practical queries: second or nth-highest salary, duplicates, above-average values, top records per group.

•       Concepts: indexes, normalisation, transactions, views.

Java developers are often asked JDBC-related SQL, testers are asked to verify data in tables, and data analysts are asked deeper query and window-function questions. In every case, the fundamentals below are the foundation.

Sample Tables Used in This Guide

All examples use two tables: departments and employees. Each employee may belong to a department and may report to another employee (a manager), which lets us practise joins and self joins.


 

SQL (CREATE AND INSERT)

CREATE TABLE departments (

    dept_id   INT PRIMARY KEY,

    dept_name VARCHAR(50) NOT NULL

);

 

CREATE TABLE employees (

    emp_id     INT PRIMARY KEY,

    name       VARCHAR(50) NOT NULL,

    salary     INT,

    dept_id    INT,

    manager_id INT,

    FOREIGN KEY (dept_id)    REFERENCES departments(dept_id),

    FOREIGN KEY (manager_id) REFERENCES employees(emp_id)

);

 

INSERT INTO departments VALUES (1,'IT'), (2,'HR'), (3,'Finance');

 

INSERT INTO employees VALUES

(1, 'Asha',  60000, 1,    NULL),

(2, 'Rohan', 45000, 1,    1),

(3, 'Meera', 50000, 2,    1),

(4, 'Kabir', 45000, 1,    1),

(5, 'Neha',  55000, NULL, 3);

 

Note that Neha has no department, and the Finance department has no employees. Those two details make the join examples more interesting.

SQL Basics Interview Questions for Freshers

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

SQL (Structured Query Language) is the standard language for creating, reading, updating and deleting data in relational databases. MySQL, PostgreSQL, Oracle and SQL Server are database management systems that implement SQL, each with small dialect differences. In short: SQL is the language; MySQL is one of the systems that understands it.

Q2. What are DDL, DML, DCL and TCL commands?

•       DDL (Data Definition Language): defines structure. CREATE, ALTER, DROP, TRUNCATE.

•       DML (Data Manipulation Language): works with the data. INSERT, UPDATE, DELETE (and SELECT, which many people group here).

•       DCL (Data Control Language): controls access. GRANT, REVOKE.

•       TCL (Transaction Control Language): manages transactions. COMMIT, ROLLBACK, SAVEPOINT.

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

•       Primary key: uniquely identifies each row. A table has only one, and it cannot contain NULL.

•       Foreign key: a column that refers to the primary key of another table (or the same table), enforcing a relationship.

•       Unique key: ensures values in a column are not repeated. A table can have several, and most databases allow NULLs in them (rules vary slightly by database).

Q4. What are SQL constraints?

Constraints are rules that keep data valid. Common ones are NOT NULL (value required), UNIQUE (no duplicates), PRIMARY KEY, FOREIGN KEY, CHECK (value must satisfy a condition) and DEFAULT (value used when none is given).

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

•       DELETE removes selected rows (you can use WHERE) and is a DML command. The table structure stays.

•       TRUNCATE removes all rows quickly and cannot use WHERE. The table structure stays. Whether it can be rolled back depends on the database.

•       DROP removes the entire table, including its structure and data.

Q6. What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping. HAVING filters groups after GROUP BY, usually on aggregate values such as COUNT or SUM.

SQL

-- WHERE filters rows before grouping

SELECT dept_id, COUNT(*) AS total

FROM employees

WHERE salary > 45000

GROUP BY dept_id;

 

-- HAVING filters groups after grouping

SELECT dept_id, COUNT(*) AS total

FROM employees

GROUP BY dept_id

HAVING COUNT(*) > 1;     -- only dept_id 1 (three employees)

 

Q7. In what order does SQL execute a query?

You write SELECT first, but the database reads the query in a different logical order. Knowing this explains many common errors, such as why a column alias cannot be used inside WHERE.


Q8. What is the difference between CHAR and VARCHAR?

CHAR stores fixed-length text and pads shorter values; VARCHAR stores variable-length text and uses only the space needed. Use CHAR for values of a fixed size, such as country codes, and VARCHAR for names and descriptions.

SQL Joins Interview Questions and Answers

Q9. What is a join, and what are the types of joins?

A join combines rows from two or more tables based on a related column. The four standard types are INNER, LEFT, RIGHT and FULL OUTER joins.

 


 

Q10. What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only rows that match in both tables. LEFT JOIN returns all rows from the left table and the matching rows from the right, filling unmatched right-side columns with NULL.

SQL

-- INNER JOIN: Neha is excluded because she has no department

SELECT e.name, d.dept_name

FROM employees e

INNER JOIN departments d ON e.dept_id = d.dept_id;

-- Asha IT | Rohan IT | Meera HR | Kabir IT

 

-- LEFT JOIN: every employee appears; Neha gets NULL for dept_name

SELECT e.name, d.dept_name

FROM employees e

LEFT JOIN departments d ON e.dept_id = d.dept_id;

-- Asha IT | Rohan IT | Meera HR | Kabir IT | Neha NULL

Q11. What are RIGHT JOIN and FULL OUTER JOIN?

RIGHT JOIN returns all rows from the right table plus matches from the left. FULL OUTER JOIN returns all rows from both tables, matched where possible. MySQL does not support FULL OUTER JOIN directly; you can combine a LEFT JOIN and a RIGHT JOIN with UNION to get the same result.

SQL

-- RIGHT JOIN: Finance appears with NULL for the employee name

SELECT d.dept_name, e.name

FROM employees e

RIGHT JOIN departments d ON e.dept_id = d.dept_id;

Q12. What is a self join? Show employees with their managers.

A self join joins a table to itself, using different aliases. It is the standard way to handle hierarchies such as employee and manager.

SQL

SELECT e.name AS employee, m.name AS manager

FROM employees e

JOIN employees m ON e.manager_id = m.emp_id;

-- Rohan Asha | Meera Asha | Kabir Asha | Neha Meera

Q13. How do you find departments that have no employees?

Use a LEFT JOIN from departments to employees and keep the rows where the employee side is NULL.

SQL

SELECT d.dept_name

FROM departments d

LEFT JOIN employees e ON d.dept_id = e.dept_id

WHERE e.emp_id IS NULL;

-- Finance

Aggregate Functions, GROUP BY and NULL Questions

Q14. What are aggregate functions, and how does GROUP BY work?

Aggregate functions calculate a single value from many rows: COUNT, SUM, AVG, MIN and MAX. GROUP BY splits rows into groups so the aggregate runs once per group.

SQL

SELECT d.dept_name, COUNT(*) AS employees, AVG(e.salary) AS avg_salary

FROM employees e

JOIN departments d ON e.dept_id = d.dept_id

GROUP BY d.dept_name;

-- IT 3 | 50000   (60000 + 45000 + 45000) / 3

-- HR 1 | 50000

Q15. What is the difference between COUNT(*) and COUNT(column)?

COUNT(*) counts all rows. COUNT(column) counts only rows where that column is not NULL.

SQL

SELECT COUNT(*) AS all_rows, COUNT(dept_id) AS with_department

FROM employees;

-- 5 | 4   (Neha has a NULL dept_id)

Q16. What is NULL, and how do you handle it?

NULL means "unknown or missing." It is not the same as zero or an empty string. Any comparison with NULL using = returns unknown, so use IS NULL and IS NOT NULL. To replace NULL with a default value, use COALESCE.

SQL

SELECT name FROM employees WHERE dept_id IS NULL;      -- Neha

 

SELECT name, COALESCE(dept_id, 0) AS dept_id_or_zero

FROM employees;                                         -- Neha shows 0

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

UNION combines results and removes duplicate rows. UNION ALL keeps every row, including duplicates, and is usually faster because it skips the duplicate check.

SQL

SELECT salary FROM employees WHERE dept_id = 1

UNION

SELECT salary FROM employees WHERE dept_id = 2;

-- 60000 | 45000 | 50000  (duplicate 45000 removed)

-- With UNION ALL you would get 4 rows, including both 45000 values.

Q18. How do the LIKE operator and wildcards work?

LIKE matches text patterns. The percent sign (%) stands for any number of characters, and the underscore (_) stands for exactly one character. The three queries below match names that start with K, end with a, and have "oh" as the second and third letters.

SQL

SELECT name FROM employees WHERE name LIKE 'K%';    -- Kabir

SELECT name FROM employees WHERE name LIKE '%a';    -- Asha, Meera, Neha

SELECT name FROM employees WHERE name LIKE '_oh%';  -- Rohan

Popular SQL Query Interview Questions for Freshers

Q19. How do you find the second-highest salary?

This is the most repeated SQL question in fresher interviews. Know at least two approaches and be ready to explain the trade-offs.

SQL

-- 1. Subquery

SELECT MAX(salary) AS second_highest

FROM employees

WHERE salary < (SELECT MAX(salary) FROM employees);

 

-- 2. LIMIT and OFFSET (MySQL, PostgreSQL)

SELECT DISTINCT salary

FROM employees

ORDER BY salary DESC

LIMIT 1 OFFSET 1;

 

-- Result for both: 55000

Q20. How do you find the nth-highest salary using DENSE_RANK?

Window functions such as DENSE_RANK are available in MySQL 8 and later, PostgreSQL and SQL Server. DENSE_RANK handles ties without skipping numbers, which makes the nth-highest question easy to generalise.

SQL

SELECT salary

FROM (

    SELECT salary,

           DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk

    FROM employees

) ranked

WHERE rnk = 2;      -- change 2 to any n

-- 55000

Q21. How do you find employees who earn more than the average salary?

SQL

SELECT name, salary

FROM employees

WHERE salary > (SELECT AVG(salary) FROM employees);

-- The average is 51000, so: Asha 60000 | Neha 55000

Q22. How do you find duplicate values in a column?

Group by the column and keep the groups that appear more than once.

SQL

SELECT salary, COUNT(*) AS occurrences

FROM employees

GROUP BY salary

HAVING COUNT(*) > 1;

-- 45000 | 2

Q23. How do you find the highest salary in each department?

SQL

SELECT d.dept_name, MAX(e.salary) AS highest_salary

FROM employees e

JOIN departments d ON e.dept_id = d.dept_id

GROUP BY d.dept_name;

-- IT 60000 | HR 50000

Q24. How do you find employees who earn more than their manager?

SQL

SELECT e.name

FROM employees e

JOIN employees m ON e.manager_id = m.emp_id

WHERE e.salary > m.salary;

-- Neha earns 55000 and her manager Meera earns 50000

Q25. How does the CASE expression work?

CASE adds if-then logic inside a query, which is useful for labelling or categorising values.

SQL

SELECT name, salary,

       CASE WHEN salary >= 55000 THEN 'High'

            WHEN salary >= 50000 THEN 'Medium'

            ELSE 'Entry'

       END AS band

FROM employees;

Q26. What is a subquery, and how is it different from a join?

A subquery is a query nested inside another query. A join combines tables side by side. Many problems can be solved either way: joins are often easier to read and optimise when you need columns from both tables, while subqueries are convenient for filters such as "salary above the average." Be ready to solve the same problem both ways.

SQL Concepts: Indexes, Normalisation, Transactions and Views

Q27. What is an index, and when should you use one?

An index is a data structure that helps the database find rows faster, like the index of a book. It speeds up reads that filter or join on the indexed column, but it takes extra storage and slows down inserts and updates, because the index must be maintained. Index columns that appear often in WHERE and JOIN conditions, not every column.

SQL

CREATE INDEX idx_emp_dept ON employees(dept_id);

Q28. What is normalisation?

Normalisation organises data to reduce redundancy and avoid update problems. In plain terms:

•       1NF: each column holds a single value, with no repeating groups.

•       2NF: in 1NF, and every non-key column depends on the whole primary key, not just part of it.

•       3NF: in 2NF, and non-key columns depend only on the key, not on other non-key columns.

Example: instead of storing the department name in every employee row, store it once in departments and refer to it by dept_id.

Q29. What are transactions and ACID properties?

A transaction is a group of operations that must succeed or fail together, such as transferring money between two accounts. ACID describes the guarantees: Atomicity (all or nothing), Consistency (data stays valid), Isolation (concurrent transactions do not interfere improperly) and Durability (committed data survives failures).

SQL (MYSQL SYNTAX)

START TRANSACTION;

UPDATE accounts SET balance = balance - 500 WHERE acc_id = 1;

UPDATE accounts SET balance = balance + 500 WHERE acc_id = 2;

COMMIT;       -- use ROLLBACK; to undo both changes instead

In PostgreSQL, the equivalent starts with BEGIN.

Q30. What are a view, a stored procedure and a trigger?

•       View: a saved query that behaves like a virtual table.

•       Stored procedure: a named block of SQL stored in the database that you can run with parameters.

•       Trigger: code that runs automatically when an INSERT, UPDATE or DELETE happens on a table.

SQL

CREATE VIEW it_staff AS

SELECT emp_id, name FROM employees WHERE dept_id = 1;

How to Prepare for SQL Interviews in 7 Days

 

1.     Day 1: install MySQL or PostgreSQL, create the sample tables and practise SELECT, WHERE, ORDER BY.

2.     Day 2: practise GROUP BY, HAVING and the aggregate functions.

3.     Day 3: practise INNER, LEFT and self joins until you can write them from memory.

4.     Day 4: solve subquery questions: second-highest, above average, duplicates.

5.     Day 5: learn DENSE_RANK and CASE, and revisit NULL handling.

6.     Day 6: revise indexes, normalisation, transactions and constraints. Explain each aloud.

7.     Day 7: do a timed mock round: ten queries from scratch, then review mistakes.

Common Mistakes Freshers Make in SQL Interviews

 

1.     Memorising queries without understanding. A small twist in the question breaks the memorised answer.

2.     Using = to compare with NULL instead of IS NULL.

3.     Confusing WHERE and HAVING, or using an alias inside WHERE.

4.     Forgetting join conditions, which creates a huge accidental cross product.

5.     Never running queries. Practise on a real database so you see the actual results and errors.

6.     Not explaining your approach. Say what you are doing and why while you write.

About VibrantMinds Technologies

VibrantMinds Technologies Pvt. Ltd. is a Pune-based IT training and recruitment company. It operates as a talent ecosystem that connects candidates, colleges and companies, with 1900+ partner colleges and 600+ hiring companies in its network.

Visit vibrantminds.in to learn about the company, or open the candidate portal at candidates.vibrantminds.in.

These are the VibrantMinds courses:

Course

Duration

Key topics

Full Stack Java Development

4–6 months

Core Java, OOP, SQL and JDBC, web fundamentals, backend frameworks, front-end basics, projects

Software Testing (Manual + Automation)

2–5 months

Testing fundamentals, test cases, bug reporting, SDLC and STLC, automation basics, interview preparation

Core Java

1–2 months

Syntax, OOP, strings, collections, exception handling, practice programs

Python & Data Science

2–4 months

Python basics, data handling, analysis libraries, visualisation, introduction to machine learning

How VibrantMinds Helps You Prepare for SQL and Technical Interviews

SQL is a core part of the Full Stack Java Development course, where SQL and JDBC sit alongside Core Java, OOP, web fundamentals, backend frameworks and projects. That combination matters, because interviewers often connect the two: they ask a SQL question, then ask how you would run it from Java using JDBC. For Python & Data Science and Software Testing learners, SQL is a natural skill to add; ask the team how SQL practice fits into the batch you are considering.

The VibrantMinds 6-step placement pipeline then connects your preparation to real openings:

1.     Requirement Mapping: understanding what hiring companies need, so your preparation matches real requirements.

2.     Candidate Sourcing: identifying candidates who fit those openings.

3.     Screening & Assessment: checking skills and readiness, so gaps surface before a real interview.

4.     Drive Coordination: organising recruitment drives with hiring companies.

5.     Interview Support: preparing candidates for interview rounds, including technical rounds like this one.

6.     Onboarding Follow-up: staying in touch after selection to support the joining process.


VibrantMinds tip

Not sure which course matches your target role? Talk to the team, and ask which projects, assessments and interview practice are part of the current batch.

Visit vibrantminds.in   |   Candidate portal

Real Outcomes: What Past Students Say

Feedback shared by past students mentions placements with companies such as Aress Software and Education Technologies, Saama Technologies and Three M Software. To be clear and fair: outcomes vary from person to person, depending on skills, effort, attendance, interview performance and company requirements. Nothing here is a guarantee of a job, so please confirm details directly with the VibrantMinds team before you decide.

Connect With VibrantMinds Technologies

Address: Viva Academy Building, Warje, Pune, Maharashtra 411052

Phone: +91 95035 79517

Email: support@vibrantmindstech.com

Website: https://vibrantminds.in/

Candidate portal: https://candidates.vibrantminds.in/

Join the Job-Update WhatsApp Groups

Group 1: https://chat.whatsapp.com/CUCS1derlmTFee2c9dyUHd

Group 2: https://chat.whatsapp.com/FvMf1fGYQYnHppQ8AwFX40

Group 3: https://chat.whatsapp.com/I7RNnGMkb2L8S8HibdyWpQ

 

Caution: never pay anyone to apply for a job or to get shortlisted. If someone asks for money in exchange for a job opportunity, stop and verify directly with the company or the VibrantMinds team.

Frequently Asked Questions About SQL Interviews

Which SQL database should a fresher learn first?

MySQL or PostgreSQL are both good starting points. SQL concepts transfer between databases, so learning joins, grouping and subqueries well matters more than the exact system. Check which one your target companies mention.

How much SQL is enough for a fresher interview?

For most fresher roles, being comfortable with joins, GROUP BY and HAVING, subqueries, NULL handling and the practical questions in this guide covers the common ground. Data analyst roles usually go deeper, including window functions.

Are window functions asked to freshers?

Sometimes, especially for data roles and in questions like nth-highest salary. Learn ROW_NUMBER, RANK and DENSE_RANK at a basic level. Check that your database version supports them.

Do I need to memorise SQL queries?

No. Understand the pattern behind each query, such as grouping then filtering with HAVING, or joining a table to itself, and practise on a real database until you can write them yourself.

What is the difference between SQL and NoSQL?

SQL databases store data in structured tables with relationships, and use SQL for queries. NoSQL databases use other models such as documents or key-value pairs. Freshers are usually tested on SQL first.

How can I practise SQL for free?

Install MySQL or PostgreSQL on your computer and create practice tables, as in this guide. Many free online platforms also offer practice problems and sample databases.

How long does it take to learn SQL basics?

Basic querying can be learned in a few weeks of regular practice, but the time varies by person. Joins, subqueries and practical questions take more repeated practice than syntax.

Why do testers and Java developers need SQL?

Testers verify that data is saved correctly behind the screen, and Java developers store and read application data through JDBC or frameworks. Both are regularly asked SQL questions in interviews.

Final Thoughts: Practise Queries, Don't Just Read Them

SQL interviews reward practice more than theory. Create the sample tables, run every query in this guide, change the data, and predict the output before you press Enter. Once joins, grouping and subqueries feel natural, most fresher SQL questions become variations on patterns you already know.

If you would like structured training that includes SQL and JDBC, or help planning which skills to build for your target role, the VibrantMinds team is happy to talk it through.

Share this article:
WhatsApp LinkedIn Facebook Twitter

Launch Your IT Career

Learn Python, Java, testing, or data analytics with 100% placement assurance.

Explore Courses →

Join Live Placement Drives

Direct hiring access for top IT and multinational corporations.

Register Today →
Chat with us!