0% found this document useful (0 votes)
39 views12 pages

SQL 1000+ Questions

Uploaded by

tvrkrishna2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views12 pages

SQL 1000+ Questions

Uploaded by

tvrkrishna2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Query retrieves only the first and last names of employees working in
the HR department

a. SELECT first_name, last_name, department FROM employees


WHERE department = 'HR';

2. - Adding a new record to the employees table.

a. INSERT INTO employees (first_name, last_name, department,


salary) VALUES ('John', 'Doe', 'Finance', 60000);

3. - Updating the salary for a specific employee.

a. UPDATE employees SET salary = 65000 WHERE first_name =


'John' AND last_name = 'Doe';

4. -- Deleting an employee record.


a. DELETE FROM employees WHERE first_name = 'John' AND
last_name = 'Doe';

5. - Creating a table with various data types.

a. CREATE TABLE employees (id INT PRIMARY KEY, first_name


VARCHAR (50), last_name VARCHAR (50), salary DECIMAL (10, 2),
join_date DATE, is_active BOOLEAN);

6. - Calculating a 10% bonus for each employee.

a. SELECT first_name, last_name, salary, salary * 0.10 AS bonus


FROM employees;

7. - Retrieving employees with a salary greater than 50,000.


a. SELECT first_name, last_name, salary FROM employees WHERE
salary > 50000;

8. -- Selecting employees with complex conditions.

a. SELECT first_name, last_name FROM employees WHERE


department = 'Finance' AND salary > 50000;

9. - Finding employees who joined after January 1, 2023.

a. SELECT first_name, last_name, join_date FROM employees


WHERE join_date > '2023-01-01';

10. -- Retrieving distinct departments.


a. SELECT DISTINCT department FROM employees;

11. -- Retrieving the top 3 highest-paid employees.


a. SELECT TOP 3 first_name, last_name, salary FROM employees
ORDER BY salary DESC;

12. A PRIMARY KEY is a constraint that ensures each row in a table is


uniquely identifiable. It guarantees two properties:
a. Uniqueness: No two rows can have the same value for the
primary key column(s).
b. Non-nullability: A primary key column cannot contain NULL value

13. A FOREIGN KEY establishes a link between two tables by referencing


the primary key of another table. It enforces referential integrity,
ensuring that the value in the foreign key column must exist in the
referenced table. If the referenced value is deleted or updated, SQL can
prevent, cascade, or restrict the change to maintain data integrity

a. CREATE TABLE departments (department_id INT PRIMARY KEY,


department_name VARCHAR (50) );

b. CREATE TABLE employees (employee_id INT PRIMARY KEY,


first_name VARCHAR (50),
department_id INT, FOREIGN KEY (department_id) REFERENCES
departments(department_id) );

14. The GROUP BY clause groups rows with the same values into
categories. It is usually paired with aggregate functions like SUM(),
COUNT(), or AVG() to calculate metrics for each group.

a. SELECT department, SUM(salary) AS total_salary FROM


employees GROUP BY department;

15. - Filtering departments with total salaries greater than 100,000.

a. SELECT department, SUM (salary) AS total_salary FROM


employees GROUP BY department HAVING SUM (salary) >
100000;

16. The ORDER BY clause sorts the results of a query based on one or
more columns. You can specify ascending (ASC) or descending (DESC)

-- Retrieving employees sorted by salary in descending order.


a. SELECT first_name, last_name, salary FROM employees ORDER
BY salary DESC;
17. INNER JOIN: Retrieves only the rows where there is a match in both
tables. If no matching rows are found, they are excluded from the
result.

a. SELECT e.first_name, d.department_name FROM employees e


INNER JOIN departments d ON e.department_id =
d.department_id;

18. OUTER JOIN: Returns all rows from one or both tables, including those
without matches. Types of outer joins:

a. SELECT e.first_name, d.department_name FROM employees e


FULL OUTER JOIN departments d ON e.department_id =
d.department_id;

19. A CROSS JOIN returns the Cartesian product of two tables

a. SELECT e.first_name, d.department_name FROM employees e


