Top 75 SQL Interview Questions and Answers for Freshers

Top 75 SQL Interview Questions and Answers for Freshers

SQL (Structured Query Language) is an essential skill for software developers, full-stack developers, data analysts, database administrators, data engineers and AI/ML engineers. This guide covers fundamental, intermediate and advanced SQL concepts along with practical queries for campus placements and technical interviews.

Section 1: SQL Fundamentals

1. What is SQL?

SQL stands for Structured Query Language. It is a standard language used to create, access, manage and manipulate data in relational databases.

2. What is a database?

A database is an organized collection of data that can be electronically stored, accessed, managed and updated.

3. What is DBMS?

A Database Management System is software used to create, store, retrieve and manage databases. Examples include MySQL, Oracle and SQL Server.

4. What is RDBMS?

A Relational Database Management System stores data in tables and supports relationships between them. Examples include MySQL, PostgreSQL, Oracle and SQL Server.

5. What is the difference between DBMS and RDBMS?

An RDBMS is a specific category of DBMS.

DBMS RDBMS
Manages databases Manages relational databases
May use different data models Uses the relational model
Integrity mechanisms vary Supports relational integrity constraints

6. What is a table in SQL?

A table stores related data in rows and columns.

Student_ID Name Marks
101 Ravi 85
102 Priya 92
103 Kumar 78

7. What are rows and columns?

A row represents an individual record (tuple). A column represents an attribute of the records.

8. What are the different types of SQL commands?

The following classification is commonly used in interview preparation.

Category 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

9. What is the difference between SQL and MySQL?

SQL is a language, whereas MySQL is database management software that implements SQL.

SQL MySQL
Database language Relational database management system
Standardized language Implements SQL with additional features

10. What are SQL data types?

Data types specify the kind of values stored in a column. Availability and behavior vary by database.

Data type Purpose
INT Integers
FLOAT Approximate decimals
DECIMAL Exact decimals
CHAR Fixed-length strings
VARCHAR Variable-length strings
DATE Dates
TIMESTAMP Date/time information (DBMS dependent)
BOOLEAN Logical values
BLOB Binary data

Section 2: SQL Keys and Constraints

11. What is a primary key?

A column or combination of columns that uniquely identifies each record. It cannot contain duplicate key values or NULL values.

CREATE TABLE Students (
    Student_ID INT PRIMARY KEY,
    Name VARCHAR(100)
);

12. What is a foreign key?

A column or combination of columns referencing an eligible unique key in another table or the same table. It maintains referential integrity.

CREATE TABLE Students (
    Student_ID INT PRIMARY KEY,
    Department_ID INT,
    FOREIGN KEY (Department_ID)
        REFERENCES Departments(Department_ID)
);

13. What is a candidate key?

A minimal set of attributes that uniquely identifies a record. One candidate key is selected as the primary key.

14. What is a super key?

Any set of attributes that uniquely identifies a record. It may contain unnecessary attributes.

15. What is a composite key?

A key formed using two or more columns.

PRIMARY KEY (Student_ID, Course_ID)

16. What is an alternate key?

A candidate key not selected as the primary key.

17. What are constraints in SQL?

Rules that maintain data accuracy, consistency and integrity.

Constraint Purpose
PRIMARY KEY Uniquely identifies records
FOREIGN KEY Maintains referential integrity
UNIQUE Enforces uniqueness
NOT NULL Prevents NULL values
CHECK Validates a condition
DEFAULT Supplies a default value

18. What is the difference between PRIMARY KEY and UNIQUE?

Both enforce uniqueness.

PRIMARY KEY UNIQUE
One per table Multiple allowed
Does not allow NULL NULL handling depends on DBMS
May contain multiple columns May contain multiple columns

19. What is a NULL value?

NULL represents missing or unknown information. It is not zero or an empty string.

SELECT * FROM Students WHERE Email IS NULL;

20. What is a DEFAULT constraint?

It supplies a predefined value when a value is omitted during insertion.

CREATE TABLE Students (
    Student_ID INT PRIMARY KEY,
    Status VARCHAR(20) DEFAULT 'Active'
);

Section 3: SQL Commands and Clauses

21. What is the SELECT statement?

Retrieves data from one or more tables.

