Intermediate SQL Interview Questions
Intermediate SQL Interview Questions
Databases, organized in a tabular format, store information that can be easily accessed and
managed using SQL. SQL provides a set of commands that allow users to interact with the
database, making it a fundamental skill for anyone working with data or involved in
software development.
In SQL, TRUNCATE and DELETE are both used to remove data from a table, but there are
some key differences between the two:
1. Speed :
• TRUNCATE is faster than DELETE as it does not generate any undo/rollback
logs.
2. Transaction Logs :
• DELETE generates undo/rollback logs, while TRUNCATE does not. This
makes TRUNCATE more efficient when working with large tables.
3. Triggers :
• TRUNCATE does not activate any triggers associated with the table,
while DELETE does.
4. Identity Columns :
• TRUNCATE resets the identity column to its original seed value,
while DELETE does not.
5. Referential Integrity :
• TRUNCATE does not enforce referential integrity constraints,
while DELETE does. This means that TRUNCATE may violate foreign key
constraints.
The syntax for DELETE in SQL is as follows:
DELETE FROM table_name [WHERE condition];
where table_name is the name of the table from which you want to delete data
and condition is an optional clause to specify which rows to delete.
2. Explain the foreign key ?
A stored procedure in SQL is a pre-compiled, reusable program that can accept parameters,
execute a series of SQL statements, and return a result. Stored procedures provide several
benefits over direct execution of SQL statements:
1. Improved performance :
• Stored procedures are compiled and optimized when created, and then
executed directly from memory on subsequent calls.
2. Enhanced security :
• By encapsulating complex logic in a stored procedure, you can restrict access to
the underlying data and limit the risk of SQL injection attacks.
3. Code reuse :
• Stored procedures can be called from multiple places within an application,
reducing the need to duplicate code.
4. Improved maintainability :
• Changes to complex logic can be made in a single place, making it easier to
maintain the code.
A stored procedure can return a result set, return a single value, or not return anything at
all. Syntax and implementation vary depending on the specific database management
system being used (e.g. MySQL, Microsoft SQL Server, Oracle, etc.).
Stored procedures in SQL are pre-compiled and reusable units of code that are stored in a
database and can be executed repeatedly. They are used for various purposes, including:
1. Data Validation :
• Stored procedures can be used to validate incoming data, ensuring that only
valid data is entered into the database.
2. Improved Performance :
• Stored procedures can be used to improve the performance of database
operations by reducing the amount of data that needs to be transmitted
between the database and the application.
3. Security :
• Stored procedures can be used to enforce security policies and restrict access to
sensitive data.
4. Code Reuse :
• Stored procedures can be reused across different applications, reducing the
need for duplicate code and making it easier to maintain.
5. Encapsulation of Business Logic :
• Stored procedures can be used to encapsulate complex business logic that
would otherwise be difficult to implement in the application layer.
6. Centralized Maintenance :
• Stored procedures can be maintained centrally, making it easier to update and
maintain the code.
5. Explain the join ?
In SQL, a join operation combines rows from two or more tables based on a related column
between them. The result of the join operation is a single table that includes columns from
both of the original tables. There are several types of joins in SQL, including:
1. INNER JOIN :
• returns only the rows for which there is a match in both tables.
2. LEFT JOIN or LEFT OUTER JOIN :
• returns all the rows from the left table (table1), and the matching rows from the
right table (table2). The result will contain NULL values for non-matching rows
in the right table.
3. RIGHT JOIN or RIGHT OUTER JOIN :
• returns all the rows from the right table (table2), and the matching rows from
the left table (table1). The result will contain NULL values for non-matching
rows in the left table.
4. FULL JOIN or FULL OUTER JOIN :
• returns all rows from both tables, with NULL values for non-matching rows in
either table.
The basic syntax for a join operation is:
To insert data into a table in SQL, you need to use the INSERT INTO statement. The basic
syntax is as follows:
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
1. INSERT INTO :
• Specifies that data is being inserted into the table.
2. table_name :
• Specifies the name of the table that the data will be inserted into.
3. column1, column2, etc. :
• Specify the names of the columns in the table. This is optional, but can be useful
if you only want to insert data into a subset of the columns.
4. VALUES :
• Specifies the values to be inserted.
5. value1, value2, etc. :
• Specify the values for each column.
Here is an example that inserts a new employee into the employees table:
INSERT INTO employees (employee_id, last_name, first_name, salary)
VALUES (100, 'Smith', 'John', 65000);
In this example, data is being inserted into all columns of the employees table, and the
values are provided in the same order as the columns in the table.
Note that the specific syntax for inserting data can vary between different SQL
implementations, such as MySQL, Oracle, Microsoft SQL Server, and others.
• To delete a column in SQL, you can use the ALTER TABLE statement with the
DROP COLUMN clause.
The basic syntax is:
Here’s an example of a CASE statement in SQL, which can be used as a switch statement:
DECLARE @num INT = 1;
SELECT
CASE
WHEN @num = 1 THEN 'One'
WHEN @num = 2 THEN 'Two'
WHEN @num = 3 THEN 'Three'
ELSE 'Other number'
END AS result
• In this example, the CASE statement checks the value of @num and returns the
corresponding string value. If the value of @num does not match any of the
specified values (1, 2, or 3), the statement returns the string ‘Other number’.
• This is just one example of how a CASE statement can be used in SQL, and the
exact syntax and implementation may vary depending on the specific SQL
dialect being used.
9. Explain the Read query and code ?
• The LIMIT clause in SQL is used to specify the maximum number of rows to be
returned by a SELECT statement. It is often used in combination with
the OFFSET clause to paginate the results of a query.
For example, the following SQL statement returns the first 10 rows from
the employees table:
SELECT * FROM employees LIMIT 10;
• You can also use the LIMIT clause with the OFFSET clause to return a specific
range of rows. For example, the following SQL statement returns rows 11 to 20
from the employees table:
SELECT * FROM employees LIMIT 10 OFFSET 10;
• In this example, the LIMIT clause specifies that only 10 rows should be
returned, and the OFFSET clause specifies that the first 10 rows should be
skipped. The result is a set of 10 rows starting from the 11th row of
the employees table.
• Note that the LIMIT clause is not standard SQL and its syntax may vary
between different relational database management systems. However, the basic
concept of limiting the number of rows returned by a SELECT statement is
supported by most relational databases.
12. Explain the functions in sql ?
SQL functions are pre-defined, reusable pieces of code that perform specific operations on
data in a database. Functions can be used in SQL statements to perform calculations,
manipulate data, and aggregate data.
1. Scalar functions :
• perform operations on individual values and return a single value as a result.
For example, the LENGTH function returns the length of a string, and
the ABS function returns the absolute value of a number.
2. Aggregate functions :
• perform operations on a set of values and return a single result that
summarizes the data. For example, the SUM function returns the sum of a set of
values, and the AVG function returns the average of a set of values.
3. String functions :
• perform operations on string values, such as concatenation, trimming, and
substitution. For example, the CONCAT function concatenates two strings, and
the SUBSTRING function returns a portion of a string.
4. Date and time functions :
• perform operations on date and time values, such as extracting parts of a date,
formatting dates and times, and performing date and time arithmetic. For
example, the NOW function returns the current date and time, and
the DATEDIFF function returns the difference between two dates.
Functions can be used in a variety of contexts in SQL, including in the SELECT clause,
WHERE clause, GROUP BY clause, and HAVING clause. They can also be used in stored
procedures, triggers, and user-defined functions.
13. Again assuming a table for real-time, where you will be applying Index for this table ?
When optimizing a real-time table, indexes should be applied based on the most common
query patterns and usage scenarios. To determine the appropriate index to use, consider
the following factors:
1. Query performance :
• The goal is to improve the performance of frequently executed queries that
involve searching or filtering data.
2. Columns used in the WHERE clause :
• The most common query pattern in real-time systems is to filter data based on
specific conditions, so you should consider indexing columns that are
frequently used in the WHERE clause.
3. Data volume and distribution :
• If the table has a large amount of data and the data is evenly distributed, you
may consider using a clustered index. If the data is highly skewed, a non-
clustered index may be more appropriate.
4. Insert performance :
• The indexing strategy should also consider the impact on the insert
performance of the table, as adding new rows may require updates to the index
structure.
5. Update and Delete operations :
• The indexing strategy should also take into account the frequency of update and
delete operations on the table, as these may require updates to the index
structure as well.
Based on these factors, you can make an informed decision on the type and columns of the
index to use for the real-time table. It may also be beneficial to use multiple indexes for a
table to support different query patterns.
A view in SQL is a virtual table that is based on the result of a SELECT statement. It acts as a
stored query, allowing you to simplify complex joins and aggregate data in a way that can
be easily reused across multiple queries.
A view can be thought of as a window into the underlying data of one or more tables,
without actually storing any data itself. The data is fetched and aggregated dynamically
each time the view is queried.
1. Abstraction :
• A view can simplify complex queries by abstracting away the underlying details
of the tables involved.
2. Security :
• A view can restrict access to certain columns or rows of a table, providing a
level of security.
3. Performance :
• A view can be indexed, providing improved performance for frequently
executed queries.
4. Code reuse :
• Views can be reused across multiple queries, reducing code duplication and
making it easier to maintain the code.
Syntax for creating a view in SQL:
CREATE VIEW view_name AS SELECT column1, column2, ... FROM table_name WHERE
condition
Note: The syntax may vary slightly depending on the specific SQL dialect being used.
DQL (Data Query Language) in SQL consists of a set of commands used to retrieve data
from a database. The main DQL commands and their syntax are:
1. SELECT :
• The SELECT statement is used to retrieve data from one or more tables in a
database. The basic syntax is:
SELECT column1, column2, ... FROM table_name;
2. FROM :
• The FROM clause specifies the table(s) from which to retrieve data. The basic
syntax is:
SELECT column1, column2, ... FROM table_name;
3. WHERE :
• The WHERE clause is used to filter data based on specified conditions. The basic
syntax is:
pastacode lang=”sql”
manual=”SELECT%20column1%2C%20column2%2C%20…%20FROM%20table_name%2
0WHERE%20condition%3B” message=”” highlight=”” provider=”manual”/]
4. GROUP BY :
• The GROUP BY clause is used to group data based on one or more columns. The
basic syntax is:
SELECT column1, column2, ... FROM table_name GROUP BY column1, column2, ...;
5. HAVING :
• The HAVING clause is used to filter groups based on aggregate values. The basic
syntax is:
SELECT column1, column2, ... FROM table_name GROUP BY column1, column2, ...
HAVING condition;
6. ORDER BY :
• The ORDER BY clause is used to sort data in ascending or descending order. The
basic syntax is:
SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC|DESC], column2
[ASC|DESC], ...;
These are some of the most commonly used DQL commands in SQL. The syntax may vary
slightly depending on the specific SQL implementation being used.
DCL (Data Control Language) in SQL consists of a set of commands used to control access to
data stored in a database. The main DCL commands and their syntax are:
1. GRANT :
• The GRANT statement is used to give specific permissions to users or roles to
access or manipulate data in the database. The basic syntax is:
GRANT privilege_name ON object_name TO user_name [WITH GRANT OPTION];
2. REVOKE :
• The REVOKE statement is used to remove previously granted permissions from
users or roles. The basic syntax is:
REVOKE privilege_name ON object_name FROM user_name;
• privilege_name refers to the specific permission being granted or revoked (e.g.
SELECT, INSERT, UPDATE, DELETE, etc.). object_name refers to the database
object (e.g. table, view, sequence, etc.) on which the permission is being granted
or revoked. user_name refers to the user or role that the permission is being
granted or revoked for. The WITH GRANT OPTION clause allows the recipient
of a GRANT to grant the same privilege to others.
• DCL is an important aspect of database security, as it regulates who can
perform specific actions on the data stored in a database, such as reading,
writing, or deleting data. By controlling access to the data, DCL helps to ensure
the security and integrity of the data stored in a database.
17. DDL types syntax and explain ?
DDL (Data Definition Language) in SQL consists of a set of commands used to define the
structure of a database, including creating and modifying database objects such as tables,
indexes, views, etc. The main DDL commands and their syntax are:
1. CREATE :
• The CREATE statement is used to create database objects such as tables, views,
indexes, etc. The basic syntax for creating a table is:
CREATE TABLE table_name (
column1_name data_type [CONSTRAINT constraint_name] [NOT NULL],
column2_name data_type [CONSTRAINT constraint_name] [NOT NULL],
...
);
2. ALTER :
• The ALTER statement is used to modify existing database objects such as tables,
views, etc. The basic syntax for adding a column to a table is:
ALTER TABLE table_name
ADD COLUMN column_name data_type [CONSTRAINT constraint_name] [NOT NULL];
3. DROP :
• The DROP statement is used to delete existing database objects such as tables,
views, indexes, etc. The basic syntax for deleting a table is:
DROP TABLE table_name;
4. TRUNCATE :
• The TRUNCATE statement is used to delete all data from a table, but unlike
DROP, it preserves the structure of the table. The basic syntax is:
TRUNCATE TABLE table_name;
These are some of the most commonly used DDL commands in SQL. The syntax may vary
slightly depending on the specific SQL implementation being used. DDL commands play a
crucial role in defining and maintaining the structure of a database, and are used to create,
modify, and delete database objects as needed.
DML stands for Data Manipulation Language and includes commands used to manipulate
data in a database. The main types of DML are:
1. SELECT :
• Retrieves data from one or more tables. Syntax:
SELECT column1, column2, ... FROM table_name WHERE condition;
2. INSERT :
• Adds new data to a table. Syntax:
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
3. UPDATE :
• Modifies existing data in a table. Syntax:
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
4. DELETE :
• Deletes existing data from a table. Syntax:
DELETE FROM table_name WHERE condition;
These are the main DML commands and can be used in various combinations to manipulate
data stored in a database.
TCL stands for Transaction Control Language and includes commands used to manage the
changes made to data in a database. The main types of TCL are:
1. COMMIT :
• Saves changes made during a transaction to the database. Syntax:
COMMIT;
2. ROLLBACK :
• Discards changes made during a transaction. Syntax:
ROLLBACK;
3. SAVEPOINT :
• Creates a marker within a transaction to which you can later rollback. Syntax:
SAVEPOINT savepoint_name;
4. ROLLBACK TO :
• Reverts changes made after a savepoint to the state when the savepoint was
created. Syntax:
ROLLBACK TO savepoint_name;
These commands are used to control transactions in a database, which are a series of
database operations that are executed as a single unit of work. The transaction is either
committed, which means the changes made are saved, or rolled back, which means the
changes are discarded.
IF @num > 0
SELECT 'The number is positive.' AS result;
ELSE
SELECT 'The number is non-positive.' AS result;
• In this example, the IF statement checks the value of @num. If the value
of @num is greater than 0, the statement selects and displays the message ‘The
number is positive‘. If the value of @num is not greater than 0, the statement
selects and displays the message ‘The number is non-positive’.
• This is just one example of how an IF statement can be used in SQL, and the
exact syntax and implementation may vary depending on the specific SQL
dialect being used.
22. What is temp table in sql ?