CROSS JOIN departments d;

20. A correlated subquery is a subquery that depends on the outer query


for its values.

a. SELECT e1.first_name, e1.salary


FROM employees e1
WHERE e1.salary > (
SELECT AVG(e2.salary) FROM employees e2
WHERE e2.department_id = e1.department_id );
21. NULL represents an unknown or missing value. For comparisons with
NULL we have to use IS NULL or IS NOT NULL

a. - Using LEFT JOIN to retain rows with NULL values.


SELECT e.first_name, d.department_name
FROM employees e
LEFT JOIN departments d
ON e.department_id = d.department_id;

b. -- Filtering rows with NULL values.


SELECT * FROM employees WHERE department_id IS NULL;

22. A window function performs calculations across a set of table rows


related to the current row, without collapsing rows into groups like
GROUP BY. Used to perform operations like running totals, ranking, and
moving average

a. SELECT first_name, department_id, salary,


RANK() OVER (PARTITION BY department_id ORDER BY salary
DESC) AS rank
FROM employees;
23. GROUP BY VS PARTITION BY
Concept Description
Groups rows with the same values into summary
rows, usually used with aggregate functions like
COUNT, SUM, etc.
GROUP BY
SELECT department_id, AVG(salary) AS avg_salary
FROM employees GROUP BY department_id;
Used with window functions to divide the result set
into partitions and perform calculations within each
partition without reducing the number of rows.
PARTITION
BY
SELECT name, department_id, AVG(salary)
OVER (PARTITION BY department_id) AS avg_salary
FROM employees;

24. WHERE Vs HAVING


Clause Description
Filters rows before any aggregation occurs.

SELECT department_id, salary


WHERE FROM employees
WHERE salary > 50000;

HAVIN Filters aggregated data after applying the GROUP BY clause.


G
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 60000;

25. An index improves the speed of data retrieval by providing quick


access paths to table rows but require additional storage and can slow
down INSERT, UPDATE, and DELETE operations due to maintenance
overhead.
a. -- Creating an index on the salary column.
CREATE INDEX idx_salary ON employees(salary);

b. -- Query that benefits from the index.


SELECT * FROM employees WHERE salary > 50000;

26. Normalization is the process of organizing / splitting data into smaller,


related tables using relationships & foreign keys.
a. Advantages: ● Reduces redundancy. ● Ensures data consistency
and integrity. ● Saves storage space.
b. Disadvantages: ● Complex joins are required to retrieve data. ●
Query performance can be slower in highly normalized
databases due to multiple joins.

CREATE TABLE employees ( employee_id INT PRIMARY KEY,


first_name VARCHAR(50), department_id INT );
CREATE TABLE departments ( department_id INT PRIMARY KEY,
department_name VARCHAR(50) );
c. This structure ensures each department is stored only once.

27. Denormalization is the process of combining related tables into a


single table Example: Instead of having separate employees and
departments tables, denormalization combines them:
a. CREATE TABLE employee_details ( employee_id INT PRIMARY
KEY, first_name VARCHAR(50), department_name
VARCHAR(50) );.
28. SQL databases are ACID-compliant, meaning they ensure the following
properties for transactions:
a. Atomicity: All operations in a transaction succeed or fail as a
whole.
b. Consistency: The database moves from one valid state to
another.
c. Isolation: Transactions are isolated from each other until
committed.
d. Durability: Once committed, changes are permanent. For

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100
WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE
account_id = 2;
COMMIT;
If any part of the transaction fails, the entire transaction is rolled back
to maintain consistency.

29. A stored procedure is a set of precompiled SQL statements that can be


executed as a program. Used for inserting, updating, or deleting data.
-- Creating a stored procedure to give a bonus to employees.
CREATE PROCEDURE give_bonus
(IN bonus_amount DECIMAL(10, 2))
BEGIN UPDATE employees SET salary = salary + bonus_amount;
END;

-- Calling the stored procedure.