SELECT * FROM Students;
SELECT Name, Marks FROM Students;

22. What is the INSERT statement?

Adds new records.

INSERT INTO Students (Student_ID, Name, Marks)
VALUES (101, 'Ravi', 85);

23. What is the UPDATE statement?

Modifies existing records. Without WHERE, all records may be updated.

UPDATE Students SET Marks = 95
WHERE Student_ID = 101;

24. What is the DELETE statement?

Removes records.

DELETE FROM Students WHERE Student_ID = 101;

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

Rollback support depends on the database and transaction configuration.

DELETE TRUNCATE DROP
Removes selected or all rows Removes all rows Removes the table
Supports WHERE No WHERE No WHERE
Retains structure Retains structure Removes structure
DML Typically DDL DDL

26. What is the ALTER command?

Modifies an existing table structure.

ALTER TABLE Students ADD Email VARCHAR(100);

27. What is the WHERE clause?

Filters individual records.

SELECT * FROM Students WHERE Marks >= 80;

28. What is the ORDER BY clause?

Sorts results. ASC means ascending and DESC means descending.

SELECT * FROM Students ORDER BY Marks DESC;

29. What is the DISTINCT keyword?

Eliminates duplicate result rows based on selected columns.

SELECT DISTINCT Department FROM Students;

30. What is the LIKE operator?

Searches for patterns. % matches zero or more characters; _ matches exactly one character.

SELECT * FROM Students WHERE Name LIKE 'A%';

31. What is the BETWEEN operator?

Selects values within an inclusive range.

SELECT * FROM Students WHERE Marks BETWEEN 60 AND 90;

32. What is the IN operator?

Checks whether a value matches any value in a list or subquery.

SELECT * FROM Students WHERE Department IN ('CSE', 'AIML', 'IT');

33. What is the GROUP BY clause?

Groups rows with the same values for aggregate calculations.

SELECT Department, COUNT(*) AS Total
FROM Students GROUP BY Department;

34. What is the HAVING clause?

Filters grouped results.

SELECT Department, COUNT(*) AS Total
FROM Students GROUP BY Department
HAVING COUNT(*) > 50;

35. What is the difference between WHERE and HAVING?

WHERE filters rows before grouping; HAVING filters groups after grouping.

WHERE HAVING
Filters individual rows Filters groups
Before grouping After grouping
Cannot directly filter same-level aggregates Supports aggregate conditions

Section 4: SQL Functions and Joins

36. What are aggregate functions?

They calculate a single result for each group of values.

SELECT AVG(Marks) AS Average_Marks FROM Students;
Function Purpose
COUNT() Counts rows or non-NULL values
SUM() Total
AVG() Average
MAX() Maximum
MIN() Minimum

37. What are scalar functions?

They operate on individual values. Examples include UPPER(), LOWER(), ROUND(), ABS() and LENGTH(). Names may vary by DBMS.

SELECT UPPER(Name) FROM Students;

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

COUNT(*) counts all rows; COUNT(column) counts non-NULL values.

SELECT COUNT(*), COUNT(Email) FROM Students;

39. What is a JOIN?

A JOIN combines rows from tables based on a specified condition.

Join Returns
INNER JOIN Matching rows
LEFT JOIN All left rows and matching right rows
RIGHT JOIN All right rows and matching left rows
FULL OUTER JOIN All matching and unmatched rows
CROSS JOIN All combinations

40. What is an INNER JOIN?

Returns matching rows from both tables.

SELECT S.Name, D.Department_Name
FROM Students S
INNER JOIN Departments D
ON S.Department_ID = D.Department_ID;

41. What is a LEFT JOIN?

Returns all left rows and matching right rows. Unmatched right columns contain NULL.

SELECT S.Name, D.Department_Name
FROM Students S
LEFT JOIN Departments D
ON S.Department_ID = D.Department_ID;

42. What is a RIGHT JOIN?

Returns all right rows and matching left rows.

SELECT S.Name, D.Department_Name
FROM Students S
RIGHT JOIN Departments D
ON S.Department_ID = D.Department_ID;

43. What is a FULL OUTER JOIN?

Returns all matching and unmatched rows. MySQL does not directly support this syntax.

