0% found this document useful (0 votes)
23 views

Basic SQL Int Ques

Uploaded by

kharshitha93
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Basic SQL Int Ques

Uploaded by

kharshitha93
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Basic SQL Interview Questions

1. What is the difference between SQL, Oracle, MySQL, and SQL Server?
SQL is the name of the language used to query databases and follows a standard. Oracle,
MySQL and SQL Server are different implementations or versions of a database
management system, which implement the SQL standard and build on it in different
ways. 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.

2. What is the difference between SQL and PL/SQL?


SQL is the language used to query databases. You run a query, such as SELECT or
INSERT, and get a result. 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.

3. What is the difference between SQL and T-SQL?


SQL is the language used to query databases. You run a query, such as SELECT or
INSERT, and get a result. 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
● COMMENT: adds comments to the data dictionary
● RENAME: renames an object in the database

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

6. What is the purpose of the BETWEEN keyword?


The BETWEEN keyword allows you to check that a value falls in between two other values
in the WHERE clause. 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.

7. What is the purpose of the IN keyword?


The IN keyword allows you to check if a value matches one of a range of values. It’s often
used with subqueries that return more than one row.

8. What is a view? When would you use one?


A view is a database object that allows you to run a saved query to view a set of data. You
create a view by specifying a SELECT query to be used as the view, and then the view
can be queried just like a table. 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.

Example: CREATE VIEW employee_sales AS


SELECT employee_id, employee_name, SUM(sales_amount) AS total_sales
FROM sales
GROUP BY employee_id, employee_name;

This query retrieves all employees whose total sales exceed 10,000 from the
employee_sales view, just as if it were a table.

Benefits of using Views:

• Simplifies complex queries.


• Enhances security by limiting access to underlying tables.
• Provides a layer of abstraction.

9. What’s the difference between a view and a materialized view?


A view is simply an SQL query that is stored on the database, without the results. Every
time a view is queried, this definition of the view’s query is run. If the underlying tables have
been updated, the view will load these results. 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.

10. What is a primary key?


A primary key is a column or set of columns that uniquely identifies a row in a table. It’s
created on a table and ensures that the values in that column or columns must be unique
and not NULL. This is often done using some kind of numeric ID field but doesn’t have to
be.

11. What is a foreign key?


A foreign key is a field in a table that refers to a primary key in another table. It is used to
link the record in the first table to the record in the second table.

12. What is a composite key?


A composite key is a primary key that is made up of two or more fields. Often, primary
keys are single fields, but in some cases, a row is identified by multiple fields. This is what
a composite key is.

13. What is a surrogate key?


A surrogate key is a field in a table that has been created solely for the purpose of being
the primary key. It has no other purpose than an internal storage and reference number.
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.

14. What is a unique constraint? How is it different from a primary key?


A unique constraint is a constraint on a table that says that a column or set of columns
needs to have unique values. 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.

15. What is a synonym?


A synonym is a database object that allows you to create a kind of “link” or “alias” to
another database object. This is often done to hide the name of the actual object for
security reasons, or to improve maintenance of the code in the future.

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.

17. what are SQL constraints?

In SQL, constraints are rules applied to columns or tables that enforce data integrity and
ensure that the data adheres to certain conditions. Constraints help maintain accuracy,
consistency, and reliability of the data in a database.

Common SQL Constraints:

1. NOT NULL:
o Ensures that a column cannot have a NULL value (i.e., it must always contain a
value).

CREATE TABLE employees (


employee_id INT NOT NULL,
name VARCHAR(50) NOT NULL);

2. UNIQUE:
o Ensures that all values in a column (or a group of columns) are distinct,
meaning no duplicate values are allowed.

CREATE TABLE users (


user_id INT,
email VARCHAR(100) UNIQUE);

3. PRIMARY KEY:
o Combines the NOT NULL and UNIQUE constraints. It uniquely identifies each
row in a table. Each table can have only one primary key, and it cannot
contain NULL values.

CREATE TABLE products (


product_id INT PRIMARY KEY,
product_name VARCHAR(50));

4. FOREIGN KEY:
o Ensures referential integrity between two tables by creating a relationship
between a column in one table (the foreign key) and the PRIMARY KEY of
another table.

CREATE TABLE orders (


order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES
customers(customer_id));

5. CHECK:
o Ensures that values in a column satisfy a specific condition.

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
age INT CHECK (age >= 18));

6. DEFAULT:
o Assigns a default value to a column if no value is provided when inserting
data.

CREATE TABLE orders (


order_id INT,
order_date DATE DEFAULT CURRENT_DATE);

1. What are the different JOIN types and what do they do?
The different join types in Oracle SQL are:

● Inner join: Returns records that exist in both tables.


● Left join/left outer join: Returns records that exist in the first table and shows NULL for
those values that don’t exist in the second table.
● Right join/right outer join: Returns records that exist in the second table and shows
NULL for those values that don’t exist in the first table.
● Full join/full outer join: Returns records that exist in both the first and second table,
and shows NULL for those values that don’t exist in the corresponding table.
● Cross join: Returns all combinations of all records in both tables.
● Natural join: an inner join with two tables on columns that have the same names.
● Self join: A join from one table to another record in the same table.
Read in details

2. What is a “cross join”?


A cross join is a type of join where the results displayed contain the records from both
tables in all possible combinations. There is no field used to perform the join.

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. The result can also be called a “cartesian product”.

3. 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.

1. What is an aggregate function?


