SQLQUESTIONS
SQLQUESTIONS
It stands for Structured Query Language, and it's a programming language used
for interaction with relational database management systems (RDBMS). This includes
fetching, updating, inserting, and removing data from tables.
11. What is an SQL query, and what types of queries do you know?
A query is a piece of code written in SQL to access or modify data from a
database.
There are two types of SQL queries: select and action queries. The first ones
are used to retrieve the necessary data (this also includes limiting, grouping,
ordering the data, extracting the data from multiple tables, etc.), while the
second ones are used to create, add, delete, update, rename the data, etc.
RIGHT (OUTER) JOIN - returns all records from the right table and those records
from the left table that satisfy a defined join condition.
SYNTAX:
SELECT *
FROM Table_A A
RIGHT JOIN Table_B B
ON A.col = B.col;
FULL (OUTER) JOIN - returns all records from both (or all) tables. It can be
considered as a combination of left and right joins.
SYNTAX:
SELECT *
FROM Table_A A
FULL JOIN Table_B B
ON A.col = B.col;
EXAMPLE:
CREATE TABLE Students ( /* Create table with foreign key - Way 1 */
ID INT NOT NULL
Name VARCHAR(255)
LibraryID INT
PRIMARY KEY (ID)
FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
);
Non-unique indexes, on the other hand, are not used to enforce constraints on
the tables with which they are associated. Instead, non-unique indexes are used
solely to improve query performance by maintaining a sorted order of data values
that are used frequently.
Clustered index - defines the physical order of records of a database table and
performs data searching based on the key values. A table can have only one
clustered index.
Non-clustered index - keeps the order of the table records that don't match the
physical order of the actual data on the disk. It means that the data is stored in
one place and a non-clustered index - in another one. A table can have multiple
non-clustered indexes.
29. What are some common statements used with the SELECT query?
The most common ones are FROM, GROUP BY, JOIN, WHERE, ORDER BY, LIMIT, and
HAVING.
We can specify that we need a descending order using the DESC keyword;
otherwise, the order will be ascending by default. Also, we can sort by more than
one column and specify for each one, ascending or descending order separately. For
example:
37. What is the DISTINCT statement and how do you use it?
This statement is used with the SELECT statement to filter out duplicates and
return only unique values from a column of a table. The syntax is:
40. What is NULL value? How is it different from zero or a blank space?
A NULL value indicates the absence of data for a certain cell of a table.
Instead, zero is a valid numeric value, and an empty string is a legal string of
zero length.
UCASE() (in other SQL flavors - UPPER()) - returns a string converted to the
upper case
LCASE() (in other SQL flavors - LOWER()) - returns a string converted to the
lower case
INITCAP() - returns a string converted to the title case (i.e., each word of the
string starts from a capital letter)
CONCAT() - joins two or more string values appending the second string to the
end of the first one
SUBSTR() - returns a part of a string satisfying the provided start and end
points
LENGTH() (in other SQL flavors - LEN()) - returns the length of a string,
including the blank spaces
REPLACE() - replaces all occurrences of a defined substring in a provided string
with another substring
INSTR() - returns the numeric position of a defined substring in a provided
string
LPAD() and RPAD() - return the padding of the left-side/right-side character for
right-justified/left-justified value
TRIM() - removes all the defined characters, as well as white spaces, from the
left, right, or both ends of a provided string
48. What is the default data ordering with the ORDER BY statement, and how do you
change it?
By default, the order is ascending. To change it to descending, we need to add
the DESC keyword as follows:
51. What is the difference between a primary key and a unique key?
While both types of keys ensure unique values in a column of a table, the first
one uniquely identifies each record of the table, and the second one prevents
duplicates in that column.
53. What is the order of appearance of the common statements in the SELECT query?
SELECT - FROM - JOIN - ON - WHERE - GROUP BY - HAVING - ORDER BY - LIMIT
54. In which order the interpreter executes the common statements in the SELECT
query?
FROM - JOIN - ON - WHERE - GROUP BY - HAVING - SELECT - ORDER BY - LIMIT
62. What is the difference between renaming a column and giving an alias to it?
Renaming a column means permanently changing its actual name in the original
table. Giving an alias to a column means giving it a temporary name while executing
an SQL query, with the purpose to make the code more readable and compact.
CASE
WHEN condition_1 THEN value_1
WHEN condition_2 THEN value_2
WHEN condition_3 THEN value_3
...
ELSE value
END;
66. What is the difference between the DELETE and TRUNCATE statements?
DELETE is a reversible DML (Data Manipulation Language) command used to delete
one or more rows from a table based on the conditions specified in the WHERE
clause. Instead, TRUNCATE is an irreversible DDL (Data Definition Language) command
used to delete all rows from a table. DELETE works slower than TRUNCATE. Also, we
can't use the TRUNCATE statement for a table containing a foreign key.
67. What is the difference between the DROP and TRUNCATE statements?
DROP deletes a table from the database completely, including the table structure
and all the associated constraints, relationships with other tables, and access
privileges. TRUNCATE deletes all rows from a table without affecting the table
structure and constraints. DROP works slower than TRUNCATE. Both are irreversible
DDL (Data Definition Language) commands.
68. What is the difference between the HAVING and WHERE statements?
The first one works on aggregated data after they are grouped, while the second
one checks each row individually. If both statements are present in a query, they
appear in the following order: WHERE - GROUP BY - HAVING. The SQL engine interprets
them also in the same order.
In this way, we can also delete multiple records if they satisfy the provided
condition.
To select all odd records, the syntax is identical in both cases, only that we
would use the inequality operator <> instead of =.
78. How to find the values in a text column of a table that start with a certain
letter?
Using the LIKE operator in combination with the % and _ wildcards. For example,
we need to find all surnames in a table that start with "A". The query is:
Here, we assume that a surname must contain at least two letters. Without this
assumption (meaning that a surname can be just A), the query is as follows:
SELECT id
FROM table_name
ORDER BY id DESC
LIMIT 1;
SELECT TOP 1 id
FROM table_name
ORDER BY id DESC
SELECT *
FROM students
WHERE first_name NOT LIKE 'K%'
SELECT *
FROM students
WHERE first_name LIKE '%Q%'
SELECT *
FROM students
WHERE first_name LIKE '__K%'
82. How to create empty tables with the same structure as another table?
Creating empty tables with the same structure can be done smartly by fetching
the records of one table into a new table using the INTO operator while fixing a
WHERE clause to be false for all records. Hence, SQL prepares the new table with a
duplicate structure to accept the fetched records but since no records get fetched
due to the WHERE clause in action, nothing is inserted into the new table.
85. What is Collation? What are the different types of Collation Sensitivity?
Collation refers to a set of rules that determine how data is sorted and
compared. Rules defining the correct character sequence are used to sort the
character data. It incorporates options for specifying case sensitivity, accent
marks, kana character types, and character width. Below are the different types of
collation sensitivity:
EXAMPLE:
DECLARE @name VARCHAR(50) /* Declare All Required Variables */
DECLARE db_cursor CURSOR FOR /* Declare Cursor Name*/
SELECT name
FROM myDB.students
WHERE parent_name IN ('Sara', 'Ansh')
OPEN db_cursor /* Open cursor and Fetch data into @name */
FETCH next
FROM db_cursor
INTO @name
CLOSE db_cursor /* Close the cursor and deallocate the resources */
DEALLOCATE db_cursor
TRUNCATE command is used to delete all the rows from the table and free the
space containing the table.
DROP command is used to remove an object from the database. If you drop a
table, all the rows in the table are deleted and the table structure is removed
from the database.
A scalar function returns a single value based on the input value. Following are
the widely used SQL scalar functions:
98. How can you find the Nth highest salary from an “employee” table without using
the TOP or limit method?
This can be achieved by leveraging the dense_rank function:
SELECT * FROM
(
SELECT e.name, e.salary,
DENSE_RANK() OVER(ORDER BY salary DESC) AS salary_rank
FROM employees e
) ranked_salaries
The inner query ranks salaries in descending order assigning the nth rank number
to the nth highest salaried employee. Outer query filters on the rank number to
only select the record with the desired nth highest salary, avoiding limits.
99. What is SQL injection? How can you prevent SQL injection attacks?
SQL injection attacks involve malicious insertion of SQL code snippets via
user input fields to gain unauthorized data access or corrupt databases.
100. What are CTEs in SQL? When would you use them?
CTEs or Common Table Expressions represent temporary defined sets comprising
a query statement that provides input to subsequent statements.
WITH cte_running_totals AS (
SELECT
ID, Date, Value,
SUM(Value) OVER(ORDER BY DATE) AS running_total
FROM Sales
)
SELECT *
FROM cte_running_totals;
102. Explain the difference between a correlated subquery and a nested subquery.
A correlated subquery references data from the outer query in its WHERE
clause. A nested subquery can be placed anywhere in the outer query and doesn't
directly reference the outer table.
103. Write a query to find the average salary for each department, excluding
employees with salaries above a certain threshold.
SELECT Department, AVG(Salary) AS AverageSalary
FROM (
SELECT Department, Salary
FROM Employees
WHERE Salary <= (SELECT MAX(Salary) FROM Employees) / 2
) AS Subquery
GROUP BY Department;
104. How can you handle missing values (NULL) in your queries?
you can use functions like ISNULL, COALESCE, or CASE statements to handle
missing values. These functions allow you to specify alternative values or perform
different operations based on NULL checks.
105. Explain the difference between UNION and UNION ALL in SQL.
UNION removes duplicate rows from the combined result set, while UNION ALL
includes all rows, even duplicates, from the selected queries.
106. Write a query to find the difference in days between the order date and the
ship date for each order.
SELECT OrderID, DATEDIFF(day, OrderDate, ShipDate) AS DaysDiff
FROM Orders;
107. Write a query to find the manager for each employee in a company, even if the
employee doesn't have a manager assigned.
SELECT e.EmployeeID, m.ManagerName
FROM Employees e
LEFT JOIN Employees m ON e.ManagerID = m.EmployeeID;
108. Write a query to pivot data from rows to columns, showing the total sales for
each product category by month.
SELECT Month,
SUM(CASE WHEN ProductCategory = 'Electronics' THEN Sales ELSE 0 END) AS
Electronics,
SUM(CASE WHEN ProductCategory = 'Clothing' THEN Sales ELSE 0 END) AS
Clothing,
... (add more categories)
FROM SalesData
GROUP BY Month;
109. Write a query to find the department with the highest average salary for
employees who have been with the company for more than 2 years.
SELECT TOP 1
d.DepartmentName,
AVG(e.Salary) AS AverageSalary
FROM Employees e
INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID
WHERE e.HireDate < DATEADD(YEAR, -2, GETDATE())
GROUP BY d.DepartmentName
ORDER BY AverageSalary DESC;
110. Write a query to find the nth highest salary in an employee table.
SELECT Salary
FROM Employees
WHERE Salary IN (
SELECT Salary
FROM (
SELECT Salary, ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum
FROM Employees
) AS Subquery
WHERE RowNum = n
);
111. Write a query to find the total number of customers who placed orders in each
quarter of the last year.
112. Write a query to find the manager hierarchy for a specific employee, showing
all levels up to the CEO.
113. Write a query to find the product categories with the highest and lowest total
sales for the previous year.
SELECT TOP 2 ProductCategory, SUM(SalesAmount) AS TotalSales
FROM SalesData
WHERE SaleDate >= DATEADD(year, -1, GETDATE())
GROUP BY ProductCategory
ORDER BY TotalSales DESC, ProductCategory ASC;
114. Write a query to find employees who earn more than the average salary in their
department.
SELECT e.EmployeeID, e.EmployeeName, d.DepartmentName, e.Salary
FROM Employees e
INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID
WHERE e.Salary > (
SELECT AVG(e2.Salary)
FROM Employees e2
WHERE e2.DepartmentID = e.DepartmentID
);
115. Write a query to display the top 2 customers with the most orders in the last
30 days.
SELECT c.Name, COUNT(*) AS NumOrders
FROM Customers c
INNER JOIN Orders o ON c.Customer_ID = o.Customer_ID
WHERE o.Order_Date >= DATEADD(day, -1, GETDATE())
GROUP BY c.Name;
116. Find the month with the highest total order value.
SELECT TOP 1
MONTH(Order_Date) AS Order_Month,
SUM(Order_Total) AS Total_Order_Value
FROM Orders
GROUP BY MONTH(Order_Date)
ORDER BY Total_Order_Value DESC;
119. list all orders placed on specific dates (eg., 2023-07-04 and 2023-07-06) and
their corresponding customer names.
SELECT
c.Name,
o.Order_Date,
o.Order_Total
FROM
Customers c
INNER JOIN
Orders o
ON
c.Customer_ID = o.Customer_ID
WHERE
o.Order_Date IN ('2023-07-04', '2023-07-06');
120. Find the customer who has placed the highest total order value.
SELECT TOP 1
c.Name,
SUM(o.Order_Total) AS Total_Order_Value
FROM
Customers c
INNER JOIN
Orders o
ON
c.Customer_ID = o.Customer_ID
GROUP BY
c.Name
ORDER BY
Total_Order_Value DESC;