SELECT S.Name, D.Department_Name
FROM Students S
FULL OUTER JOIN Departments D
ON S.Department_ID = D.Department_ID;

44. What is a CROSS JOIN?

Returns the Cartesian product. Five rows crossed with four rows produce twenty rows.

SELECT * FROM Students CROSS JOIN Courses;

45. What is a SELF JOIN?

Joins a table with itself using aliases, for example employees and managers.

SELECT E.Name AS Employee, M.Name AS Manager
FROM Employees E LEFT JOIN Employees M
ON E.Manager_ID = M.Employee_ID;

Section 5: Intermediate and Advanced SQL Concepts

46. What is a subquery?

A query inside another query. This example retrieves students scoring above average.

SELECT Name, Marks FROM Students
WHERE Marks > (SELECT AVG(Marks) FROM Students);

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

Both combine compatible query results. UNION removes duplicates; UNION ALL retains them and generally requires less processing.

48. What is a view?

A virtual table based on a query. A regular view generally stores the query definition rather than its results.

CREATE VIEW TopStudents AS
SELECT Student_ID, Name, Marks FROM Students
WHERE Marks >= 90;

49. What is an index?

A structure that improves data retrieval performance but requires storage and may increase write costs.

CREATE INDEX idx_student_name ON Students(Name);

50. What is normalization?

Organizing tables to reduce unnecessary redundancy and insertion, update and deletion anomalies.

Normal form Description
1NF Atomic values and no repeating groups
2NF 1NF with no partial dependency of non-prime attributes on candidate keys
3NF Removes problematic transitive dependencies
BCNF Every determinant of a non-trivial functional dependency is a super key

51. What is denormalization?

Intentionally introducing redundancy to improve read performance and reduce joins, often in reporting and data warehouses.

52. What is a transaction?

A sequence of database operations treated as a logical unit. For example, both sides of a bank transfer should succeed together or be rolled back together.

53. What are ACID properties?

ACID properties help ensure reliable transactions.

Property Meaning
Atomicity All operations succeed or none are committed
Consistency Preserves database integrity rules
Isolation Controls interference between concurrent transactions
Durability Committed changes survive failures under durability guarantees

54. What are COMMIT, ROLLBACK and SAVEPOINT?

COMMIT saves changes, ROLLBACK reverses uncommitted changes and SAVEPOINT allows partial rollback. Example uses MySQL-style syntax.

START TRANSACTION;
UPDATE Accounts SET Balance = Balance - 1000 WHERE Account_ID = 101;
UPDATE Accounts SET Balance = Balance + 1000 WHERE Account_ID = 102;
COMMIT;

55. What is a stored procedure?

A named collection of SQL statements stored in the database. Example in MySQL:

CREATE PROCEDURE GetStudents()
SELECT * FROM Students;

CALL GetStudents();

56. What is a trigger?

A database program that automatically executes on specified events such as INSERT, UPDATE or DELETE. Used for auditing, validation and maintaining related data.

57. What is a Common Table Expression (CTE)?

A named temporary result set defined using WITH and available within one statement.

WITH TopStudents AS (
    SELECT * FROM Students WHERE Marks >= 90
)
SELECT * FROM TopStudents;

58. What are window functions?

Functions that calculate across related rows without collapsing them. Examples include ROW_NUMBER(), RANK(), DENSE_RANK(), LEAD() and LAG().

SELECT Name, Marks,
DENSE_RANK() OVER (ORDER BY Marks DESC) AS Student_Rank
FROM Students;

59. What is SQL injection?

A vulnerability in which malicious input interferes with SQL queries. Use parameterized queries, prepared statements and least-privilege database permissions; input validation is supplementary.

60. What is the difference between SQL and NoSQL databases?

SQL databases are relational; NoSQL databases use various non-relational models.

SQL databases NoSQL databases
Relational model Document, key-value, graph or other models
Generally predefined schema Often flexible schema
Uses SQL Query mechanisms vary
Supports relational joins Join support varies
MySQL, PostgreSQL, Oracle MongoDB, Redis, Cassandra

Section 6: Top 15 Practical SQL Interview Questions

Consider the following Employees table. Each example is independent and uses the original sample data. The examples are illustrative and have not been executed against a database.