An aggregate function is an SQL function that reads data from multiple rows and displays
a single
value. Some examples of aggregate functions are COUNT, SUM, MIN, MAX, and AVG.
They are often used with a GROUP BY clause but can be used by themselves.

2. Can you nest aggregate functions?


Yes, you can have nested aggregate functions up to two levels deep. For example, you
can use MAX(COUNT(*)).

3. Does COUNT return the number of columns in a table?


No, it returns the number of records in a table.

4.. What’s the difference between COUNT(column) and COUNT(DISTINCT column)?


COUNT(column) will return the number of non-NULL values in that column.
COUNT(DISTINCT column) will return the number of unique non-NULL values in that
column.

5. 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.

6. What’s wrong with this query?


SELECT department_id, count(*) FROM department;
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.

7. What’s wrong with this query?


SELECT department_id, count(*) FROM department WHERE count(*) > 5
GROUP BY department_id;

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.
1. 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.

2. Can you sort a column using a column alias?


Yes, you can sort by column aliases in an ORDER BY clause.

1.. What is a window function or analytic function?


A window function or analytic function is a function that performs a calculation across a
set of related rows. It’s similar to an aggregate function, but a window function does not
group any rows together. The window function accesses multiple rows “behind the
scenes”.

2. What is the difference between RANK and DENSE_RANK?


The difference between RANK and DENSE_RANK is where there is a tie or two records
with the same value. 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.

3. What’s the difference between ROWNUM and ROW_NUMBER?


ROWNUM is a pseudocolumn and has no parameters, where as ROW_NUMBER is an
analytical function that takes parameters. ROWNUM is calculated on all results but before
ORDER BY. ROW_NUMBER is calculated as part of the column calculation ROWNUM is
unique. ROW_NUMBER can contain duplicates.

1. 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.

2. What’s the difference between UNION and JOIN?


A join allows us to lookup data from one table in another table based on common fields
(for example employees and departments). It requires us to have a field that is common
in both tables. 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.

3. What’s the difference between UNION, MINUS, and INTERSECT?


They are all set operators. 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. INTERSECT will display the records that appear in
both query1 and query2.
1. 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.

2. What is a correlated subquery?


A correlated subquery is a subquery that refers to a field in the outer 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.

3. Write a query to display the 5th highest employee salary in the employee
table
SELECT * FROM ( SELECT employee_id, first_name, last_name, salary,
DENSE_RANK() OVER (ORDER BY salary DESC NULLS LAST)
rank_val 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.

1. 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.

2. 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.

3. What is normalization?
Normalization is the process of organizing your data into tables that adhere to certain
rules. It aims to make the process of selecting, inserting, updating, and deleting data more
efficient and reduce data issues that may appear otherwise.

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.
4. What is denormalization?
Denormalization is the process of converting a normalized database into a series of tables
that are not normalized. These deformalized tables often contain records that refer to the
same value, so updating them is not as efficient. However, the aim of this process is
usually to prepare the data for a data warehouse, so the goal is the efficient reading of
data. It often results in a smaller number of tables, each of which has more columns than
normalized tables.

5. 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
1. 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,
LENGTH,TRIM, REPLACE.

2.. Which function or functions returns the remainder of a division operation?


The MOD function and REMAINDER function both return the remainder of a division
operator.

3. 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.

4. 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.

5. 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.

6. What’s the difference between DROP and DELETE?


DROP is used to remove database objects from the database, such as tables or views.
DELETE is used to remove data from a table. Also, DROP is a DDL statement and DELETE
is a DML statement, which means DELETE can be rolled back but DROP cannot.

7. What’s the difference between TRUNCATE and DELETE?


There are several differences. 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 does not allow for rollbacks, and DELETE does. TRUNCATE is
often faster because it does not generate an undo log, but DELETE does.

Other SQL Interview Questions


1. What is a clustered index?
A clustered index is a type of index that reorders how the records are stored on the disk.
This allows for fast retrieval of data that uses this index. 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.

2. What is DCL? Provide an explanation of some of the commands.


DCL stands for Data Control Language. The commands that come under DCL are:
● GRANT: give access privileges to a user
● REVOKE: withdraw access privileges from a user

3. What is TCL? Provide an explanation of some of the commands.


TCL stands for Transaction Control Language and it contains statements to manage
changes made by
DML statements. It includes:
● COMMIT: saves the data to the database
● ROLLBACK: undo the modifications made since the last COMMIT
● SAVEPOINT: create a point in a transaction that you can ROLLBACK to
● SET TRANSACTION: change the transaction options, such as isolation level
● SET ROLE: sets the current active role

4. What is an execution plan? How can you view the execution plan?
An execution plan is a graphic or text visualization of how the database’s optimizer 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.

5. 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.

6. What’s the difference between ANY and ALL?


The ANY keyword checks that a value meets at least one of the conditions in the following
set of values. The ALL keyword checks that a value meets all of the conditions in the
following set of values.

7. What’s the difference between VARCHAR2 and CHAR?


VARCHAR2 does not pad spaces at the end of a character string, but CHAR does. CHAR
values are always the maximum length, but VARCHAR2 values are variable length.

8. 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.
● 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.

9. 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.

10. What is a CTE?


CTE stands for Common Table Expression. It’s a SELECT query that returns a temporary
result set that you can use within another SQL query.
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:
This is a simple example, but more complicated queries will benefit from CTEs, both in
performance
and readability.

11. 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.
Follow me on LinkedIn

You might also like