SQL Interview Questions
SQL Interview Questions
Especially programming interviews, where you may have to write some code (such as SQL) during the
interview.
But, with a little revision of some SQL interview questions and some tips, they are much easier.
You can use this guide as a study guide for any upcoming interviews. It contains all of the interview
questions from my SQL Interviews post.
Oracle database is targeted at large companies, SQL Server is owned by Microsoft, and MySQL is
owned by Oracle but targeted toward smaller companies and systems.
PL/SQL stands for Procedural Language/Structured Query Language. It’s Oracle’s procedural
language and is built on top of SQL. It allows for more programming logic to be used along with SQL.
T-SQL stands for Transact-SQL and is a language and set of extensions for SQL Server that allows for
further programming logic to be used with SQL.
4. What are the different DDL commands in SQL? Give a description of their
purpose.
● CREATE: creates objects in the database
● ALTER: makes changes to objects in the database
● DROP: removes objects from the database
● TRUNCATE: deletes all data from a table
www.DatabaseStar.com
SQL Interview Questions
5. What are the different DML commands in SQL? Give a description of their
purpose.
● SELECT: retrieve or view data from the database
● INSERT: add new records into a table
● UPDATE: change existing records in a table
● DELETE: removes data from a table
● MERGE: performs an UPSERT operation, also known as insert or update.
● CALL: runs a PL/SQL procedure or Java program
● EXPLAIN PLAN: explains the way the data is loaded
● LOCK TABLE: helps control concurrency
It’s the same as checking if a value is greater than or equal to one value, and less than or equal to
another value.
There are several reasons to use a view, such as to improve to security, create a layer of abstraction
between the underlying tables and applications, and to simplify queries.
www.DatabaseStar.com
SQL Interview Questions
A materialized view is a query where the results have been stored in a permanent state, like a table. If
the underlying tables are updated, then by default, the materialized views are not updated.
This is often done using some kind of numeric ID field but doesn’t have to be.
For example, a customer may have an account number that is unique to them, but a customer_id field
might be created on the table and used as the primary key, in case business rules change and mean
that the account number is no longer unique.
It’s different to a primary key in that a table can only have one primary key, but a table can have zero,
one, or many unique constraints.
Unique constraints can also allow NULL values, but primary keys cannot.
www.DatabaseStar.com
SQL Interview Questions
16. If a table contains duplicate rows, will a query display duplicate values by
default? How can you eliminate duplicate rows from a query result?
Yes, they will be displayed by default. To eliminate duplicate records, you use the DISTINCT keyword
after the word SELECT.
Answer:
Even if you don’t need a table to get your data, you need to add a table to your SELECT query for it to
run.
In this case, you can use the DUAL table that Oracle has created.
SELECT SYSDATE
FROM dual;
Joins
18. What are the different JOIN types and what do they do?
The different join types in Oracle SQL are:
www.DatabaseStar.com
SQL Interview Questions
● Self join: A join from one table to another record in the same table.
For example, if table A has 10 records and table B has 8 records, then the cross join will result in 80 (or
10 x 8) records.
20. What is a self join and why would you use one?
A self join is a type of join where a table is joined to itself.
You would use a self join when a table has a field that refers to another record in the same table. It’s
often used in hierarchical structures, such as employee tables having a manager_id column where the
manager_id refers to another employee record.
21. Given this ERD, write a query that shows the following information.
Entity Relationship Diagram
www.DatabaseStar.com
SQL Interview Questions
The customer ID, customer first and last name, the order ID of any orders the customer has placed (if
any) and the date of the order. The data should be ordered by last name then first name, both in
ascending order.
Answer:
SELECT
c.customer_id,
c.first_name,
c.last_name,
co.order_id,
co.order_date
FROM customer c
This question checks your ability to translate a normal English statement into a SELECT query.
You should have picked up on the need for a LEFT JOIN, the need for table aliases for ambiguous
columns, and the ORDER BY.
Table aliases are good to use in any case, so experienced developers will use them for every query.
www.DatabaseStar.com
SQL Interview Questions
You might have several different variations of this interview question for SQL interviews. Knowing
your query structure and focusing on the requirement for the query are important here.
Note: If you’re looking for a tool to create these kinds of diagrams, check out my guide on 76 Data
Modeling Tools Compared.
26. What is the difference between the WHERE and HAVING clauses?
The WHERE clause is run to remove data before grouping. The HAVING clause is run on data after it
has been grouped.
This also means the WHERE clause cannot operate on aggregate functions calculated as part of the
group.
More information: The Difference Between the WHERE and HAVING Clause.
www.DatabaseStar.com
SQL Interview Questions
FROM department;
Answer:
There is no GROUP BY clause and it will display an error. Because we have used the COUNT function,
which is an aggregate function, along with a database field, we need to add a GROUP BY clause. It
should GROUP BY the department_id column.
FROM department
GROUP BY department_id;
Answer:
The WHERE clause cannot include any checks on the aggregate column – even if a GROUP BY has
been performed.
This is because the WHERE happens before the grouping, so there is no way for the WHERE clause to
know what the value of the COUNT function is.
To resolve this, use the HAVING clause to check for COUNT(*) > 5.
Ordering
29. What is the default sort order using ORDER BY? How can it be changed?
The default sort order is ascending. This can be changed by specifying the word DESC after any
column name in the ORDER BY clause. The word ASC can be used instead to specify ascending order.
www.DatabaseStar.com
SQL Interview Questions
RANK will assign non-consecutive values, which means there will be gaps in numbers.
DENSE_RANK will assign consecutive values, which means there will be no gaps.
ROWNUM is calculated on all results but before ORDER BY. ROW_NUMBER is calculated as part of
the column calculation
More information: What’s The Difference Between Oracle ROWNUM vs Oracle ROW_NUMBER?
Set Operators
34. What does UNION do? What’s the difference between UNION and UNION
ALL?
Union allows you to combine two sets of results into one result.
It’s different to UNION ALL because UNION removes duplicate values and UNION ALL does not.
A union allows us to combine the results of two queries into a single result. No join between the results
is needed. Only the number and type of columns need to be the same.
But, UNION will combine the results from query1 with query2 and remove duplicate records.
MINUS will display the results of query1 and remove those that match any records from query2.
www.DatabaseStar.com
SQL Interview Questions
INTERSECT will display the records that appear in both query1 and query2.
Subqueries
37. What is a subquery?
A subquery is a query within another query. This subquery can be in many places, such as in the FROM
clause, the SELECT clause, or a WHERE clause.
It’s often used if you need to use the result of one query as an input into another query.
Subqueries can be standalone queries (non-correlated), or they can use fields in the outer query. These
fields are often used in join conditions or in WHERE clauses.
39. Given these two queries and result sets, what will the result of this query be?
Explain your answer.
SELECT *
FROM employee;
SELECT *
www.DatabaseStar.com
SQL Interview Questions
FROM department;
DEPARTMENT_ID DEPARTMENT_NAME
1 Executive
2 Sales
3 Customer Support
4 Hardware Development
5 Software Development
6 Marketing
7 Finance
8 Legal
9 Maintenance
SELECT *
FROM department
SELECT department_id
FROM employee
);
Answer:
This will return an empty result set. This is because of how the NOT IN command treats NULL values.
If the set of data inside the NOT IN subquery contains any values that have a NULL value, then the
outer query returns no rows.
To avoid this issue, add a check for NULL to the inner query:
SELECT *
FROM department
SELECT department_id
FROM employee
);
www.DatabaseStar.com
SQL Interview Questions
40. Write a query to display the 5th highest employee salary in the employee
table
SELECT *
FROM (
SELECT employee_id,
first_name,
last_name,
salary,
FROM employee
WHERE rank_val = 5;
This could also be done using the ROW_NUMBER function. It’s one of those interview questions in
SQL that can have multiple answers, but as long as you provide an answer to it, you should be OK.
Database Design
41. What is cardinality?
Cardinality refers to the uniqueness of values in a column. High cardinality means that there is a large
percentage of unique values. Low cardinality means there is a low percentage of unique values.
42. How can you create an empty table from an existing table?
You can use the CREATE TABLE AS SELECT command.
The SELECT statement will contain all of the columns that you want to have in your new table. To
ensure it is empty, add a WHERE clause that evaluates to FALSE, such as WHERE 1=0.
www.DatabaseStar.com
SQL Interview Questions
There are three popular normal forms, named first/second/third normal form. Third normal form is
commonly used as a goal, but there are normal forms after third normal form that are occasionally
used.
It often results in a smaller number of tables, each of which has more columns than normalised tables.
45. What do OLTP and OLAP mean and how are they different?
OLTP stands for OnLine Transaction Processing and refers to databases that are designed for regular
transactions of inserting, updating, and deleting data. This often includes a normalised database and is
linked to an application used during business hours for people to do their job.
OLAP stands for OnLine Analytical Processing and refers to databases that are designed for analysis
and reporting. They are focused on SELECT queries and often contain denormalised database designs.
They are often used by reporting systems to analyse data from other OLTP systems.
Functions
46. What are the case manipulation functions in Oracle SQL?
To change the case of a string in Oracle SQL you can use UPPER, LOWER, or INITCAP. Read more
here.
This is one of the SQL interview questions which is Oracle specific, as the REMAINDER function does
not exist in other database management systems.
48. What does the NVL function do, and how is it different from NVL2?
The NVL function checks if a value is NULL, and returns the value if it is not NULL. If the value is NULL,
it returns a different value which you can specify.
www.DatabaseStar.com
SQL Interview Questions
NVL2 is slightly different in that you specify both the value to return if the checked value is NULL and
if it is not NULL.
The CASE statement is more flexible and arguably easier to read than the DECODE function.
50. How can you search for a value in a column when you don’t have the exact
match to search for?
If you don’t know the exact match, you can use wildcards along with LIKE. The wildcards are the %
symbol for any number of characters, and the _ symbol for a single character.
52. Can you insert a NULL value into a column with the INSERT statement?
Yes, you can. You can do this by:
● Leaving the column out of the list of columns in the INSERT statement; or
● Specifying the value of NULL for the column in the VALUES clause
53. Can you INSERT data from one table into another table? If so, how?
Yes, you can do this using an INSERT INTO SELECT query. You start by writing an INSERT INTO
statement, along with the columns you want, and then instead of the VALUES clause, you write a
SELECT query.
This SELECT query can select data from the same table, or another table, or a combination of tables
using JOINs, just like a regular SELECT query.
www.DatabaseStar.com
SQL Interview Questions
54. What happens if you don’t have a WHERE clause in an UPDATE statement?
All records in the table will be updated. You need to be sure that’s what you want to do.
55. What happens if you don’t have a WHERE clause in a DELETE statement?
All records will be deleted from the table. It will still run, there will be no error. You need to be sure
that’s what you want to do.
Also, DROP is a DDL statement and DELETE is a DML statement, which means DELETE can be rolled
back but DROP cannot.
TRUNCATE deletes all records from a table and you cannot specify a WHERE clause, but DELETE
allows you to specify a WHERE clause if you want.
TRUNCATE is often faster because it does not generate an undo log, but DELETE does.
A table can only have one clustered index. An alternative is a non-clustered index, which does not
order the records on a disk but does offer other benefits of indexes.
www.DatabaseStar.com
SQL Interview Questions
61. What is an execution plan? How can you view the execution plan?
An execution plan is a graphic or text visualisation of how the database’s optimiser will run a query.
They are useful for helping a developer understand and analyse the performance of their query.
To find the execution plan of a query, add the words “EXPLAIN PLAN FOR” before your query. The
query won’t run, but the execution plan for the query will be displayed.
62. Is NULL the same as a zero or blank space? If not, what is the difference?
No, they are different. NULL represents an unknown value. Zero represents the number zero, and a
blank space represents a character string with no data.
NULL is compared differently to a zero and a blank space and must use comparisons like IS NULL or IS
NOT NULL.
65. List the ACID properties and explain what they are.
ACID stands for Atomicity, Consistency, Isolation, and Durability. They are a set of properties that
ensure that database transactions are processed reliably.
● Atomicity means that each transaction be atomic, which means “all or nothing”. Either the
entire transaction gets saved, or none of it gets saved.
www.DatabaseStar.com
SQL Interview Questions
● Consistency means that any transaction will bring the database from one consistent state to
another. Data must be valid according to all business rules.
● Isolation means that transactions that are executed at the same time will give the same results
as transactions executed one after the other. The effects of one transaction may not be visible
to another transaction.
● Durability means that once a transaction has been committed, it remains committed. This is
even if there is a disaster, such as power loss or other errors.
This SQL interview question should be relevant to all database management systems. It’s not Oracle
specific.
The sequence is used to generate new values, and the BEFORE INSERT trigger will read these new
values and put them into the required column whenever you INSERT a new record.
In Oracle 12c, you can define a column as an Identity column by putting the words GENERATED AS
IDENTITY after the column in the CREATE TABLE statement. This means new values are generated
automatically.
67. What’s the difference between % and _ for pattern matching (e.g. in the LIKE
operator)?
The difference is the % sign will match one or more characters, but the _ sign will match only one
character.
They are often used to break up complex queries to make them simpler. They use the WITH clause in
SQL. An example of a CTE would be:
SELECT ma.make_name,
mo.model_name
FROM car_make ma
www.DatabaseStar.com
SQL Interview Questions
SELECT make_name,
model_name
FROM cte_car_model;
This is a simple example, but more complicated queries will benefit from CTEs, both in performance
and readability.
69. What is a temp table, and when would you use one?
A temp table (or temporary table) is a database table that exists temporarily on the system. It allows
you to store the results of a query for use later in a session. They are useful if you have a large number
of results and you want to use them again.
A temporary table, by default, is only accessible by you. Global temporary tables can be accessed by
others.
Temporary tables are automatically deleted when the connection that created them is closed.
Conclusion
Interviews for SQL-heavy positions (ETL developer, BI developer, data analyst, for example) can seem
daunting because of the wide range of technical questions that can be asked.
But they don’t have to be. Knowing your basics and a good level of SQL needed for the position you’re
applying for is all the interviewer will want to know.
Study these questions and understand the topics, and along with any experience you have, you’ll be
well prepared for an SQL interview.
Good luck!
Ben Brumm
www.DatabaseStar.com
www.DatabaseStar.com