Employee_ID Name Department Salary
101 Ravi IT 50000
102 Priya HR 45000
103 Kumar IT 75000
104 Sneha Finance 60000
105 Arjun IT 75000

61. Display all employees.

Retrieve every row and column.

SELECT * FROM Employees;

62. Find employees earning more than 50,000.

Filter by salary.

SELECT * FROM Employees WHERE Salary > 50000;

63. Find the highest salary.

Expected output: 75000.

SELECT MAX(Salary) AS Highest_Salary FROM Employees;

64. Find the second-highest distinct salary.

Expected output: 60000.

SELECT MAX(Salary) AS Second_Highest FROM Employees
WHERE Salary < (SELECT MAX(Salary) FROM Employees);

65. Find the third-highest distinct salary.

Expected output: 50000.

WITH RankedEmployees AS (
    SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS Salary_Rank
    FROM Employees
)
SELECT DISTINCT Salary FROM RankedEmployees WHERE Salary_Rank = 3;

66. Count employees in each department.

Group by department.

SELECT Department, COUNT(*) AS Total FROM Employees GROUP BY Department;
Department Total
IT 3
HR 1
Finance 1

67. Find the average salary.

Expected output: 61000.

SELECT AVG(Salary) AS Average_Salary FROM Employees;

68. Find employees earning above average.

Expected output: Kumar and Arjun (75000 each).

SELECT Name, Salary FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);

69. Find duplicate salary values.

Expected output: 75000, with two occurrences.

SELECT Salary, COUNT(*) AS Total FROM Employees
GROUP BY Salary HAVING COUNT(*) > 1;

70. Display the top three highest-paid employees.

Uses MySQL/PostgreSQL syntax.

SELECT * FROM Employees
ORDER BY Salary DESC, Employee_ID ASC LIMIT 3;

71. Find employees whose names start with A.

Expected output: Arjun.

SELECT * FROM Employees WHERE Name LIKE 'A%';

72. Increase IT employee salaries by 10%.

Update matching records only.

UPDATE Employees SET Salary = Salary * 1.10 WHERE Department = 'IT';

73. Find the highest salary in each department.

Use MAX with GROUP BY.

SELECT Department, MAX(Salary) AS Highest_Salary
FROM Employees GROUP BY Department;

74. Find departments having more than two employees.

Expected output: IT.

SELECT Department, COUNT(*) AS Total FROM Employees
GROUP BY Department HAVING COUNT(*) > 2;

75. Rank employees based on salary.

RANK assigns equal ranks to ties and leaves gaps.

SELECT Name, Salary, RANK() OVER (ORDER BY Salary DESC) AS Employee_Rank
FROM Employees;
Name Salary Rank
Kumar 75000 1
Arjun 75000 1
Sneha 60000 3
Ravi 50000 4
Priya 45000 5

SQL Logical Query Processing Order

The simplified logical processing order differs from the written order. The optimizer may choose a different physical execution plan.

  1. FROM / JOIN – identify source tables
  2. WHERE – filter rows
  3. GROUP BY – group rows
  4. HAVING – filter groups
  5. SELECT – evaluate selected expressions
  6. DISTINCT – remove duplicate results
  7. ORDER BY – sort results
  8. LIMIT / OFFSET – restrict returned rows

SQL Interview Preparation Checklist for Freshers

  • SQL fundamentals and data types
  • DDL, DML, DQL, DCL and TCL
  • Keys and constraints
  • WHERE, ORDER BY and DISTINCT
  • GROUP BY and HAVING
  • Aggregate and scalar functions
  • SQL joins
  • Subqueries and correlated subqueries
  • UNION and UNION ALL
  • Normalization and database design
  • Views and indexes
  • Transactions and ACID
  • Stored procedures and triggers
  • CTEs and window functions
  • Practical queries and database security

Conclusion

SQL is an essential skill for students aspiring to build careers in the IT industry. Practice with a Student Management System, Employee Management System, Library Management System or E-Commerce database to strengthen your practical knowledge.

These 75 SQL interview FAQs cover beginner, intermediate, advanced and practical concepts. Examples primarily use standard SQL and MySQL-compatible syntax, with database-specific differences noted where relevant. Individual examples assume the required tables and columns already exist.

Leave a Reply

Your email address will not be published. Required fields are marked *