CALL give_bonus(500);
30. Indexes improve query performance by enabling quick data lookups,
but there are key differences between clustered and non-clustered
indexes: ● Clustered Index: POWERMIND.IN ECOMNOWVENTURES 27 ○
It sorts and stores the actual data rows of the table in the order of the
index key. ○ There can only be one clustered index per table since the
physical order of the table can only follow one sequence. ○ Example: If
a clustered index is created on employee_id, the table will store rows
physically ordered by employee_id. ● Non-Clustered Index: ○ It stores a
separate structure (a pointer) with the indexed column and a reference
to the actual data row. ○ A table can have multiple non-clustered
indexes, each improving search on different columns. For Example: --
Creating a clustered index. CREATE CLUSTERED INDEX idx_employee_id
ON employees(employee_id); -- Creating a non-clustered index. CREATE
NONCLUSTERED INDEX idx_salary ON employees(salary); The clustered
index orders the entire table by employee_id, while the non clustered
index on salary allows efficient lookups for salary-based queries. 32.
What is the difference between DELETE, TRUNCATE, and DROP?
Answer: ● DELETE: ○ Removes specific rows from a table based on a
condition. ○ Supports ROLLBACK if used within a transaction. ○ Slower
than TRUNCATE as each row deletion is logged. ● TRUNCATE:
POWERMIND.IN ECOMNOWVENTURES 28 ○ Removes all rows from a
table quickly without logging individual deletions. ○ Cannot be rolled
back in most databases. ○ Resets identity counters, like auto-increment
columns. ● DROP: ○ Deletes the table and its structure from the
database. ○ All data and indexes are permanently removed. For
Example: -- Deleting specific rows. DELETE FROM employees WHERE
department = 'HR'; -- Truncating the entire table. TRUNCATE TABLE
employees; -- Dropping the table. DROP TABLE employees; Use DELETE
to remove specific rows, TRUNCATE to clear all data but retain the
structure, and DROP to remove the table completely. 33. What is the
purpose of CTE (Common Table Expression) in SQL? Answer: A
Common Table Expression (CTE) provides a temporary result set that
simplifies complex queries by breaking them into smaller parts. CTEs
improve readability and help avoid using subqueries multiple times in a
query. They are useful when performing joins, aggregates, or recursive
operations. For Example: POWERMIND.IN ECOMNOWVENTURES 29 --
Using CTE to calculate average salary by department. WITH dept_avg
AS ( SELECT department_id, AVG(salary) AS avg_salary FROM
employees GROUP BY department_id ) SELECT e.first_name, e.salary,
da.avg_salary FROM employees e JOIN dept_avg da ON
e.department_id = da.department_id; Here, the CTE dept_avg stores
the average salaries by department, which is used in the main query to
display employees along with their department's average salary. 34.
How does a recursive CTE work in SQL? Answer: A recursive CTE is a
self-referencing query that continues to execute until a specified
condition is met. Recursive CTEs are useful when working with
hierarchical data like employee-manager relationships or directory
structures. The recursive part of the query repeatedly references the
CTE itself. For Example: -- Recursive CTE to find employee hierarchies.
WITH RECURSIVE employee_hierarchy AS ( -- Anchor member:
Employees without managers. SELECT employee_id, first_name,
manager_id, 1 AS level FROM employees WHERE manager_id IS NULL
UNION ALL -- Recursive member: Employees reporting to managers.
POWERMIND.IN ECOMNOWVENTURES 30 SELECT e.employee_id,
e.first_name, e.manager_id, eh.level + 1 FROM employees e JOIN
employee_hierarchy eh ON e.manager_id = eh.employee_id ) SELECT *
FROM employee_hierarchy; This query builds a hierarchy by recursively
joining employees to their managers and adding levels of reporting. 35.
What is the difference between RANK(), DENSE_RANK(), and
ROW_NUMBER()? Answer: These window functions assign a rank or
number to each row within a partition but behave differently when
handling ties: ● RANK(): Skips numbers if there are ties (e.g., 1, 2, 2, 4).
● DENSE_RANK(): Does not skip numbers, even if there are ties (e.g., 1,
2, 2, 3). ● ROW_NUMBER(): Assigns a unique sequential number to
each row, without considering ties. For Example: -- Comparing RANK(),
DENSE_RANK(), and ROW_NUMBER(). SELECT first_name, salary,
RANK() OVER (ORDER BY salary DESC) AS rank, DENSE_RANK() OVER
(ORDER BY salary DESC) AS dense_rank, ROW_NUMBER() OVER (ORDER
BY salary DESC) AS row_number FROM employees; If two employees
have the same salary, RANK() will skip the next number, while
DENSE_RANK() will not. POWERMIND.IN ECOMNOWVENTURES 31 36.
What is the difference between transactional (OLTP) and analytical
(OLAP) databases? Answer: ● Transactional Databases (OLTP): ○ Handle
real-time operations such as inserts, updates, and deletes. ○ Prioritize
data integrity and speed for individual transactions. ○ Example: Bank
systems, e-commerce websites. ● Analytical Databases (OLAP): ○
Optimized for complex queries and data analysis over large datasets. ○
Used for generating reports and trends over historical data. ○ Example:
Business intelligence platforms, data warehouses. 37. How do triggers
work in SQL, and when are they used? Answer: A trigger is a stored
procedure that automatically executes before or after an event occurs
on a table, such as an INSERT, UPDATE, or DELETE. Triggers enforce
business rules and maintain data integrity by validating or recording
changes. For Example: -- Creating a trigger to log salary updates.
CREATE TRIGGER log_salary_update AFTER UPDATE ON employees FOR
EACH ROW BEGIN INSERT INTO salary_log (employee_id, old_salary,
new_salary) VALUES (OLD.employee_id, OLD.salary, NEW.salary); END;
POWERMIND.IN ECOMNOWVENTURES 32 This trigger logs the old and
new salaries whenever an employee's salary is updated. 38. What is
partitioning, and how does it improve performance? Answer:
Partitioning splits a large table into smaller pieces based on a column’s
value, such as date or region. Queries only scan the relevant partitions
instead of the entire table, improving performance for large datasets.
For Example: -- Creating a partitioned table. CREATE TABLE orders
( order_id INT, order_date DATE, customer_id INT ) PARTITION BY
RANGE (YEAR(order_date)) ( PARTITION p_2022 VALUES LESS THAN
(2023), PARTITION p_2023 VALUES LESS THAN (2024) ); This table is
partitioned by year, allowing efficient queries on specific years. 39.
What is the purpose of the MERGE statement in SQL? Answer: The
MERGE statement performs upserts—it inserts, updates, or deletes
records based on a condition. It is useful when synchronizing two
datasets, as it combines multiple operations into a single query. For
Example: POWERMIND.IN ECOMNOWVENTURES 33 -- Merging data
into the employees table. MERGE INTO employees e USING
new_employees n ON e.employee_id = n.employee_id WHEN
MATCHED THEN UPDATE SET e.salary = n.salary WHEN NOT MATCHED
THEN INSERT (employee_id, first_name, salary) VALUES
(n.employee_id, n.first_name, n.salary); This query updates existing
employees' salaries or inserts new employees. 40. How does SQL
handle deadlocks, and how can they be prevented? Answer: A deadlock
occurs when two transactions block each other by holding resources
the other needs. SQL databases detect and resolve deadlocks by
terminating one of the transactions and rolling it back to free
resources. Prevention Techniques: ● Access resources in a consistent
order across transactions. ● Keep transactions short to minimize lock
times. ● Use row-level locks instead of table-level locks. For Example: --
Example of a potential deadlock. -- Transaction 1: Locks row 1. BEGIN
TRANSACTION; UPDATE employees SET salary = salary + 1000 WHERE
employee_id = 1; POWERMIND.IN ECOMNOWVENTURES 34 --
Transaction 2: Locks row 1. BEGIN TRANSACTION; UPDATE employees
SET salary = salary - 500 WHERE employee_id = 1; SQL detects the
deadlock and rolls back one transaction to resolve the conflict..

You might also like