SQL Interview Questions and Answers for Freshers: Top Questions to Prepare
Quick Answer: What Should Freshers Prepare for SQL Interviews?
Freshers preparing for SQL interviews should understand databases, tables, records, columns, data types, SQL commands, constraints, primary keys, foreign keys, and aggregate functions. They should also practise SELECT queries, filtering, sorting, joins, subqueries, GROUP BY, HAVING, and database normalization. For technical interviews, candidates should understand indexes, views, stored procedures, transactions, and practical query-writing problems involving real-world datasets.
Introduction
Structured Query Language (SQL) is one of the most important technologies used in database management and application development. It allows developers to store, retrieve, update, and manage structured information efficiently. From customer records and employee details to financial transactions and inventory information, SQL plays an important role in handling business data.
SQL is widely used in software development, data analytics, database administration, business intelligence, and backend application development. Developers use SQL to communicate with relational database management systems such as MySQL, PostgreSQL, Microsoft SQL Server, and Oracle Database.
For fresh graduates, preparing for an SQL interview requires more than remembering query syntax. Interviewers often evaluate whether candidates understand how databases organise information, how tables are connected, how queries retrieve records, and how database operations affect data consistency.
Questions may begin with basic database concepts and gradually move towards joins, subqueries, normalization, indexes, transactions, and query optimisation.
This guide covers more than 60 SQL interview questions and answers for freshers, progressing from fundamental database concepts to advanced SQL topics and practical query-writing exercises. Each explanation includes straightforward examples to help beginners understand the logic and prepare confidently for technical interviews.
Note: The examples use broadly standard SQL syntax. Some features and syntax may vary between MySQL, PostgreSQL, SQL Server, Oracle, and other database systems.
1. Basic SQL Interview Questions and Answers
1. What is SQL?
SQL stands for Structured Query Language. It is a standard language used to communicate with relational database management systems.
SQL allows users to create database structures, insert records, retrieve information, update existing data, and delete records.
For example:
SELECT * FROM Employees;
This query retrieves all columns and records from the Employees table.
SQL is commonly used in web applications, enterprise software, reporting systems, and data management solutions.
2. What is a database?
A database is an organised collection of information stored electronically so that it can be accessed, managed, updated, and retrieved efficiently.
For example, a college database may contain information about students, courses, faculty members, attendance, and examination results.
Databases help organisations maintain structured information, reduce unnecessary duplication, and support reliable data access.
3. What is a DBMS?
DBMS stands for Database Management System. It is software that allows users and applications to create, store, retrieve, update, and manage data in databases.
A DBMS provides features for data organisation, access control, backup, recovery, and database administration.
Examples include MySQL, PostgreSQL, Microsoft SQL Server, and Oracle Database.
4. What is an RDBMS?
RDBMS stands for Relational Database Management System. It is a database management system that organises data into related tables consisting of rows and columns.
Relationships between tables are commonly established using primary keys and foreign keys.
For example, a college database may contain a Students table and a Courses table, with another table connecting students to their enrolled courses.
RDBMS technology helps maintain structured relationships and supports data integrity.
5. What is the difference between DBMS and RDBMS?
Both DBMS and RDBMS are used to manage data, but they differ in their data organisation and relational capabilities.
| DBMS | RDBMS |
|---|---|
| General database management system. | Relational database management system. |
| May use different data organisation models. | Organises relational data into tables. |
| Relationship enforcement depends on the database model and system. | Supports relationships through relational structures and constraints. |
| Data integrity mechanisms vary by implementation. | Provides relational integrity features such as primary and foreign keys. |
| Examples include file-based database systems and non-relational systems. | Examples include MySQL, PostgreSQL, and Oracle Database. |
An RDBMS is particularly useful when applications need structured data and relationships between multiple tables.
6. What are tables, rows, and columns in SQL?
A table is a database structure used to store related information. It consists of rows and columns.
- Table: Represents a collection of related records, such as employees or products.
- Row: Represents one individual record in a table.
- Column: Represents a particular attribute or field, such as employee name, ID, or salary.
For example:
| Employee_ID | Name | Department |
|---|---|---|
| 101 | Arun | Development |
| 102 | Priya | Testing |
| 103 | Kumar | HR |
Here, Employees is the table, each employee entry is a row, and Employee_ID, Name, and Department are columns.
7. What are the different data types in SQL?
SQL data types determine what kind of values a column can store.
Common SQL data types include:
| Data type | Purpose | Example |
|---|---|---|
| INT / INTEGER | Stores whole numbers. | 100 |
| DECIMAL | Stores exact decimal values. | 1250.50 |
| FLOAT | Stores approximate floating-point values. | 25.75 |
| VARCHAR | Stores variable-length character strings. | 'Arun' |
| CHAR | Stores fixed-length character strings. | 'A' |
| DATE | Stores calendar dates. | '2026-11-03' |
| TIME | Stores time values. | '10:30:00' |
| TIMESTAMP | Stores date and time information. | Date-time value |
| BOOLEAN | Represents true or false values where supported. | TRUE |
The availability, naming, precision, and behaviour of some data types vary between database systems.
8. What is a primary key in SQL?
A primary key is a column or combination of columns that uniquely identifies each record in a table.
A primary key must contain unique, non-null values. A table can have only one primary key constraint, although that key may consist of multiple columns.
Example:
CREATE TABLE Students (
Student_ID INT PRIMARY KEY,
Name VARCHAR(100),
Age INT
);
Here, Student_ID uniquely identifies every student record.
Primary keys help maintain data integrity and establish relationships between tables.
9. What is a foreign key in SQL?
A foreign key is a column or combination of columns that references a candidate key, commonly the primary key, in another table or the same table.
It helps maintain referential integrity by ensuring that referenced values exist, subject to the configured constraint rules.
Example:
CREATE TABLE Departments (
Department_ID INT PRIMARY KEY,
Department_Name VARCHAR(100)
);
CREATE TABLE Employees (
Employee_ID INT PRIMARY KEY,
Employee_Name VARCHAR(100),
Department_ID INT,
FOREIGN KEY (Department_ID)
REFERENCES Departments(Department_ID)
);
Here, Department_ID in the Employees table references the corresponding department.
10. What is the difference between primary key and foreign key?
| Primary Key | Foreign Key |
|---|---|
| Uniquely identifies records in a table. | Establishes a relationship with a referenced key. |
| Must contain unique, non-null values. | Can contain repeated values and may allow NULL unless restricted. |
| A table has one primary key constraint. | A table can have multiple foreign key constraints. |
| Enforces entity integrity. | Helps enforce referential integrity. |
| Identifies records within its own table. | References a candidate key in another or the same table. |
Both constraints are essential for designing reliable relational databases.
11. What is a unique key in SQL?
A UNIQUE constraint ensures that duplicate values are not allowed in the constrained column or combination of columns.
Example:
CREATE TABLE Users (
User_ID INT PRIMARY KEY,
Email VARCHAR(150) UNIQUE,
Name VARCHAR(100)
);
Here, each email value must be unique.
Unlike a primary key, a UNIQUE constraint does not automatically make a column NOT NULL. The treatment of NULL values under unique constraints varies between database systems.
12. What is NULL in SQL?
NULL represents missing, unknown, or unavailable information in a database column.
It is different from zero, an empty string, or a regular value.
For example, if an employee has not provided a phone number, the Phone column may contain NULL.
To identify NULL values, use:
SELECT *
FROM Employees
WHERE Phone IS NULL;
Use IS NULL and IS NOT NULL instead of comparing NULL with the equality operator.
13. What is the difference between NULL, zero, and an empty string?
These three values represent different conditions.
| Value | Meaning |
|---|---|
| NULL | Represents missing, unknown, or unavailable information. |
| 0 | Represents the numeric value zero. |
| '' | Represents a string containing no characters. |
For example, a salary of zero is a numeric value, an empty employee name is a string with no characters, and a NULL salary indicates that the salary information is missing or unknown.
Understanding these differences is important when writing filtering conditions and calculating results.
2. SQL Commands and Constraints Interview Questions
14. What are the different types of SQL commands?
SQL commands are commonly grouped into five categories.
| Category | Full Form | Purpose | Examples |
|---|---|---|---|
| DDL | Data Definition Language | Defines database structures. | CREATE, ALTER, DROP, TRUNCATE |
| DML | Data Manipulation Language | Inserts and modifies data. | INSERT, UPDATE, DELETE |
| DQL | Data Query Language | Retrieves data. | SELECT |
| DCL | Data Control Language | Manages access permissions. | GRANT, REVOKE |
| TCL | Transaction Control Language | Manages transactions. | COMMIT, ROLLBACK, SAVEPOINT |
These categories help developers understand the purpose of different SQL statements.
15. What is DDL in SQL?
DDL stands for Data Definition Language. It is used to create and modify database structures such as tables, schemas, and other database objects.
Common DDL commands include:
- CREATE creates a database object.
- ALTER modifies an existing database object.
- DROP removes a database object.
- TRUNCATE removes all rows from a table while retaining its structure.
Example:
CREATE TABLE Courses (
Course_ID INT PRIMARY KEY,
Course_Name VARCHAR(100)
);
This statement creates a new table named Courses.
16. What is DML in SQL?
DML stands for Data Manipulation Language. It is used to insert, modify, and delete records in database tables.
Common DML commands include:
- INSERT adds new records.
- UPDATE modifies existing records.
- DELETE removes selected records.
Example:
INSERT INTO Students
(Student_ID, Name, Age)
VALUES
(101, 'Arun', 22);
This query inserts a new student record into the Students table.
17. What is the difference between DELETE, TRUNCATE, and DROP?
These commands remove data or database structures, but their behaviour is different.
| DELETE | TRUNCATE | DROP |
|---|---|---|
| Removes selected rows or all rows. | Removes all rows from a table. | Removes the table structure and its data. |
| Supports WHERE conditions. | Does not support WHERE conditions. | Does not support WHERE conditions. |
| Uses row-level deletion semantics. | Uses a table-level data removal operation, with implementation-specific behaviour. | Removes the database object. |
| Table structure remains. | Table structure remains. | Table structure is removed. |
Example:
DELETE FROM Employees
WHERE Employee_ID = 101;
TRUNCATE TABLE Employees;
DROP TABLE Employees;
The transaction behaviour, identity reset behaviour, and restrictions of TRUNCATE vary by database system.
18. What is the SELECT statement in SQL?
The SELECT statement retrieves information from one or more database tables.
Example:
SELECT Name, Salary
FROM Employees;
This query retrieves employee names and salaries.
To retrieve every column, use:
SELECT *
FROM Employees;
In production applications, selecting only the required columns is generally preferable because it reduces unnecessary data retrieval.
19. What is the WHERE clause in SQL?
The WHERE clause filters records based on specified conditions.
Example:
SELECT *
FROM Employees
WHERE Salary > 30000;
This query retrieves employees whose salary is greater than 30,000.
The WHERE clause supports operators such as =, >, <, >=, <=, <>, AND, OR, and NOT.
20. What is the difference between WHERE and HAVING?
Both clauses filter data, but they operate at different stages of query processing.
| WHERE | HAVING |
|---|---|
| Filters individual rows before grouping. | Filters groups after grouping. |
| Commonly used with regular column conditions. | Commonly used with aggregate conditions. |
| Does not directly filter aggregate results. | Can filter using aggregate functions. |
| Used before GROUP BY in the logical query processing order. | Used after GROUP BY. |
Example:
SELECT Department_ID,
AVG(Salary) AS Average_Salary
FROM Employees
WHERE Salary > 20000
GROUP BY Department_ID
HAVING AVG(Salary) > 40000;
This query first filters individual employee records, groups the remaining records by department, and then returns departments whose average salary exceeds 40,000.
21. What is the ORDER BY clause in SQL?
ORDER BY sorts query results based on one or more columns.
It supports two common sorting directions:
- ASC sorts values in ascending order.
- DESC sorts values in descending order.
Example:
SELECT *
FROM Employees
ORDER BY Salary DESC;
This query displays employees from the highest salary to the lowest salary.
If no direction is specified, ascending order is generally used.
22. What is the DISTINCT keyword in SQL?
DISTINCT removes duplicate rows from the result set based on the selected columns.
Example:
SELECT DISTINCT Department
FROM Employees;
This query returns each department value only once.
DISTINCT can also be applied to multiple columns, in which case it removes duplicate combinations of those selected values.
23. What is the BETWEEN operator in SQL?
BETWEEN checks whether a value falls within a specified inclusive range.
Example:
SELECT *
FROM Employees
WHERE Salary BETWEEN 20000 AND 50000;
This query returns employees whose salaries are between 20,000 and 50,000, including both boundary values.
BETWEEN is useful for filtering salary ranges, dates, prices, and other numeric or comparable values.
24. What is the LIKE operator in SQL?
The LIKE operator searches for text values that match a specified pattern.
It commonly uses two wildcard characters:
- % matches zero or more characters.
- _ matches exactly one character.
Example:
SELECT *
FROM Employees
WHERE Name LIKE 'A%';
This query retrieves names that begin with the letter A.
Another example:
SELECT *
FROM Employees
WHERE Name LIKE '_a%';
This searches for names whose second character is a.
Pattern matching and case sensitivity depend on the database system and collation settings.
25. What are SQL constraints?
Constraints are rules applied to table columns or combinations of columns to maintain data accuracy and integrity.
Important SQL constraints include:
- NOT NULL prevents a column from storing NULL values.
- UNIQUE prevents duplicate constrained values.
- PRIMARY KEY uniquely identifies records.
- FOREIGN KEY maintains relationships between tables.
- CHECK enforces a specified condition.
- DEFAULT supplies a value when an insert does not provide one.
Example:
CREATE TABLE Employees (
Employee_ID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Email VARCHAR(150) UNIQUE,
Age INT CHECK (Age >= 18),
Status VARCHAR(20) DEFAULT 'Active'
);
Constraints help prevent invalid data from entering the database.
26. What is the DEFAULT constraint in SQL?
The DEFAULT constraint specifies a value that is used when an INSERT statement does not provide a value for the corresponding column.
Example:
CREATE TABLE Employees (
Employee_ID INT PRIMARY KEY,
Name VARCHAR(100),
Status VARCHAR(20) DEFAULT 'Active'
);
If an employee is inserted without specifying Status, the database uses the default value where the column definition and insert statement permit it.
27. What is the CHECK constraint in SQL?
A CHECK constraint ensures that values satisfy a specified condition.
Example:
CREATE TABLE Students (
Student_ID INT PRIMARY KEY,
Age INT CHECK (Age >= 18)
);
This constraint prevents records from being inserted or updated with an age below 18, subject to the database system's constraint semantics.
CHECK constraints are useful for enforcing basic business rules at the database level.
3. SQL Query Interview Questions: Joins and Aggregate Functions
28. What is a JOIN in SQL?
A JOIN combines related rows from two or more tables using a specified relationship or condition.
For example, an Employees table may contain employee details, while a Departments table stores department information.
A JOIN can retrieve employee names along with their corresponding department names without storing the same department details repeatedly in every employee record.
SQL supports several join types, including INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN.
29. What is an INNER JOIN?
INNER JOIN returns rows where the join condition matches records in both tables.
Example:
SELECT
Employees.Name,
Departments.Department_Name
FROM Employees
INNER JOIN Departments
ON Employees.Department_ID =
Departments.Department_ID;
This query returns employees who have a matching department record.
Employees without a matching department are excluded from the result.
30. What is a LEFT JOIN in SQL?
LEFT JOIN returns all rows from the left table and matching rows from the right table.
When no matching record exists in the right table, its selected columns contain NULL.
Example:
SELECT
Employees.Name,
Departments.Department_Name
FROM Employees
LEFT JOIN Departments
ON Employees.Department_ID =
Departments.Department_ID;
This query returns every employee, including those who do not have a matching department.
31. What is a RIGHT JOIN in SQL?
RIGHT JOIN returns all rows from the right table and matching rows from the left table.
When no matching record exists in the left table, the corresponding left-side columns contain NULL.
Example:
SELECT
Employees.Name,
Departments.Department_Name
FROM Employees
RIGHT JOIN Departments
ON Employees.Department_ID =
Departments.Department_ID;
This query returns all departments, including departments that currently have no matching employees.
32. What is a FULL OUTER JOIN?
FULL OUTER JOIN returns matching rows from both tables along with unmatched rows from either side.
When a row has no matching record in the other table, the missing side contains NULL values.
Example:
SELECT
Employees.Name,
Departments.Department_Name
FROM Employees
FULL OUTER JOIN Departments
ON Employees.Department_ID =
Departments.Department_ID;
This join is useful when comparing two datasets and identifying matching as well as unmatched records.
Not all database systems support FULL OUTER JOIN directly. In such systems, an equivalent result may be constructed using other operations.
33. What is a SELF JOIN in SQL?
A SELF JOIN is a join in which a table is joined with itself.
It is useful when records in the same table have relationships with other records in that table.
For example, an employee table may contain both employee IDs and manager IDs.
SELECT
E.Name AS Employee,
M.Name AS Manager
FROM Employees E
LEFT JOIN Employees M
ON E.Manager_ID = M.Employee_ID;
This query displays employee names along with their corresponding manager names.
34. What is a CROSS JOIN in SQL?
A CROSS JOIN produces the Cartesian product of two tables.
Every row from the first table is combined with every row from the second table.
Example:
SELECT
Students.Name,
Courses.Course_Name
FROM Students
CROSS JOIN Courses;
If the first table contains three records and the second contains four records, the result contains twelve combinations.
CROSS JOIN is useful when all possible combinations between two datasets are required.
35. What is the difference between INNER JOIN and LEFT JOIN?
The main difference is how unmatched records are handled.
| INNER JOIN | LEFT JOIN |
|---|---|
| Returns matching records from both tables. | Returns all records from the left table. |
| Excludes unmatched left-side records. | Includes unmatched left-side records. |
| Excludes unmatched right-side records. | Includes matching right-side records where available. |
| Useful when matching records are required. | Useful when all records from one table must be retained. |
Understanding joins is essential because real-world databases commonly divide information across multiple related tables.
36. What are aggregate functions in SQL?
Aggregate functions perform calculations on a set of rows and return a single result for each group or for the entire result set.
Common aggregate functions include:
| Function | Purpose |
|---|---|
| COUNT() | Counts rows or non-NULL expression values, depending on the argument. |
| SUM() | Calculates the total of numeric values. |
| AVG() | Calculates the average of numeric values. |
| MIN() | Returns the minimum value. |
| MAX() | Returns the maximum value. |
Example:
SELECT
COUNT(*) AS Total_Employees,
AVG(Salary) AS Average_Salary,
MAX(Salary) AS Highest_Salary
FROM Employees;
Aggregate functions are frequently used in reports, dashboards, and business analysis.
37. What is the GROUP BY clause in SQL?
GROUP BY groups rows that share the same values in one or more columns. It is commonly used with aggregate functions to calculate summaries.
Example:
SELECT
Department_ID,
COUNT(*) AS Employee_Count
FROM Employees
GROUP BY Department_ID;
This query counts the employees in each department.
GROUP BY is especially useful for department-wise reports, sales summaries, and category-based analysis.
38. What is the difference between COUNT(*) and COUNT(column_name)?
Both functions count values, but they treat NULL values differently.
- COUNT(*) counts all rows in the result.
- COUNT(column_name) counts only rows where the specified column is not NULL.
- COUNT(DISTINCT column_name) counts distinct non-NULL values.
Example:
SELECT
COUNT(*) AS Total_Rows,
COUNT(Email) AS Available_Emails
FROM Employees;
If some employee records have NULL email values, the second count will be smaller than the first.
39. What is the UNION operator in SQL?
UNION combines the results of two or more SELECT queries into a single result set and removes duplicate rows.
The participating queries must return the same number of columns, with compatible data types in corresponding positions.
Example:
SELECT Name FROM Current_Employees
UNION
SELECT Name FROM Former_Employees;
This query combines employee names from both tables without retaining duplicate result rows.
40. What is the difference between UNION and UNION ALL?
Both operators combine results from multiple SELECT statements, but their duplicate-handling behaviour differs.
| UNION | UNION ALL |
|---|---|
| Removes duplicate result rows. | Retains duplicate result rows. |
| Performs duplicate elimination. | Does not perform duplicate elimination. |
| May require additional processing. | Often requires less processing. |
| Useful when unique results are required. | Useful when all source records must be retained. |
Choose the operator based on whether duplicates are meaningful for the required result.
4. SQL Database Interview Questions: Subqueries, Keys and Normalization
41. What is a subquery in SQL?
A subquery is a query written inside another SQL statement.
It is used when the result of one query is required as an input to another query.
Example:
SELECT *
FROM Employees
WHERE Salary > (
SELECT AVG(Salary)
FROM Employees
);
The inner query calculates the average salary, while the outer query retrieves employees earning more than that average.
Subqueries are useful for solving problems involving comparisons, filtering, and conditional data retrieval.
42. What is a correlated subquery?
A correlated subquery is a subquery that references columns from the outer query. It is logically evaluated in relation to each applicable outer row, although the database optimizer may transform its execution.
Example:
SELECT E1.Name, E1.Salary
FROM Employees E1
WHERE E1.Salary > (
SELECT AVG(E2.Salary)
FROM Employees E2
WHERE E2.Department_ID =
E1.Department_ID
);
This query returns employees whose salary is higher than the average salary of their own department.
Correlated subqueries are useful for comparisons involving related groups of records.
43. What is the difference between a subquery and a JOIN?
Both are used to retrieve information from related data, but their query structures and use cases differ.
| Subquery | JOIN |
|---|---|
| Places one query inside another query. | Combines rows from multiple tables. |
| Useful for filtering based on another query's result. | Useful for retrieving related columns from multiple tables. |
| Can return a scalar, row, or table-like result depending on its context. | Returns combined rows based on the join condition. |
| May be correlated or non-correlated. | Uses explicit table relationships or matching conditions. |
The best approach depends on the problem, database design, and query execution plan.
44. What are the different types of keys in SQL?
Keys help identify records and establish relationships between tables.
Important database keys include:
- Primary key: Uniquely identifies each record in a table.
- Foreign key: References a candidate key in another or the same table.
- Candidate key: A minimal set of columns capable of uniquely identifying a record.
- Super key: Any set of columns that uniquely identifies a record.
- Composite key: A key formed using multiple columns.
- Alternate key: A candidate key that is not selected as the primary key.
Understanding database keys is essential when designing relational database structures.
45. What is a composite key in SQL?
A composite key is a key formed by combining two or more columns to uniquely identify a record.
For example, a student can enrol in multiple courses, and a course can have multiple students. A combination of Student_ID and Course_ID can identify each enrolment record.
CREATE TABLE Enrollments (
Student_ID INT,
Course_ID INT,
Enrollment_Date DATE,
PRIMARY KEY (Student_ID, Course_ID)
);
The combination of the two columns prevents the same student-course pair from appearing more than once.
46. What is database normalization?
Database normalization is the process of organising relational tables to reduce unnecessary data duplication and improve data integrity.
It involves dividing information into appropriately structured tables and establishing relationships between them.
For example, instead of repeating department information in every employee record, a database can store departments in a separate table and reference them using Department_ID.
Normalization helps make database updates more consistent and reduces common insertion, update, and deletion anomalies.
47. What are the different normal forms in SQL?
Normal forms are guidelines used in relational database design to improve data organisation.
| Normal Form | Description |
|---|---|
| First Normal Form (1NF) | Requires values in each column to be atomic according to the chosen relational model and avoids repeating groups. |
| Second Normal Form (2NF) | Must satisfy 1NF and remove partial dependencies of non-key attributes on candidate keys. |
| Third Normal Form (3NF) | Must satisfy 2NF and eliminate inappropriate transitive dependencies of non-key attributes on candidate keys. |
| Boyce-Codd Normal Form (BCNF) | Requires every determinant of a non-trivial functional dependency to be a super key. |
These normal forms help developers design relational databases with fewer unnecessary dependencies.
48. What is denormalization in SQL?
Denormalization is the intentional introduction of controlled redundancy into a database to improve particular query performance or simplify data retrieval.
For example, a reporting system may store certain summary values to avoid repeatedly calculating them from multiple related tables.
However, denormalization can increase storage requirements and create additional data-maintenance responsibilities.
It should be considered after understanding query performance and the application's data consistency requirements.
49. What is an index in SQL?
An index is a database structure that helps the database locate records more efficiently without necessarily scanning every row in a table.
For example:
CREATE INDEX idx_employee_name
ON Employees(Name);
This creates an index on the Name column.
Indexes can improve filtering, sorting, and joining performance when designed appropriately. However, they require additional storage and can increase the cost of INSERT, UPDATE, and DELETE operations.
50. What is a view in SQL?
A view is a named database query that presents data from one or more underlying tables as a virtual table.
Example:
CREATE VIEW HighSalaryEmployees AS
SELECT Employee_ID, Name, Salary
FROM Employees
WHERE Salary > 50000;
To retrieve the view's records:
SELECT *
FROM HighSalaryEmployees;
Views help simplify complex queries, provide controlled access to selected data, and improve query organisation.
51. What is a stored procedure in SQL?
A stored procedure is a named collection of SQL statements and procedural logic stored in a database system.
Stored procedures can accept parameters, perform multiple operations, and return results or output values depending on the database platform.
They are commonly used for reusable business operations, data processing, and database-side workflows.
The syntax and supported procedural features vary significantly across MySQL, SQL Server, Oracle, and PostgreSQL.
52. What is a trigger in SQL?
A trigger is a database object that automatically executes specified logic when particular events occur on a table or other supported database object.
Common trigger events include INSERT, UPDATE, and DELETE operations.
Triggers can be used for auditing, maintaining related information, and enforcing selected business rules.
However, they should be designed carefully because automatic execution can make database behaviour harder to understand and debug.
5. Advanced SQL Technical Interview Questions
53. What are SQL transactions?
A transaction is a logical unit of database operations that should be completed according to defined consistency rules.
For example, transferring money between two bank accounts involves deducting money from one account and adding it to another. Both operations should succeed together or be rolled back according to the transaction design.
Example:
BEGIN TRANSACTION;
UPDATE Accounts
SET Balance = Balance - 1000
WHERE Account_ID = 101;
UPDATE Accounts
SET Balance = Balance + 1000
WHERE Account_ID = 102;
COMMIT;
The exact transaction-start syntax varies by database system. If an operation fails, an application may use ROLLBACK instead of committing the transaction.
54. What are the ACID properties in SQL?
ACID represents four important properties that help maintain reliable database transactions.
- Atomicity: A transaction is treated as an indivisible unit of work, so incomplete operations are not committed as successful transactions.
- Consistency: A transaction should preserve defined database integrity rules.
- Isolation: Concurrent transactions are controlled so that their interactions follow the database's isolation rules.
- Durability: Once a transaction is committed, its changes are expected to survive failures according to the database's durability guarantees.
These properties are particularly important in banking, payment processing, inventory systems, and other applications where data accuracy matters.
55. What is the difference between COMMIT and ROLLBACK?
Both commands are used to manage transaction changes.
| COMMIT | ROLLBACK |
|---|---|
| Makes the transaction's changes permanent. | Undoes uncommitted changes within the applicable transaction scope. |
| Ends the current transaction in common transaction models. | Returns the transaction to its previous state or a savepoint. |
| Used when operations complete successfully. | Used when operations need to be cancelled. |
Example:
BEGIN TRANSACTION;
UPDATE Employees
SET Salary = 50000
WHERE Employee_ID = 101;
ROLLBACK;
The salary update is rolled back instead of being committed.
Transaction behaviour and supported syntax depend on the database system and storage engine.
56. What is a SAVEPOINT in SQL?
A SAVEPOINT marks a position within a transaction so that a partial rollback can be performed without necessarily cancelling the entire transaction.
Example:
BEGIN TRANSACTION;
UPDATE Employees
SET Salary = 50000
WHERE Employee_ID = 101;
SAVEPOINT salary_update;
UPDATE Employees
SET Salary = 60000
WHERE Employee_ID = 102;
ROLLBACK TO SAVEPOINT salary_update;
COMMIT;
The second update is undone, while the first update remains part of the committed transaction.
Savepoint syntax and behaviour vary between database systems.
57. What is a deadlock in SQL?
A deadlock occurs when two or more transactions wait for resources held by one another, preventing them from progressing.
For example, one transaction may lock the first account and wait for the second account, while another transaction holds the second account and waits for the first.
Database systems generally detect deadlocks and resolve them by terminating or rolling back one of the participating transactions.
Developers can reduce deadlock risks by maintaining consistent resource-access order, keeping transactions short, and designing appropriate indexes.
58. What is a Common Table Expression (CTE) in SQL?
A Common Table Expression is a named temporary result set defined using the WITH clause and referenced within a single SQL statement.
Example:
WITH DepartmentSalary AS (
SELECT
Department_ID,
AVG(Salary) AS Average_Salary
FROM Employees
GROUP BY Department_ID
)
SELECT *
FROM DepartmentSalary
WHERE Average_Salary > 40000;
CTEs help break complicated queries into smaller, understandable sections.
Recursive CTEs can also be used for hierarchical data and tree-like relationships in database systems that support them.
59. What is a window function in SQL?
A window function performs calculations across a related set of rows while retaining individual result rows.
Unlike a regular aggregate query with GROUP BY, a window function does not necessarily combine multiple rows into a single grouped row.
Example:
SELECT
Name,
Department_ID,
Salary,
RANK() OVER (
PARTITION BY Department_ID
ORDER BY Salary DESC
) AS Salary_Rank
FROM Employees;
This query assigns salary rankings within each department.
Window functions are useful for ranking, running totals, moving averages, and analytical reporting.
60. What is the difference between ROW_NUMBER(), RANK(), and DENSE_RANK()?
These are SQL ranking window functions used to assign positions to rows based on a specified ordering.
| Function | Behaviour |
|---|---|
| ROW_NUMBER() | Assigns a unique sequential number to every row. |
| RANK() | Assigns the same rank to tied values and leaves gaps in subsequent ranks. |
| DENSE_RANK() | Assigns the same rank to tied values without leaving gaps. |
For example, consider salary values of 50,000, 50,000, and 40,000.
| Salary | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 50,000 | 1 | 1 | 1 |
| 50,000 | 2 | 1 | 1 |
| 40,000 | 3 | 3 | 2 |
These functions are frequently used in employee rankings, sales reports, and analytical queries.
6. SQL Query Interview Questions: Practical Coding Examples
Practical SQL questions help interviewers evaluate whether candidates can convert business requirements into correct database queries.
For the following examples, assume an Employees table with these columns:
Employee_ID, Name, Department_ID, Salary, and Joining_Date.
61. How do you retrieve all records from a table?
Use the SELECT statement with the wildcard character.
SELECT *
FROM Employees;
This query retrieves every column and row from the Employees table.
62. How do you retrieve employees whose salary is greater than 30,000?
Use the WHERE clause to filter records.
SELECT *
FROM Employees
WHERE Salary > 30000;
This query returns employees earning more than 30,000.
63. How do you find the highest salary in a table?
Use the MAX() aggregate function.
SELECT MAX(Salary) AS Highest_Salary
FROM Employees;
This query returns the highest non-NULL salary value.
64. How do you find the second-highest salary in SQL?
A subquery with DISTINCT and MAX can retrieve the second-highest distinct salary.
SELECT MAX(Salary) AS Second_Highest_Salary
FROM Employees
WHERE Salary < (
SELECT MAX(Salary)
FROM Employees
);
The inner query identifies the highest salary, while the outer query finds the highest salary below that value.
This approach handles duplicate salary values by returning the second-highest distinct salary.
65. How do you find duplicate records in a table?
Use GROUP BY and HAVING to identify values that occur more than once.
SELECT
Name,
COUNT(*) AS Duplicate_Count
FROM Employees
GROUP BY Name
HAVING COUNT(*) > 1;
This query identifies names that appear multiple times.
For real database cleanup, identify duplicates using the appropriate business key rather than relying only on employee names.
66. How do you count the total number of employees?
Use the COUNT() aggregate function.
SELECT COUNT(*) AS Total_Employees
FROM Employees;
This query returns the total number of employee records.
67. How do you find the average salary of employees?
Use AVG() to calculate the average of non-NULL salary values.
SELECT AVG(Salary) AS Average_Salary
FROM Employees;
This query returns the average salary across the employee records.
68. How do you retrieve employees department-wise?
Use GROUP BY to organise employees according to their department.
SELECT
Department_ID,
COUNT(*) AS Employee_Count
FROM Employees
GROUP BY Department_ID;
This query calculates the number of employees in each department.
69. How do you find employees who joined after a specific date?
Use the WHERE clause with a date comparison.
SELECT *
FROM Employees
WHERE Joining_Date > '2025-01-01';
This query retrieves employees who joined after 1 January 2025.
Date literal formats and conversion rules should be checked for the target database system.
70. How do you retrieve the top five highest-paid employees?
Use ORDER BY and a row-limiting clause.
SELECT *
FROM Employees
ORDER BY Salary DESC
FETCH FIRST 5 ROWS ONLY;
This syntax is supported by several database systems, including PostgreSQL and Oracle. MySQL and SQL Server use different row-limiting syntax.
To return exactly five employees consistently when salaries are tied, include a unique secondary sort column such as Employee_ID.
7. How to Prepare for an SQL Technical Interview
Preparing for an SQL interview requires a combination of theoretical understanding, query-writing practice, and database problem-solving skills.
Build a strong foundation in database concepts. Start with databases, DBMS, RDBMS, tables, rows, columns, data types, and relationships. Understand how relational databases organise information and why proper database design matters.
Practise essential SQL commands. Learn SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, and TRUNCATE. Practise filtering records using WHERE, sorting results using ORDER BY, and removing duplicate results using DISTINCT.
Understand joins thoroughly. Practise INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, SELF JOIN, and CROSS JOIN. Use sample tables to understand how matching and unmatched records appear in query results.
Learn aggregate functions and grouping. Understand COUNT, SUM, AVG, MIN, MAX, GROUP BY, and HAVING. These concepts are especially important when solving reporting and data analysis problems.
Study subqueries and database relationships. Practise nested queries, correlated subqueries, primary keys, foreign keys, composite keys, and normalization. Understanding relationships makes it easier to design and query real-world databases.
Explore advanced SQL concepts. Learn indexes, views, stored procedures, triggers, transactions, ACID properties, CTEs, and window functions. These topics help candidates prepare for more challenging technical interview rounds.
Solve practical query problems. Work on employee salary calculations, duplicate identification, department-wise reports, date filtering, ranking, and customer transaction queries.
Practise with real database systems. Use MySQL, PostgreSQL, or SQL Server to create tables, insert sample data, execute queries, and understand query results. Practical experience is more valuable than memorising SQL definitions alone.
Students interested in structured programming education and practical technical preparation can explore the training opportunities offered by Well Spring Talent Solutions as part of their journey towards software development and database-related careers.
8. Common Mistakes Freshers Should Avoid in SQL Interviews
Many freshers understand basic SQL syntax but struggle when interviewers introduce multiple tables, NULL values, grouping conditions, or more complex database requirements.
One common mistake is confusing WHERE and HAVING. Remember that WHERE filters individual rows, while HAVING filters groups after aggregation.
Another mistake is using = to compare a column with NULL. SQL uses three-valued logic, so NULL comparisons should be handled using IS NULL or IS NOT NULL.
Candidates should also avoid assuming that UNION and UNION ALL behave identically. UNION removes duplicate result rows, whereas UNION ALL retains them.
Incorrect JOIN conditions can produce duplicate records or unexpected results. Always understand the relationship between the tables and check whether the join key is unique on either side.
Do not confuse primary keys with foreign keys. A primary key identifies a record, while a foreign key establishes a relationship with a referenced key.
Another important area is transaction management. Freshers should understand when COMMIT and ROLLBACK are used and why the ACID properties matter for data consistency.
Finally, avoid writing queries without considering performance. Selecting unnecessary columns, creating excessive indexes, and using inefficient filtering conditions can affect database performance. Practise reading query execution plans as your SQL knowledge develops.
Frequently Asked Questions About SQL Interviews
1. Which SQL interview questions are commonly asked for freshers?
Freshers are commonly asked about SQL commands, database concepts, primary keys, foreign keys, constraints, joins, aggregate functions, subqueries, and normalization. Interviewers may also provide practical query-writing problems involving employee records, duplicate values, salary calculations, and department-wise reports.
2. How should beginners prepare for SQL interviews?
Beginners should start with database fundamentals, SQL syntax, SELECT queries, filtering, sorting, and data manipulation. They should gradually learn joins, grouping, subqueries, constraints, and database normalization while practising queries using MySQL or PostgreSQL.
3. Is SQL difficult for freshers to learn?
SQL is generally approachable for beginners because its basic commands use readable, structured syntax. However, understanding joins, subqueries, window functions, transactions, and query optimisation requires regular practice and a clear understanding of relational database concepts.
4. What are the most important SQL topics for technical interviews?
Important topics include SELECT statements, WHERE, ORDER BY, GROUP BY, HAVING, joins, primary keys, foreign keys, constraints, subqueries, aggregate functions, indexes, normalization, and transactions. Freshers should also practise writing SQL queries independently.
5. Do SQL interviews include practical query-writing questions?
Yes. Many SQL technical interviews include practical exercises such as finding the second-highest salary, identifying duplicate records, calculating average salaries, joining multiple tables, and retrieving department-wise employee information.
6. Which database should freshers learn for SQL interview preparation?
MySQL and PostgreSQL are useful choices for beginners because they provide relational database features and practical environments for learning SQL. Candidates should also understand that SQL syntax and database-specific features can vary across different database platforms.
7. How can freshers improve their confidence in SQL technical interviews?
Freshers can improve their confidence by practising daily SQL queries, creating sample databases, solving real-world data problems, and participating in mock technical interviews. Understanding how each query works and explaining the reasoning behind it are important for performing well in interviews.
Conclusion
SQL is an essential technology for managing structured information and building reliable database-driven applications. Understanding database fundamentals, SQL commands, constraints, joins, aggregate functions, subqueries, normalization, and transactions provides a strong foundation for aspiring software developers and database professionals.
These SQL Interview Questions and Answers for Freshers offer a structured preparation resource covering beginner concepts, intermediate database operations, advanced SQL topics, and practical query-writing exercises.
Instead of memorising every answer, practise writing queries independently, experiment with different datasets, and understand how SQL processes information. Consistent practice, database experience, and the ability to explain query logic clearly can help freshers approach SQL technical interviews with greater confidence.