SQL Interview Questions for Freshers (2026): 60 Questions and Answers

What SQL questions are asked to freshers? Interviewers usually ask the difference between DELETE, TRUNCATE and DROP, primary key vs foreign key, WHERE vs HAVING, INNER JOIN vs LEFT JOIN, GROUP BY with aggregate functions, subqueries, normalisation basics and then ask you to write queries live, such as the second highest salary, duplicate records, employees earning more than their manager and department-wise counts. This guide gives you both: 60 concept questions and 25 query problems on one sample database so you can practise exactly like the interview.
This guide from VibrantMinds Technologies in Pune is written for anyone searching SQL interview questions for freshers, SQL interview questions and answers, SQL query interview questions for freshers, SQL joins interview questions, second highest salary in SQL, SQL practice questions with answers, SQL window functions interview questions, difference between WHERE and HAVING in SQL, SQL interview questions for Java developers or a free IT job WhatsApp group for SQL and Java freshers in Pune.
Takeaway | Detail |
|---|---|
Interviews mix theory and live queries | Know definitions, but practise writing queries from memory. |
Joins and GROUP BY decide most rounds | Master INNER, LEFT, GROUP BY and HAVING. |
The classic queries repeat | Second highest salary, duplicates, department counts, Nth highest. |
Say the logic aloud | Explain tables, join keys and filters before typing. |
Know NULL behaviour |
|
Name your dialect | Mention MySQL, PostgreSQL or SQL Server when syntax differs. |
Practise on a real database | Install MySQL or PostgreSQL and run every query yourself. |
HOW SQL INTERVIEW ROUNDS USUALLY FLOW
THE SAMPLE DATABASE USED IN THIS GUIDE
Create these two tables in MySQL or PostgreSQL and run every query yourself.
sql
departments
dept_id | dept_name |
|---|---|
1 | IT |
2 | HR |
3 | Testing |
4 | Finance |
employees
emp_id | emp_name | dept_id | salary | manager_id | city |
|---|---|---|---|---|---|
1 | Amit | 1 | 60000 | NULL | Pune |
2 | Divya | 1 | 50000 | 1 | Pune |
3 | Farhan | 2 | 40000 | 1 | Mumbai |
4 | Gauri | 3 | 45000 | 1 | Pune |
5 | Harsh | 1 | 50000 | 2 | Nashik |
6 | Isha | 3 | 35000 | 4 | Pune |
7 | Jay | 2 | 42000 | 3 | Mumbai |
8 | Kiran | NULL | 30000 | 1 | Pune |
Notice the deliberate details: Kiran has no department (NULL), the Finance department has no employees, two people share the salary 50000 and Jay earns more than his manager Farhan. These traps are exactly what interviewers use.
MODULE 1: SQL AND DATABASE BASICS (Q1 TO Q12)
Q1. What is SQL?
Answer: Structured Query Language, the standard language to create, read, update and delete data in relational databases.
Q2. DBMS vs RDBMS?
Answer: A DBMS stores data in any structure (files, for example). An RDBMS stores data in related tables with keys and supports SQL and constraints. MySQL, PostgreSQL, SQL Server and Oracle are RDBMS.
Q3. What are the types of SQL commands?
Type | Full form | Commands |
|---|---|---|
DDL | Data Definition Language | CREATE, ALTER, DROP, TRUNCATE |
DML | Data Manipulation Language | INSERT, UPDATE, DELETE |
DQL | Data Query Language | SELECT |
DCL | Data Control Language | GRANT, REVOKE |
TCL | Transaction Control Language | COMMIT, ROLLBACK, SAVEPOINT |
Q4. DELETE vs TRUNCATE vs DROP
Point | DELETE | TRUNCATE | DROP |
|---|---|---|---|
Removes | Selected rows (or all) | All rows | The whole table |
WHERE clause | Yes | No | No |
Type | DML | DDL | DDL |
Rollback | Usually possible inside a transaction | Depends on the database | Depends on the database |
Table structure | Kept | Kept | Removed |
Q5. What is a table, a row and a column?
Answer: A table stores data. A row (record or tuple) is one entry. A column (field or attribute) is one data property.
Q6. What are the common data types?
Answer: Numeric (INT, DECIMAL), text (VARCHAR, CHAR, TEXT), date and time (DATE, DATETIME, TIMESTAMP), and boolean.
Q7. CHAR vs VARCHAR?
Answer: CHAR(n) is fixed length. VARCHAR(n) is variable length and stores only what’s needed.
Q8. What is NULL?
Answer: The absence of a value. It isn’t zero or an empty string. Comparisons with NULL need IS NULL or IS NOT NULL.
Q9. What are aliases?
Answer: Temporary names for columns or tables to make queries readable.
sql
Q10. What is a schema?
Answer: A logical container for database objects such as tables, views and indexes.
Q11. What is a database transaction?
Answer: A group of SQL operations treated as one unit: all succeed or all fail.
Q12. What are ACID properties?
Property | Meaning |
|---|---|
Atomicity | All steps happen or none do |
Consistency | Data stays valid after the transaction |
Isolation | Concurrent transactions don’t interfere |
Durability | Committed data survives failures |
MODULE 2: KEYS, CONSTRAINTS AND NORMALISATION (Q13 TO Q22)
Q13. What is a primary key?
Answer: A column (or set of columns) that uniquely identifies each row. It cannot be NULL or duplicate, and a table has only one.
Q14. What is a foreign key?
Answer: A column that refers to the primary key of another table, enforcing referential integrity.
Q15. Primary key vs unique key?
Point | Primary key | Unique key |
|---|---|---|
NULL | Not allowed | Usually allowed (rules vary by database) |
Count per table | One | Many |
Purpose | Row identity | Prevent duplicate values |
Q16. What is a composite key?
Answer: A primary key made of two or more columns.
Q17. What are constraints?
Answer: Rules on data: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT.
Q18. What is normalisation?
Answer: Organising data to reduce redundancy and improve integrity by splitting data into related tables.
Q19. 1NF, 2NF, 3NF in simple words
Form | Rule |
|---|---|
1NF | Each cell holds one value, no repeating groups |
2NF | 1NF, and every non-key column depends on the whole primary key |
3NF | 2NF, and non-key columns don’t depend on other non-key columns |
Q20. What is denormalisation?
Answer: Deliberately adding redundancy to speed up reads, often used in reporting.
Q21. What is referential integrity?
Answer: Ensuring a foreign key value always matches an existing primary key value (or is NULL).
Q22. What are ON DELETE CASCADE and ON DELETE SET NULL?
Answer: Rules for what happens to child rows when the parent row is deleted. CASCADE deletes the child rows. SET NULL sets the foreign key to NULL.
MODULE 3: SELECT, WHERE, ORDER BY AND FUNCTIONS (Q23 TO Q32)
Q23. Basic SELECT, WHERE and ORDER BY
sql
Q24. DISTINCT
sql
Q25. IN, BETWEEN, LIKE
sql
Q26. How do you handle NULL?
sql
Q27. LIMIT, TOP and FETCH FIRST
Answer: They return the first N rows. MySQL and PostgreSQL use LIMIT, SQL Server uses TOP, and Oracle (12c+) and standard SQL use FETCH FIRST n ROWS ONLY.
sql
Q28. Common aggregate functions?
Answer: COUNT, SUM, AVG, MIN, MAX.
Q29. COUNT(*) vs COUNT(column)?
Answer: COUNT(*) counts all rows. COUNT(column) counts only non-NULL values in that column.
sql
Q30. Common string and date functions?
Answer: UPPER, LOWER, LENGTH, SUBSTRING, CONCAT, TRIM, NOW, CURRENT_DATE, DATEDIFF. Names vary a little by database.
Q31. What is CASE?
sql
Q32. UNION vs UNION ALL?
Answer: Both combine results of two queries with the same column structure. UNION removes duplicates, while UNION ALL keeps them and is faster.
MODULE 4: GROUP BY, HAVING AND AGGREGATES (Q33 TO Q40)
Q33. What does GROUP BY do?
Answer: It groups rows with the same values so you can apply aggregate functions per group.
sql
Q34. WHERE vs HAVING
Point | WHERE | HAVING |
|---|---|---|
Filters | Rows, before grouping | Groups, after grouping |
Aggregates | Cannot use them | Can use them |
Example |
|
|
sql
Q35. Can you use a column in SELECT that isn’t in GROUP BY?
Answer: Not unless it’s inside an aggregate function (strict SQL modes enforce this). Otherwise the result is ambiguous.
Q36. How do you count employees per city, sorted by count?
sql
Q37. How do you find the highest salary in each department?
sql
Q38. Can GROUP BY have multiple columns?
Answer: Yes. Groups are formed by the combination, for example GROUP BY dept_id, city.
Q39. What does COUNT(DISTINCT column) do?
sql
Q40. How do aggregates treat NULL?
Answer: They ignore NULL values (except COUNT(*)). AVG divides by the number of non-NULL values.
MODULE 5: JOINS (Q41 TO Q48)
Q41. INNER JOIN
sql
Q42. LEFT JOIN
sql
Q43. INNER JOIN vs LEFT JOIN: the difference
Point | INNER JOIN | LEFT JOIN |
|---|---|---|
Returns | Only matching rows | All left-table rows, with NULLs where no match |
Kiran (no department) | Missing | Present |
Use when | You need matched data only | You must keep every row from the left table |
Q44. How do you find departments with no employees?
sql
Q45. What is a self join? Show employee and manager names.
sql
Q46. What is a CROSS JOIN?
Answer: It pairs every row of one table with every row of another (the Cartesian product). 8 employees × 4 departments gives 32 rows.
Q47. RIGHT JOIN and FULL OUTER JOIN?
Answer: RIGHT JOIN keeps all rows from the right table. FULL OUTER JOIN keeps all rows from both. MySQL has no direct FULL OUTER JOIN, so emulate it with LEFT JOIN UNION RIGHT JOIN.
Q48. Does the position of a condition matter in a LEFT JOIN?
Answer: Yes. A filter on the right table in WHERE can remove the NULL rows and turn the LEFT JOIN into an INNER JOIN. Put such a filter in the ON clause to keep the unmatched rows.
MODULE 6: SUBQUERIES, VIEWS, INDEXES AND TRANSACTIONS (Q49 TO Q60)
Q49. What is a subquery?
Answer: A query nested inside another query.
sql
Q50. Correlated vs non-correlated subquery?
Answer: A non-correlated subquery runs once independently. A correlated subquery depends on the outer query and runs for each outer row.
Q51. IN vs EXISTS?
Answer: IN compares against a list of values. EXISTS checks whether a subquery returns any row, and often performs well on large tables. Watch NULL behaviour with NOT IN, because a NULL in the list can make the result empty. NOT EXISTS is safer.
Q52. What is a view?
Answer: A saved query that behaves like a virtual table.
sql
Q53. What is an index? Pros and cons?
Answer: A structure that speeds up searches on a column. It makes reads faster but uses storage and slows inserts and updates.
sql
Q54. Clustered vs non-clustered index?
Answer: A clustered index decides the physical order of rows (one per table). A non-clustered index is a separate structure pointing to rows (many per table). Exact behaviour varies by database.
Q55. What is a stored procedure?
Answer: A saved set of SQL statements stored in the database that you can call by name, with parameters.
Q56. What is a trigger?
Answer: Code that runs automatically on events such as INSERT, UPDATE or DELETE.
Q57. COMMIT, ROLLBACK and SAVEPOINT
sql
Answer: COMMIT saves changes, ROLLBACK undoes them and SAVEPOINT marks a point to roll back to.
Q58. What is SQL injection and how do you prevent it?
Answer: An attack where malicious input changes a query. Prevent it with parameterised queries or prepared statements and input validation, never string concatenation.
Q59. What is a CTE?
Answer: A Common Table Expression, a named temporary result defined with WITH that makes complex queries readable.
sql
Q60. What is the difference between a function and a stored procedure?
Answer: A function returns a value and can be used inside queries. A stored procedure performs actions and may return results through output parameters or result sets. Details differ by database.
QUERY PRACTICE: 25 PROBLEMS WITH ANSWERS (USE THE SAMPLE TABLES)
Try each problem yourself before reading the answer.
P1. Find the second highest salary.
sql
P2. Second highest salary using LIMIT and OFFSET (MySQL or PostgreSQL).
sql
P3. Nth highest salary (N = 3, using DENSE_RANK).
sql
P4. Find duplicate salaries.
sql
P5. Employees earning more than the average salary.
sql
P6. Department-wise employee count including departments with no employees.
sql
Note: COUNT(e.emp_id) gives 0 for Finance, while COUNT(*) would wrongly give 1.
P7. Departments with more than 2 employees.
sql
P8. Highest-paid employee in each department.
sql
P9. Employees who earn more than their manager.
sql
P10. Employees without a department.
sql
P11. Departments with no employees.
sql
P12. Employees and their manager names.
sql
P13. Employees whose name starts with a vowel.
sql
P14. Total salary per city.
sql
P15. Top 3 highest-paid employees.
sql
P16. Employees in the same department as Divya (excluding Divya).
sql
P17. Add a salary band label to every employee.
sql
P18. Department-wise average salary, only above 40000.
sql
P19. Delete duplicate rows keeping the lowest id (concept, for a table with an id column).
sql
Practise this on a copy of a table, never on live data. Syntax differs by database.
P20. Rank employees by salary within each department.
sql
P21. Running total of salary ordered by emp_id.
sql
P22. Employees hired in the current month (for a table with a join_date column).
sql
P23. Swap values using CASE (for example, change city names).
sql
Run inside a transaction and roll back after testing.
P24. Find the manager who has the most direct reports.
sql
P25. List cities with employees in more than one department.
sql
WINDOW FUNCTIONS FOR FRESHERS
Function | What it does | Behaviour on ties |
|---|---|---|
ROW_NUMBER() | Unique sequence number | Always unique |
RANK() | Rank with gaps | Ties share a rank, next rank skips (1, 1, 3) |
DENSE_RANK() | Rank without gaps | Ties share a rank, no skip (1, 1, 2) |
SUM() OVER | Running or partition total | n/a |
LAG() / LEAD() | Previous or next row’s value | n/a |
sql
With the two salaries of 50000, you’ll see RANK jump (2, 2, 4) while DENSE_RANK doesn’t (2, 2, 3). Window functions need MySQL 8.0+ or another modern database.
SQL ORDER OF EXECUTION (WHY WHERE CAN’T USE ALIASES OR AGGREGATES)
This explains why WHERE can’t use aggregates (groups don’t exist yet) and why a SELECT alias can be used in ORDER BY but usually not in WHERE.
PERFORMANCE BASICS FRESHERS SHOULD KNOW
Practice | Why |
|---|---|
Select only needed columns | Avoid |
Index columns used in WHERE, JOIN and ORDER BY | Faster lookups |
Avoid functions on indexed columns in WHERE |
|
Use | Often more efficient |
Filter early | Reduce rows before joining and grouping |
Use | See how the database runs your query |
SQL WITH JAVA: QUESTIONS FOR JAVA FULL STACK FRESHERS
Question | Short answer |
|---|---|
Statement vs PreparedStatement? | PreparedStatement is precompiled, safer against SQL injection and faster for repeated queries. |
How do you connect Java to a database? | Load the JDBC driver, get a connection, create a statement, execute, process the ResultSet and close resources (try-with-resources). |
What is a connection pool? | A cache of reusable connections that avoids the cost of opening a new one for each request. |
How does JPA map to SQL? | Entities map to tables, fields to columns, relationships to foreign keys. |
What is the N+1 problem? | One query loads parents and then N more queries load children. Fix with joins or fetch strategies. |
java
COMMON MISTAKES FRESHERS MAKE IN SQL INTERVIEWS
Mistake | Why it hurts | Better approach |
|---|---|---|
Using | Returns nothing | Use |
Using | Counts unmatched rows as 1 | Count a column from the right table |
Mixing WHERE and HAVING | Wrong or error | Row filter in WHERE, group filter in HAVING |
Forgetting the join condition | Accidental CROSS JOIN | Always write |
Memorising only the answer | Fails on a variation | Learn the logic |
Ignoring ties | Wrong top-N results | Know RANK vs DENSE_RANK |
Typing without explaining | Interviewer can’t follow | Narrate tables, joins, filters |
Not testing queries | Syntax mistakes | Run every query on the sample database |
Using | Empty results | Use |
14-DAY SQL PREPARATION PLAN
Day | Focus | Task |
|---|---|---|
1 | Setup | Install MySQL or PostgreSQL, create the sample tables |
2 | Basics | Q1 to Q12, DDL vs DML, DELETE vs TRUNCATE vs DROP |
3 | Keys and normalisation | Q13 to Q22, design a small 3-table schema |
4 | SELECT practice | Q23 to Q32, plus P10, P13, P15 |
5 | Aggregates | Q33 to Q40, plus P7, P14, P18 |
6 | Joins 1 | INNER and LEFT joins, P6, P12 |
7 | Joins 2 | Self join, P9, P11 and P24 |
8 | Subqueries | Q49 to Q51, P1, P5, P8, P16 |
9 | Nth highest and duplicates | P2, P3, P4, P19 |
10 | Window functions | P20, P21, RANK vs DENSE_RANK |
11 | Views, indexes, transactions | Q52 to Q60, run a transaction with ROLLBACK |
12 | SQL with Java | Write a JDBC PreparedStatement example |
13 | Mock interview | Solve 8 random problems aloud in 45 minutes |
14 | Review | Redo the problems you got wrong and explain each aloud |
MYTH VS REALITY
Myth | Reality |
|---|---|
“SQL is only for data roles.” | Developers, testers and analysts all use SQL. |
“Joins are too hard.” | Practise on the sample tables and they become pattern recognition. |
“Memorising 100 queries is enough.” | Variations test whether you understand the logic. |
“ORMs like JPA mean I don’t need SQL.” | Interviewers still test SQL, and debugging needs it. |
“Only the correct answer matters.” | Explanation, edge cases (NULL, ties) and clarity count too. |
“Window functions are for experts only.” | They are now common even in fresher rounds. |
HOW VIBRANTMINDS HELPS FRESHERS CRACK SQL AND JAVA INTERVIEWS
VibrantMinds Technologies Pvt. Ltd. is a Pune-based IT training and placement support company. If you searched for VibrantMinds or VibrantMinds Technologies, here is what it offers:
Full Stack Java Development (about 4 to 6 months): Core Java, OOP, JDBC, SQL, Spring Boot, REST APIs, front-end basics, projects, aptitude and interview preparation. Please check the candidate portal for the latest syllabus and tools.
Software Testing (Manual + Automation) (SQL is useful for data validation), Core Java and Python & Data Science for other career paths
Interview preparation: Technical rounds, SQL and coding practice, project rounds, HR rounds, aptitude, communication and mock interviews
Placement support: Screening, drive coordination and interview support. Check https://candidates.vibrantminds.in/ for current openings.
Free WhatsApp job alert groups for fresher IT jobs, campus drives and walk-in alerts
Honesty first: VibrantMinds offers placement support, not a guaranteed job, and no legitimate recruiter should ask you to pay to be interviewed.
VibrantMinds works as a talent ecosystem connecting candidates, colleges and companies, with 1900+ partner colleges and 600+ hiring companies. More fresher job guidance: https://candidates.vibrantminds.in/blog/fresher-jobs-pune-2026
VIBRANTMINDS COURSES AT A GLANCE
Course | Duration | Key topics |
|---|---|---|
Full Stack Java Development | 4 to 6 months | Core Java, OOP, JDBC, SQL, Spring Boot, REST APIs, front-end basics, projects, aptitude and interview preparation |
Software Testing (Manual + Automation) | 2 to 5 months | Test cases, STLC, bug tracking, SQL, Selenium basics |
Core Java | 1 to 2 months | Syntax, OOP, collections, exceptions, strings |
Python & Data Science | 2 to 4 months | Python basics, data handling, analysis fundamentals |
Fees, syllabus and batch dates are on https://candidates.vibrantminds.in/. Please confirm them directly before enrolling.
THE VIBRANTMINDS PLACEMENT PIPELINE: SIX STEPS
REAL OUTCOMES: WHAT TO EXPECT AND WHAT NOT TO
Past students have shared positive feedback about the training and support, and have gone on to roles at companies such as Aress Software and Education Technologies, Saama Technologies and Three M Software. Results vary by candidate, skill level, effort and market conditions, so please confirm details directly with the VibrantMinds team. No one can honestly promise a guaranteed job.
JOIN FREE VIBRANTMINDS WHATSAPP GROUPS: FREE IT JOB UPDATES FOR SQL, JAVA AND PYTHON FRESHERS IN PUNE AND INDIA
Looking for free WhatsApp groups, free IT job WhatsApp groups, a Java WhatsApp group for freshers or a job updates WhatsApp group in India? The VibrantMinds groups share fresher IT openings, campus drives, walk-in interview alerts and interview preparation updates, free of charge. Join whichever group has space. All three carry the same type of updates.
Group | What it offers | Link |
|---|---|---|
VibrantMinds Fresher IT Jobs, Group 1 | Fresher openings, campus drives, walk-in alerts | |
VibrantMinds Fresher IT Jobs, Group 2 | Fresher openings, campus drives, walk-in alerts | |
VibrantMinds Fresher IT Jobs, Group 3 | Fresher openings, campus drives, walk-in alerts |
Never pay to apply. Legitimate recruiters do not charge candidates for tests, interviews or offer letters. Do not share sensitive personal or financial details in any group chat.
FREQUENTLY ASKED QUESTIONS
1. What are the most asked SQL interview questions for freshers?
DELETE vs TRUNCATE vs DROP, primary key vs foreign key, WHERE vs HAVING, INNER JOIN vs LEFT JOIN, GROUP BY with aggregates, normalisation basics, subqueries, and live queries such as the second highest salary, duplicate records, department-wise counts and employees earning more than their manager.
2. How do I find the second highest salary in SQL?
The simplest portable way is SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);. You can also use SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1; in MySQL or PostgreSQL, or DENSE_RANK() to find any Nth highest salary, which handles ties correctly.
3. What is the difference between INNER JOIN and LEFT JOIN with an example?
INNER JOIN returns only rows that match in both tables. LEFT JOIN returns every row from the left table and fills the right side with NULL where nothing matches. In the sample tables, an employee with no department appears in the LEFT JOIN result but not in the INNER JOIN result.
4. What is the difference between WHERE and HAVING in SQL?WHERE filters individual rows before grouping and can’t use aggregate functions. HAVING filters groups after GROUP BY and can use aggregates such as COUNT(*) > 2.
5. Is there a free WhatsApp group for SQL and Java freshers in Pune?
Yes. VibrantMinds runs free fresher IT job WhatsApp groups that share Java, SQL-related, testing and other IT openings, campus drives and walk-in alerts. Join through the links above, and always verify a job post and never pay to apply.
CONCLUSION: PRACTISE QUERIES, NOT JUST DEFINITIONS
The fastest way to master SQL interview questions for freshers is to run every query on a real database. Learn the 60 concepts, then solve the 25 problems on the sample tables until joins, GROUP BY, HAVING, subqueries and window functions feel natural. Watch the NULL and tie traps, explain your logic aloud and follow the 14-day plan.
If you’re in Pune and want structured Java and SQL training with practice projects, interview preparation and placement support, VibrantMinds Technologies is here to help.
Call to action:
Website: https://vibrantminds.in/
Candidate portal and courses: https://candidates.vibrantminds.in/
Fresher jobs guide: https://candidates.vibrantminds.in/blog/fresher-jobs-pune-2026
Join the free WhatsApp groups: the three links above
VISIT OR CONTACT VIBRANTMINDS IN PUNE
Company: VibrantMinds Technologies Pvt. Ltd.
Address: Viva Academy Building, Warje, Pune, Maharashtra 411052
Phone: +91 95035 79517
Email: support@vibrantmindstech.com
Website: https://vibrantminds.in/
Candidate portal and courses: https://candidates.vibrantminds.in/


