Oracle SQL Interview Questions and Answers
Oracle SQL interviews usually revolve around a handful of topics. Joins, indexes, constraints, subqueries, functions, views, query optimization, and query writing show up far more often than most candidates expect. The questions may be worded differently, but the underlying concepts remain the same.
I've arranged these oracle practice questions in the order I would recommend learning and revising these topics. We’ll begin with the fundamentals, move through commonly asked Oracle SQL concepts, and then work into practical query-based questions. As you go through the answers, focus on understanding the logic behind them.
So, let’s get started!
Constraints, Keys, Views & Sequences
1. What Is a Sequence in Oracle and Where Is It Used?
Suppose a company is adding hundreds of new employees every month. Manually assigning employee IDs would be slow and could easily lead to duplicate values.
This is where sequences become useful.
A sequence is a database object that automatically generates unique numeric values. It is used for columns such as employee IDs, order IDs, invoice numbers, and customer IDs.
For example, the following sequence starts at 1001 and increases by 1 each time a new value is requested:
CREATE SEQUENCE employee_seq
START WITH 1001
INCREMENT BY 1;To generate the next value:
SELECT employee_seq.NEXTVAL
FROM dual;Output:
1001
The next time the query runs, Oracle returns:
1002
and so on.
Sequences are used whenever a table needs automatically generated unique values. They help eliminate manual ID management and reduce the risk of duplicate records.
Concepts like keys, constraints, and sequences are often discussed in DBMS interview questions because they focus on how data is managed and maintained inside a database.
2. What Are Constraints in Oracle SQL?
Imagine an employee table where someone accidentally enters a negative salary, leaves an employee ID blank, or assigns the same employee ID to two different employees.
The database has no way of knowing these values are wrong unless we tell it what rules to follow. This is why constraints are used.
Oracle SQL Constraints are rules applied to table columns to ensure that only valid data is stored in the database. They help maintain data accuracy and prevent users from inserting, updating, or deleting data in a way that could create inconsistencies.
Some commonly used constraints in Oracle SQL include:
-
PRIMARY KEY- Ensures that each record has a unique identifier. -
FOREIGN KEY- Maintains relationships between tables. -
UNIQUE- Prevents duplicate values in a column. -
NOT NULL- Ensures a column cannot containNULLvalues. -
CHECK- Restricts values based on a specified condition.
Without constraints, a database can quickly become unreliable because incorrect or duplicate data can be stored without any restrictions.
3. What Is the Difference Between Primary Key and Unique Key?
This is one of the most common points of confusion in SQL interviews because both keys prevent duplicate values.
The easiest way to remember the difference is that a primary key identifies a record, while a unique key prevents duplicate values.
| Feature | Primary Key | Unique Key |
|---|---|---|
| Allows duplicate values | No | No |
Allows NULL values |
No | Yes (Oracle allows multiple NULLs) |
| Number allowed per table | Only 1 | Multiple |
| Purpose | Uniquely identifies each record | Ensures values remain unique |
For example, consider an employee table:
CREATE TABLE employees (
employee_id NUMBER PRIMARY KEY,
email VARCHAR2(100) UNIQUE
);Here:
- employee_id is the primary key because every employee must have a unique ID, and it cannot be
NULL. - An email is a unique key because duplicate email addresses are not allowed, but it does not serve as the main identifier for the table.
A quick interview tip: if you're asked which one is more important, the answer is usually the primary key because it uniquely identifies each row in the table, while a unique key is mainly used to enforce uniqueness on other columns.
4. What Is the Difference Between Primary Key and Foreign Key?
In the previous question, we saw that a primary key is used to uniquely identify each record in a table. Understanding the difference between a primary key and a foreign key in Oracle is important because both serve very different purposes.
Instead of identifying records, a foreign key is used to create a relationship between two tables.
For example, consider the following tables:
Departments
| department_id | department_name |
|---|---|
| 10 | HR |
| 20 | Finance |
Employees
| employee_id | employee_name | department_id |
|---|---|---|
| 101 | Rahul Sharma | 10 |
| 102 | Priya Patel | 20 |
Here:
- department_id in the Departments table is the primary key because it uniquely identifies each department.
- department_id in the Employees table is the foreign key because it references the Departments table.
Some key features of a foreign key are:
- It can contain duplicate values.
- It can contain
NULLvalues (unless restricted). - Its purpose is to maintain relationships between tables.
- It prevents invalid references from being inserted into the child table.
5. What Is a View in Oracle SQL and Why Is It Used?
Imagine an HR team that only needs employee names, departments, and salaries for reporting purposes. Giving them access to the entire employee table might expose information they don't need, such as email addresses, personal details, or internal IDs.
A view helps solve this problem.
A view is a saved SQL query that presents data from one or more tables as if it were a separate table. The data itself is not stored in the view; Oracle fetches it from the underlying tables whenever the view is queried.
For example:
CREATE VIEW employee_summary AS
SELECT employee_name, department_id, salary
FROM employees;Once created, the view can be queried just like a regular table:
SELECT * FROM employee_summary;Views are used to:
- Restrict access to sensitive data.
- Simplify complex queries.
- Present data in a format that is easier for users to work with.
- Provide a consistent layer between applications and database tables.
Learn via our Video Courses
Joins, Set Operators & Subqueries
1. What Is the Difference Between INNER JOIN and LEFT JOIN?
The difference comes down to one question: What should happen when a matching record doesn't exist?
-
INNER JOINreturns only the records that have a match in both tables. -
LEFT JOINreturns all records from the left table, even if no matching record exists in the right table.
Suppose we have an employees table and a departments table. Not every employee has been assigned a department yet.
INNER JOIN
SELECT e.employee_name, d.department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id;This query returns only employees who have a matching department.
LEFT JOIN
SELECT e.employee_name, d.department_name
FROM employees e
LEFT JOIN departments d
ON e.department_id = d.department_id;This query returns all employees. If an employee has not been assigned a department, the department_name column will contain NULL.
A simple way to remember it is this:
- Use
INNER JOINwhen you only care about matching records. - Use
LEFT JOINwhen you want to keep all records from the left table, regardless of whether a match exists.
2. What Are the Different Types of Joins in Oracle SQL?
Joins are used when related data is stored across multiple tables and needs to be retrieved together. Oracle SQL supports several types of joins, each serving a different purpose:
-
INNER JOIN- Returns only the rows that have matching values in both tables. -
LEFT JOIN- Returns all rows from the left table, along with matching rows from the right table. If no match exists,NULLvalues are returned for the right table. -
RIGHT JOIN- Returns all rows from the right table, along with matching rows from the left table. If no match exists,NULLvalues are returned for the left table. -
FULL OUTER JOIN- Returns all matching and non-matching rows from both tables. -
SELF JOIN- Joins a table with itself. This is used for hierarchical data, such as employee-manager relationships. -
CROSS JOIN- Returns every possible combination of rows from both tables.
For example, if employee details are stored in one table and department details are stored in another, a join can be used to bring the related information together in a single result.
In fact, this is one of the main reasons joins in Oracle SQL are used so extensively. The more tables a database has, the harder it becomes to answer questions without connecting data from multiple sources.
3. What Is a Self Join? Give an Example Use Case.
A self join is a join where a table is joined with itself. It is useful when the related information you need already exists within the same table.
A common example is an employee-manager hierarchy.
Suppose an employee's table contains both employee details and the ID of the employee's manager:
| employee_id | employee_name | manager_id |
|---|---|---|
| 101 | Rahul Sharma | 105 |
| 102 | Priya Patel | 105 |
| 105 | Aman Khanna | NULL |
To display each employee along with their manager's name, the table needs to be joined with itself:
SELECT e.employee_name AS employee,
m.employee_name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.employee_id;Output:
| Employee | Manager |
|---|---|
| Rahul Sharma | Aman Khanna |
| Priya Patel | Aman Khanna |
| Aman Khanna | NULL |
Notice that the employees table appears twice in the query. One copy (e) represents employees, while the other (m) represents managers. This is what makes it a self join.
4. What Is the Difference Between UNION and UNION ALL?
Both UNION and UNION ALL are used to combine the results of two or more SELECT statements. The difference is what happens when duplicate records are found.
-
UNIONremoves duplicate rows from the final result. -
UNION ALLkeeps all rows, including duplicates.
Suppose two queries return the following employee names:
Query 1 Result
| employee_name |
|---|
| Rahul Sharma |
| Priya Patel |
| Aman Khanna |
Query 2 Result
| employee_name |
|---|
| Aman Khanna |
| Neha Gupta |
| Pooja Shah |
Using UNION:
SELECT employee_name FROM table1
UNION
SELECT employee_name FROM table2;Output:
| employee_name |
|---|
| Rahul Sharma |
| Priya Patel |
| Aman Khanna |
| Neha Gupta |
| Pooja Shah |
Using UNION ALL:
SELECT employee_name FROM table1
UNION ALL
SELECT employee_name FROM table2;Output:
| employee_name |
|---|
| Rahul Sharma |
| Priya Patel |
| Aman Khanna |
| Aman Khanna |
| Neha Gupta |
| Pooja Shah |
Notice that Aman Khanna appears only once with UNION but twice with UNION ALL.
As a result, UNION ALL is usually faster because Oracle does not have to spend extra time identifying and removing duplicate records.
Oracle SQL Basics Interview Questions
1. What are the different types of SQL commands in Oracle?
Oracle SQL commands are grouped based on the task they perform. Some commands define database objects, some work with data, while others manage transactions and user access.
| What are you working with? | SQL Command Type | Common Commands |
|---|---|---|
| Database structure: tables, views, and indexes | DDL - Data Definition Language |
CREATE, ALTER, DROP, TRUNCATE
|
| Data stored in tables | DML - Data Manipulation Language |
INSERT, UPDATE, DELETE, MERGE
|
| Retrieving data | DQL - Data Query Language | SELECT |
| User permissions and access | DCL - Data Control Language |
GRANT, REVOKE
|
| Transactions | TCL (Transaction Control Language) |
COMMIT, ROLLBACK, SAVEPOINT
|
For example, if you create a new table using CREATE TABLE, you are using a DDL command. If you add a new employee record using INSERT, it falls under DML. Similarly, SELECT is a DQL command because it retrieves data without modifying it.
It is especially a good thing to understand these categories well, as databases grow larger because different commands serve different purposes. You'll come across the same classifications in most DBMS concepts as well, especially when learning about database structure, transactions, and user access control.
2. What is the difference between WHERE and HAVING clauses?
The WHERE clause filters rows before they are grouped, while the HAVING clause filters the grouped results.
For example, the following query returns employees whose salary is greater than 50,000:
SELECT *
FROM employees
WHERE salary > 50000;Here, the condition is applied to each row in the table.
Now consider:
SELECT department_id, AVG(salary)
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 50000;Now here, Oracle will first group the employees by department, calculate the average salary for each group, and then apply the condition.
Remember! The major difference between them is that WHERE works on rows, whereas HAVING works on aggregated results.
3. What is the difference between DELETE, TRUNCATE, and DROP in Oracle SQL?
DELETE, TRUNCATE, and DROP are all used to remove data, but they affect the database in different ways.
| Command | What happens? | Can a WHERE clause be used? |
|---|---|---|
DELETE |
Removes selected rows from a table | Yes |
TRUNCATE |
Removes all rows from a table but keeps the table structure | No |
DROP |
Removes both the table and its data permanently | No |
For example, if an employee's table contains 1,000 records:
-
DELETEcan remove specific records, such as employees belonging to a particular department. -
TRUNCATEremoves all 1,000 records at once but leaves the employees table available for future use. -
DROPremoves the entire employees table, including its structure, indexes, and data.
Another important difference is transaction control. A DELETE operation can be rolled back before a COMMIT, whereas TRUNCATE and DROP cannot be rolled back once executed.
This is one of those oracle sql questions that sounds straightforward at first, but interviewers often use it to check whether you understand the impact each command has on the database.
4. What is the difference between CHAR and VARCHAR2 in Oracle?
Both CHAR and VARCHAR2 are used to store character data, but they handle storage differently.
A CHAR column has a fixed length. If a column is defined as CHAR(10) and the value 'John' is stored, Oracle automatically adds spaces to fill the remaining characters.
A VARCHAR2 column has a variable length. If a column is defined as VARCHAR2(10) and the value 'John' is stored, Oracle only stores the four characters entered.
For example:
-
CHAR(10)storing 'John' → 'John ' -
VARCHAR2(10)storing 'John' → 'John'
Because of this behavior, CHAR is generally used for values that always have a fixed length, such as country codes or status flags. VARCHAR2 is preferred for names, addresses, and other data where the length can vary from one record to another.
5. What is NULL in Oracle SQL, and how is it different from zero or blank?
In Oracle SQL, NULL represents the absence of a value. It does not mean zero, an empty string, or a space; it simply indicates that no value is currently stored.
NULL-related scenarios frequently appear in SQL interview questions because a query can be syntactically correct yet return incorrect results if NULL values aren't handled properly.
For example, consider an employee's commission:
| Employee | Commission |
|---|---|
| John | 500 |
| Sarah | 0 |
| Mike | NULL |
In this case:
- 500 means the employee received a commission.
- 0 means the commission value is known and equals zero.
-
NULLmeans the commission is unknown or has not been recorded.
The same applies to text values. A blank string ('') and NULL are treated differently conceptually, although Oracle stores empty strings as NULL in character columns.
Because NULL represents a missing value, it cannot be compared using the equals (=) operator. Instead, Oracle provides the IS NULL and IS NOT NULL conditions:
SELECT employee_name
FROM employees
WHERE commission_pct IS NULL;Understanding this distinction is important because calculations, comparisons, and aggregate functions often handle NULL values differently from zeros and blanks.
Oracle SQL Functions & Query Output Questions
1. What Is the Difference Between Aggregate Functions and Analytic Functions?
At first glance, aggregate and analytic functions can look similar because both perform calculations on a set of rows. Knowing the difference becomes important once you start working with SQL aggregate functions and reporting queries.
Aggregate functions return a single result for a group of rows.
For example:
SELECT department_id,
AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id;Output:
| Department ID | Avg Salary |
|---|---|
| 10 | 81667 |
| 20 | 61800 |
| 30 | 70750 |
| 40 | 52667 |
Notice that multiple employee records are combined into one result per department.
Analytic functions perform calculations across a set of rows but keep the individual rows intact.
SELECT employee_name,
department_id,
salary,
AVG(salary) OVER (PARTITION BY department_id) AS dept_avg_salary
FROM employees;Output (partial):
| Employee Name | Department ID | Salary | Dept Avg Salary |
|---|---|---|---|
| Rahul Sharma | 10 | 65000 | 81667 |
| Priya Patel | 10 | 85000 | 81667 |
| Aman Khanna | 10 | 95000 | 81667 |
Here, the average salary is calculated for each department, but every employee row is still displayed.
Even Data Analytics Interview Questions cover such topics, so you can refer to them for practice.
2. What Is the Use of NVL, NVL2, and COALESCE in Oracle SQL?
These functions are used when a column contains NULL values, and you want to control what should happen when those values appear in the output.
Suppose an employee table contains a bonus column:
| employee_name | bonus |
|---|---|
| Rahul Sharma | 5000 |
| Priya Patel | NULL |
| Aman Khanna | 8000 |
NVL
NVL() replaces a NULL value with a specified value.
SELECT employee_name,
NVL(bonus, 0) AS bonus
FROM employees;Output:
| employee_name | bonus |
|---|---|
| Rahul Sharma | 5000 |
| Priya Patel | 0 |
| Aman Khanna | 8000 |
NVL2
NVL2() lets you specify one value if the column is NOT NULL and another if it is NULL.
SELECT employee_name,
NVL2(bonus, 'Bonus Available', 'No Bonus') AS bonus_status
FROM employees;Output:
| employee_name | bonus_status |
|---|---|
| Rahul Sharma | Bonus Available |
| Priya Patel | No Bonus |
| Aman Khanna | Bonus Available |
COALESCE
COALESCE() returns the first non-NULL value from a list of expressions.
SELECT employee_name,
COALESCE(bonus, salary, 0) AS payment_value
FROM employees;If the bonus is NULL, Oracle checks the salary. If both are NULL, it returns 0.
So, remember:
-
NVL- Replace aNULLvalue. -
NVL2- Return one value forNULLand another forNOT NULL. -
COALESCE- Return the first non-NULLvalue from a list.
Questions on NVL, NVL2, and COALESCE appear regularly in Oracle SQL functions interview questions because all three deal with NULL values, but they solve the problem in slightly different ways.
3. What Is the Difference Between ROWNUM and ROWID in Oracle?
Although their names look similar, ROWNUM and ROWID serve completely different purposes in Oracle.
-
ROWNUMis a temporary number assigned to rows as Oracle returns them in a query result. -
ROWIDis the unique physical address of a row inside the database.
For example, if you want to display only the first three employees from a table, you can use ROWNUM:
SELECT *
FROM employees
WHERE ROWNUM <= 3;Here, Oracle assigns row numbers to the records as they are fetched and returns only the first three.
ROWID, on the other hand, points to the exact storage location of a row.
SELECT ROWID, employee_name
FROM employees;Output:
| ROWID | employee_name |
|---|---|
| AAAA1xAAEAAAABPAAA | Rahul Sharma |
| AAAA1xAAEAAAABPAAB | Priya Patel |
The actual ROWID values will vary from one database to another, but each row has its own unique address.
A simple way to remember the difference:
-
ROWNUM= Position of a row in a query result. -
ROWID= Physical location of a row in the database.
If an interviewer asks which one is unique, the answer is ROWID, because it uniquely identifies a row's storage location, whereas ROWNUM can change depending on the query being executed.
4. How Can You Find Duplicate Records in a Table Using Oracle SQL?
When people talk about duplicate records, they're usually referring to rows where a particular value appears more than once.
The most common approach is to group the records by the column you want to check and then filter the groups that occur multiple times.
For example, if we want to find duplicate email IDs in the employee table:
SELECT email,
COUNT(*) AS occurrence_count
FROM employees
GROUP BY email
HAVING COUNT(*) > 1;Output:
| occurrence_count | |
|---|---|
| neha@company.com | 2 |
In our dataset, both Neha Gupta and Simran Kaur share the same email address, so the query identifies it as a duplicate.
The key part of the query is the HAVING COUNT(*) > 1 condition. After the records are grouped, it filters out values that appear only once and returns only the duplicates.
Duplicate-record checks are asked during Oracle SQL query interview questions because they combine grouping, filtering, and aggregate functions in a single query.
Oracle SQL Role & Interview Expectations
1. What are the most important Oracle SQL skills for an interview?
The most important Oracle SQL skills are query writing, joins, subqueries, constraints, Oracle-specific functions, and performance optimization. You’ll see these topics emerge frequently because they test whether you can manage data effectively.
The most important Oracle SQL skills can be grouped into four broad areas:
1. Query Writing and Data Retrieval
This is usually the first area tested in an Oracle SQL interview. You should be familiar with:
-
SELECT,WHERE,GROUP BY,HAVING, andORDER BY - Joins such as
INNER JOIN,LEFT JOIN, andSELF JOIN - Subqueries and Common Table Expressions (CTEs)
- Set operators such as
UNION,UNION ALL,INTERSECT, andMINUS
2. Oracle-Specific Features
Many Oracle-focused roles will expect you to know the features that are unique to Oracle Database, including:
-
NVL(),NVL2(), andCOALESCE() -
ROWNUMandROWID - Sequences
- Views and Materialized Views
- Hierarchical queries using
CONNECT BY
3. Performance and Query Optimization
For experienced roles, interviewers often assess how efficiently you can work with large datasets.
Key topics include:
- Indexes
- Execution plans
- Query optimization techniques
- The difference between
DELETEandTRUNCATE - Oracle optimizer hints
4. Database Design and PL/SQL Basics
You should understand database design as well because it will help you prevent problems such as query stalling, running out of memory, corrupt data, etc.
Commonly tested topics include:
- Primary keys and foreign keys
- Constraints
- Stored procedures and functions
- Cursors
- Transactions and data integrity
These topics form the core of most database rounds, but they're often discussed alongside broader technical interview questions that assess problem-solving, system understanding, and practical application.
2. What is the difference between SQL and PL/SQL in Oracle?
SQL is used to query and modify data in a database using statements such as SELECT, INSERT, UPDATE, and DELETE.
PL/SQL is Oracle's procedural extension of SQL. It supports variables, loops, conditions, and exception handling and is used for stored procedures, functions, and triggers.
3. What is Oracle SQL, and how is it different from standard SQL?
Oracle SQL and standard SQL share the same fundamentals, such as querying data with SELECT, filtering records with WHERE, and grouping results with GROUP BY. The difference is that Oracle SQL adds Oracle-specific features such as NVL(), ROWNUM, ROWID, sequences, and hierarchical queries that are not part of standard SQL.
Some of these Oracle-specific features include:
-
NVL()for handlingNULLvalues -
ROWNUMfor limiting query results -
ROWIDfor uniquely identifying rows - Sequences for generating unique values
- Hierarchical queries using
CONNECT BY
Seems like a lot? Don’t worry, when you are asked this question, and you need to think of some quick points, then remember these:
| Standard SQL | Oracle SQL |
|---|---|
| Follows ANSI SQL standards | Extends ANSI SQL with Oracle-specific features |
| Focuses on portability across databases | Optimized specifically for Oracle Database |
| Uses only standard SQL syntax | Supports additional functions, pseudocolumns, and database objects |
| Queries are generally portable | Some syntax and features are Oracle-specific |
For eg, Oracle uses NVL() to replace NULL values, here is how:
SELECT NVL(commission_pct, 0)
FROM employees;Assume there’s a table of employees and it contains:
| commission_pct |
|---|
| 0.10 |
| NULL |
| 0.15 |
| NULL |
After running the syntax, the Output would be:
| NVL(commission_pct, 0) |
|---|
| 0.10 |
| 0 |
| 0.15 |
| 0 |
Here, every NULL value is replaced with 0, while the existing values remain unchanged. Functions such as NVL() are specific to Oracle SQL and are one of the reasons Oracle SQL differs from standard SQL implementations.
Oracle SQL vs PL/SQL Questions
1. What Are Stored Procedures, Functions, and Triggers in Oracle?
These are reusable PL/SQL program units that allow business logic to be stored inside the database and even appear in pl sql interview questions.
- Stored Procedure - A named block of PL/SQL code that performs a specific task. It can accept parameters but does not need to return a value.
- Function - Similar to a procedure, but it must return a value.
-
Trigger - A block of code that runs automatically when a specific event occurs, such as an
INSERT,UPDATE, orDELETEoperation.
For example, a trigger can automatically record changes made to employee salaries, while a function can calculate annual compensation based on monthly salary data.
2. When Should You Use PL/SQL Instead of Plain SQL?
SQL is designed for retrieving and manipulating data. PL/SQL is used when you need additional programming capabilities such as variables, loops, conditions, exception handling, or reusable logic.
Here’s what you should remember:
- Use SQL when a single query can solve the problem.
- Use PL/SQL when the task involves multiple steps, decision-making, or procedural logic.
For example, generating monthly payroll, validating employee records, or processing transactions often requires PL/SQL rather than a standalone SQL statement.
3. What Are Cursors in PL/SQL and Why Are They Used?
A cursor is a pointer to the result set returned by a query. It allows PL/SQL to process records one row at a time.
Cursors are used when each row requires separate processing that cannot be handled through a single SQL statement.
For example, an organization might use a cursor to iterate through employee records and generate personalized bonus calculations for each employee.
For a deeper understanding of PL/SQL concepts, procedures, triggers, cursors, and exception handling, you can check out this PL/SQL Interview Questions guide.
Query-Based Oracle SQL Interview Questions
1. Write a Query to Display the Top 5 Highest-Paid Employees in Oracle SQL
Finding the highest-paid employees is usually a matter of sorting the salary column in descending order and returning only the first few records.
SELECT employee_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY;Output:
| Employee Name | Salary |
|---|---|
| Aman Khanna | 95000 |
| Ananya Roy | 90000 |
| Priya Patel | 85000 |
| Neha Gupta | 75000 |
| Pooja Shah | 72000 |
The query first arranges all employees from the highest salary to the lowest using ORDER BY salary DESC. Once the records are sorted, FETCH FIRST 5 ROWS ONLY returns only the top five employees.
These examples should give you a good idea of the query patterns that show up quite often in interviews. Once you're done practicing with them, what you should do next is solve similar questions without looking at the solution first.
If you'd like more questions to practice on your own, check out these SQL Practice Questions.
2. Write a query to fetch the second highest salary from an employee table.
There are multiple ways to solve this problem in Oracle SQL, but one of the easiest approaches is to first find the highest salary and then look for the highest salary below it.
SELECT MAX(salary)
FROM employees
WHERE salary < (
SELECT MAX(salary)
FROM employees
);Output:
MAX(salary) - 90000
The highest salary in the sample dataset is 95000, earned by Aman Khanna. The inner query identifies this value first.
The outer query then searches for the highest salary that is less than 95000, which returns 90000. In our dataset, that salary belongs to Ananya Roy.
This approach is easy to understand and works well when you only need the second-highest salary value. You may also come across solutions using DENSE_RANK() or ROW_NUMBER(), especially when handling duplicate salary values.
If you're still getting familiar with writing queries from scratch, don't worry too much about solving every question on your first attempt. Try running the dataset, make a few changes, and see how the output changes.
And if you'd like more guided practice before tackling interview questions, you can check out this Free SQL course to get started.
3. Write a Query to Find Employees Who Earn More Than the Average Salary
Before writing the query, let's break the problem into two parts.
First, we need to find the average salary of all employees in the table. Once we have that value, we can compare every employee's salary against it and return only those earning more than the average.
SELECT employee_name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);For the dataset above, the average salary is approximately ₹66,333.
The query returns Priya Patel, Neha Gupta, Ananya Roy, Karan Verma, Aman Khanna, Pooja Shah, and Riya Sen because each of them earns more than the company average.
4. Write a Query to Count Employees Department-Wise
Let's say HR wants to know how many employees are working in each department. Looking at the table row by row won't help much, so we need a way to group employees belonging to the same department and then count them.
SELECT department_id, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id;Output:
| Department ID | Employee Count |
|---|---|
| 10 | 3 |
| 20 | 5 |
| 30 | 4 |
| 40 | 3 |
The query groups all employees with the same department_id together. Once the groups are formed, COUNT(*) calculates how many employees belong to each department.
5. Write a Query to Find Duplicate Email IDs in a Users Table
Let's say a company is cleaning up its employee records and wants to check whether the same email ID has been assigned more than once. Looking through every row manually would take time, especially when the table contains thousands of records.
A better approach is to group the records by email ID and count how many times each email appears.
SELECT email,
COUNT(*) AS occurrence_count
FROM employees
GROUP BY email
HAVING COUNT(*) > 1;Output:
| Occurrence Count | |
|---|---|
| neha@company.com | 2 |
The GROUP BY clause creates a group for each email ID, while COUNT(*) tells us how many times it appears. The HAVING clause then filters out emails that appear only once, leaving us with the duplicates.
Transactions, Indexing & Performance Questions
1. What Are COMMIT, ROLLBACK, and SAVEPOINT in Oracle SQL?
Imagine you're updating employee salaries for an entire department. Halfway through the process, you realize one of the updates was incorrect.
At that point, Oracle gives you a few options depending on how much of the work you want to keep.
-
COMMITpermanently saves all changes made during the current transaction. -
ROLLBACKreverses changes that have not yet been committed. -
SAVEPOINTcreates a checkpoint within a transaction that you can roll back to later.
Example:
UPDATE employees
SET salary = salary + 5000
WHERE department_id = 20;
SAVEPOINT salary_update;
UPDATE employees
SET salary = salary + 10000
WHERE employee_id = 105;If the second update turns out to be incorrect:
ROLLBACK TO salary_update;This removes only the changes made after the savepoint while preserving the earlier salary updates.
Once you're satisfied with the results:
COMMIT;After a commit, the changes become permanent and can no longer be rolled back.
2. What Is an Index in Oracle and How Does It Improve Query Performance?
Suppose an employee table contains a few million records, and you need to find Aman Khanna's details. Oracle could scan every row until it finds a match, but that would take unnecessary time.
An index helps Oracle find the required data much faster.
You can think of it like the index section at the back of a book. Instead of reading every page to find a topic, you jump directly to the relevant page number.
For example:
CREATE INDEX idx_employee_name
ON employees(employee_name);Once the index is created, queries that search by employee_name can often locate records without scanning the entire table.
SELECT *
FROM employees
WHERE employee_name = 'Aman Khanna';If you've studied indexing in DBMS before, you'll notice the same idea here: reduce the amount of data Oracle needs to scan before finding the required records.
Some benefits of indexes include:
- Faster data retrieval.
- Reduced full table scans.
- Better performance for frequently searched columns.
- Improved performance for joins and sorting operations in many cases.
One thing to remember is that indexes are not free. Oracle also has to maintain them whenever records are inserted, updated, or deleted. That's why indexes are usually created on columns that are searched frequently rather than on every column in a table.
3. What Is an Execution Plan in Oracle SQL?
After creating an index, the next question is usually: Did Oracle actually use it?
An execution plan helps answer that.
An execution plan shows the steps Oracle follows to execute a query. It tells you how the database accesses tables, whether it uses indexes, the order of joins, and the operations performed before returning the final result.
For example, consider the following query:
SELECT *
FROM employees
WHERE employee_name = 'Aman Khanna';To view the execution plan:
EXPLAIN PLAN FOR
SELECT *
FROM employees
WHERE employee_name = 'Aman Khanna';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);A simplified execution plan might look like this:
| Operation | Object Name |
|---|---|
| INDEX RANGE SCAN | IDX_EMPLOYEE_NAME |
| TABLE ACCESS BY INDEX ROWID | EMPLOYEES |
This tells us that Oracle used the IDX_EMPLOYEE_NAME index to locate the matching record instead of scanning the entire table.
Execution plans are = used when troubleshooting slow queries because they reveal how Oracle is processing the query behind the scenes. They can help identify issues such as unnecessary full table scans, inefficient joins, or unused indexes.
4. How Would You Optimize a Slow Oracle SQL Query?
One mistake people make is jumping straight into changes before figuring out where the time is actually being spent.
The first step is usually to check the execution plan. A slow query can have several causes, and the solution depends on the problem you're dealing with.
Some common areas to investigate include:
- Full table scans on large tables that could benefit from indexing.
- Unnecessary columns are being retrieved with
SELECT *. - Inefficient joins that process more data than required.
- Missing indexes on frequently filtered or joined columns.
- Subqueries that can be rewritten using joins or analytic functions.
- Large result sets are being returned when only a subset of rows is needed.
For example, consider the following query:
SELECT *
FROM employees
WHERE employee_name = 'Aman Khanna';If employee_name is searched frequently, creating an index on that column may significantly reduce the time required to locate matching records.
CREATE INDEX idx_employee_name
ON employees(employee_name);The key point is that optimization doesn’t work with just a single technique. It usually starts with understanding how Oracle is executing the query and then removing the specific bottlenecks that are slowing it down. That's also why these scenarios appear so often in oracle sql performance tuning interview questions.
5. What Is Normalization and Why Is It Important in Database Design?
Imagine an employee table that stores employee details, department details, manager details, and office location details all in the same place.
At first, it seems convenient. But after a while, the same department name starts appearing hundreds of times, office locations have to be updated in multiple rows, and a single mistake can leave the data inconsistent.
Normalization was created to solve exactly these kinds of problems.
Normalization is the process of organizing data into smaller, related tables to reduce redundancy and improve data consistency. Instead of storing the same information repeatedly, related data is separated and linked using keys.
For example, instead of storing department information in every employee record, you might create a separate Departments table and connect it to the Employees table using a foreign key.
Some benefits of normalization include:
- Reduces duplicate data.
- Improves data consistency.
- Makes updates easier to manage.
- Reduces storage requirements.
- Helps maintain data integrity.
Now, you'll often hear terms such as First Normal Form (1NF), Second Normal Form (2NF), and Third Normal Form (3NF). These are different stages of normalization that progressively reduce redundancy and dependency issues within a database.
But always remember to store data once, store it correctly, and avoid unnecessary duplication.