SQL, or Structured Query Language, is a powerful and standardized programming language designed for managing and manipulating relational databases. It serves as a means to interact with databases, enabling users to create, retrieve, update, and delete data. SQL is widely used in various industries for tasks ranging from simple data queries to complex database management and administration.

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.

Uncover a curated selection of intermediate-level SQL questions that mirror the complexities faced in real-world scenarios. With detailed answers, insightful explanations, and a focus on problem-solving strategies, this resource ensures you’re well-prepared to tackle the nuances of database querying and optimization during your interviews.

Intermediate SQL Interview Questions

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.
  1. Transaction Logs :
  • DELETE generates undo/rollback logs, while TRUNCATE does not. This makes TRUNCATE more efficient when working with large tables.
  1. Triggers :
  • TRUNCATE does not activate any triggers associated with the table, while DELETE does.
  1. Identity Columns :
  • TRUNCATE resets the identity column to its original seed value, while DELETE does not.
  1. 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.

  • In SQL, a foreign key is a column or a set of columns in a table that refers to a primary key in another table. It is used to enforce referential integrity in a database, which means that the data in one table is related to the data in another table.
  • The foreign key creates a link between two tables, ensuring that data entered in one table is valid in relation to the data in the other table. For example, if a foreign key is used to link a customers table to an orders table, it would ensure that every customer in the customers table has a corresponding order in the orders table.

The basic syntax of creating a foreign key in SQL is as follows:

ALTER TABLE table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY (column_name)
REFERENCES referenced_table_name (referenced_column_name);
  • where table_name is the name of the table you want to add the foreign key to, constraint_name is the name you want to give to the constraint, column_name is the name of the column in the table_name that will serve as the foreign key, referenced_table_name is the name of the table the foreign key is referencing, and referenced_column_name is the name of the column in the referenced_table_name that is being referenced by 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.
  1. 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.
  1. Code reuse :
  • Stored procedures can be called from multiple places within an application, reducing the need to duplicate code.
  1. 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.
  1. 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.
  1. Security :
  • Stored procedures can be used to enforce security policies and restrict access to sensitive data.
  1. Code Reuse :
  • Stored procedures can be reused across different applications, reducing the need for duplicate code and making it easier to maintain.
  1. 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.
  1. Centralized Maintenance :
  • Stored procedures can be maintained centrally, making it easier to update and maintain the code.

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

SELECT column1, column2, ...
FROM table1
JOIN table2
ON table1.column = table2.column;
SELECT column1, column2, ...
FROM table1
JOIN table2
ON table1.column = table2.column;

  • SELECT: specifies the columns to be returned in the result set.
  • FROM: specifies the first table to be queried.
  • JOIN: specifies the type of join to be performed.
  • ON: specifies the join condition, which determines how the rows from the two tables are matched.

For example, to join the employees and departments tables on the department_id column:

SELECT employees.last_name, employees.first_name, departments.department_name
FROM employees
JOIN departments
ON employees.department_id = departments.department_id;

 

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.
  1. table_name :
  • Specifies the name of the table that the data will be inserted into.
  1. 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.
  1. VALUES :
  • Specifies the values to be inserted.
  1. 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:

ALTER TABLE table_name
DROP COLUMN column_name;
  • Replace table_name with the name of the table and column_name with the name of the column you want to delete.
  • Note: Deleting a column will permanently remove the data stored in that column. It is important to make sure that the deletion of the column will not result in any loss of important data.



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.



  • The SELECT statement in SQL is used to retrieve data from a table.

Here is the syntax for using the SELECT statement in SQL:

SELECT column1, column2, ... FROM table_name;
  • column1, column2, … are the names of the columns that you want to retrieve from the table_name. If you omit the column names, all columns will be retrieved.
  • table_name is the name of the table that you want to retrieve data from.

Here is an example of using the SELECT statement to retrieve all columns from the employee table:

SELECT * FROM employee;
  • This query selects all columns from the employee table and returns all rows. The * symbol represents all columns.

Here is an example of using the SELECT statement to retrieve specific columns from the employee table:

SELECT first_name, last_name, salary FROM employee;
  • This query selects only the first_name, last_name, and salary columns from the employee table and returns all rows.



  • SQL injection is a type of security vulnerability that occurs when an attacker is able to inject malicious code into a SQL query in order to access, modify, or delete sensitive data from a database. This type of attack is particularly dangerous because it can bypass authentication and authorization controls and give the attacker full control over the database.
  • To prevent SQL injection attacks, it is important to follow best practices for writing secure SQL statements. This includes using parameterized queries or prepared statements to separate data from the SQL code, validating user input to ensure that it is of the expected type and format, and using appropriate database permissions to limit the amount of access that users have to the database.
  • In addition to these best practices, it is also recommended to use tools such as firewalls, intrusion detection systems, and web application firewalls to monitor network traffic and detect potential SQL injection attacks. You can also implement input validation rules and use encryption technologies to protect sensitive data stored in the database.
  • It is also important to stay up-to-date with patches and updates for your database management system, as many security vulnerabilities are discovered and fixed over time. Regular security assessments, penetration testing, and code reviews can also help identify and address potential SQL injection vulnerabilities.
  • 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.

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.

Some common types of SQL functions include:

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



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

Advantages of using views:

  1. Abstraction :
  • A view can simplify complex queries by abstracting away the underlying details of the tables involved.
  1. Security :
  • A view can restrict access to certain columns or rows of a table, providing a level of security.
  1. Performance :
  • A view can be indexed, providing improved performance for frequently executed queries.
  1. 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;
  1. FROM :
  • The FROM clause specifies the table(s) from which to retrieve data. The basic syntax is:
SELECT column1, column2, ... FROM table_name;
  1. 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%20WHERE%20condition%3B” message=”” highlight=”” provider=”manual”/]

  1. 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, ...;
  1. 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;
  1. 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];
  1. 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.

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],
...
);
  1. 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];
  1. 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;
  1. 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;
  1. INSERT :
  • Adds new data to a table. Syntax:
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
  1. UPDATE :
  • Modifies existing data in a table. Syntax:
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
  1. 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;
  1. ROLLBACK :
  • Discards changes made during a transaction. Syntax:
ROLLBACK;
  1. SAVEPOINT :
  • Creates a marker within a transaction to which you can later rollback. Syntax:
SAVEPOINT savepoint_name;
  1. 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.



 

Here’s an example of a WHILE loop in SQL using a stored procedure:

DECLARE @Counter INT = 0
DECLARE @max INT = 10

WHILE ( @Counter <= @max)
BEGIN
PRINT 'The counter value is = ' + CONVERT(VARCHAR,@Counter)
SET @Counter = @Counter + 1
END
  • In this example, the WHILE loop will run 10 times, starting from 0 and incrementing the counter by 1 each time. On each iteration, the value of the counter is selected and displayed. The loop will continue as long as the value of the @Counter is less than the value of @max.
  • This is just one example of how loops can be used in SQL, and the exact syntax and implementation may vary depending on the specific SQL dialect being used.



Here’s an example of an IF statement in SQL using a stored procedure:

DECLARE @num INT = 5;

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.



  • A temporary table in SQL is a table that exists temporarily on the database server and is used to store intermediate results during query execution. They are also known as “temporary tables” or “local temporary tables”. They are usually created with a “#” or “##” prefix and are only accessible within the session that created them. They are automatically dropped when the session ends or the connection is closed. Temporary tables can be used to manipulate data and can have indexes, keys, and constraints just like regular tables. They are particularly useful for complex query operations, such as those that involve multiple joins and aggregations.

 

Categorized in: