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

SQL 2

Uploaded by

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

SQL 2

Uploaded by

Riddhi Sarnaik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Q: Write a query to find the second highest salary from an employee table.

A: SELECT MAX(salary) AS second_highest_salary FROM employees WHERE salary < (SELECT

MAX(salary) FROM employees);

Q: How would you use a JOIN to combine data from two tables: one with employee information and

another with department information?

A: SELECT e.employee_id, e.name, d.department_name FROM employees e JOIN departments d

ON e.department_id = d.department_id;

Q: Write a query to retrieve employees who joined in the last 30 days.

A: SELECT * FROM employees WHERE join_date >= CURDATE() - INTERVAL 30 DAY;

Q: How can you handle NULL values in SQL when performing calculations?

A: Use the COALESCE() function to replace NULL with a default value, e.g., SELECT

COALESCE(column_name, 0) AS result;

Q: Explain the difference between WHERE and HAVING clauses in SQL.

A: WHERE filters rows before grouping, while HAVING filters groups after grouping.

Q: Write a query to find the count of employees in each department.

A: SELECT department_id, COUNT(*) AS employee_count FROM employees GROUP BY

department_id;

Q: How would you optimize a slow-running query?

A: Use indexes, avoid SELECT *, optimize joins, analyze query plans, and reduce subqueries.

Q: Write a query to update the salary of all employees by 10%.

A: UPDATE employees SET salary = salary * 1.10;

Q: Explain the purpose of indexes and how they improve query performance.

A: Indexes speed up data retrieval by allowing the database to find data without scanning every row.

Q: Write a query to create a new table with columns for employee ID, name, and salary.

A: CREATE TABLE employees (employee_id INT PRIMARY KEY, name VARCHAR(50), salary

DECIMAL(10, 2));

Q: How would you retrieve the top 5 highest-paid employees from an employee table?
A: SELECT * FROM employees ORDER BY salary DESC LIMIT 5;

Q: Write a query to delete duplicate rows from a table based on a specific column.

A: DELETE FROM employees WHERE id NOT IN (SELECT MIN(id) FROM employees GROUP BY

column_name);

Q: Explain the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN.

A: INNER JOIN returns matching rows; LEFT JOIN includes unmatched rows from the left; RIGHT

JOIN includes unmatched rows from the right; FULL OUTER JOIN includes unmatched rows from

both.

Q: Write a query to calculate the average salary for each department.

A: SELECT department_id, AVG(salary) AS average_salary FROM employees GROUP BY

department_id;

Q: How do you use the CASE statement in SQL, and provide an example?

A: CASE is used for conditional expressions, e.g., SELECT name, CASE WHEN salary > 5000

THEN 'High' ELSE 'Low' END AS salary_level FROM employees;

Q: Write a query to find employees who have not been assigned to any department.

A: SELECT * FROM employees WHERE department_id IS NULL;

Q: Explain the concept of a primary key and a foreign key in SQL.

A: A primary key uniquely identifies rows in a table, while a foreign key enforces relationships

between tables.

Q: Write a query to add a new column to an existing table.

A: ALTER TABLE employees ADD COLUMN age INT;


SQL clauses are keywords used in SQL statements to define and manipulate data.
Below are the key SQL clauses:

---

1. SELECT

Used to retrieve specific columns from a table.


Example:

SELECT name, age FROM employees;

---

2. FROM

Specifies the table from which to retrieve data.


Example:

SELECT * FROM orders;

---

3. WHERE

Filters rows based on specified conditions.


Example:

SELECT * FROM products WHERE price > 100;

---

4. GROUP BY

Groups rows that have the same values in specified columns.


Example:
SELECT department, COUNT(*) FROM employees GROUP BY department;

---

5. HAVING

Filters groups created by GROUP BY.


Example:

SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 50000;

---

6. ORDER BY

Sorts the result set by one or more columns.


Example:

SELECT name, age FROM employees ORDER BY age DESC;

---

7. LIMIT

Restricts the number of rows returned.


Example:

SELECT * FROM customers LIMIT 10;

---

8. OFFSET

Skips a specific number of rows before returning results. Often used with LIMIT.
Example:
SELECT * FROM customers LIMIT 10 OFFSET 5;

---

9. JOIN

Combines rows from two or more tables based on a related column.


Types of JOINs:

INNER JOIN

LEFT JOIN

RIGHT JOIN

FULL OUTER JOIN

Example:

SELECT employees.name, departments.department_name


FROM employees
INNER JOIN departments
ON employees.department_id = departments.id;

---

10. UNION

Combines results of two or more SELECT statements.


Example:

SELECT name FROM table1


UNION
SELECT name FROM table2;

---
11. DISTINCT

Removes duplicate rows in the result set.


Example:

SELECT DISTINCT department FROM employees;

---

12. IN

Filters rows where a column's value matches a set of values.


Example:

SELECT * FROM employees WHERE department IN ('HR', 'IT', 'Finance');

---

13. BETWEEN

Filters rows within a range of values.


Example:

SELECT * FROM products WHERE price BETWEEN 50 AND 100;

---

14. LIKE

Searches for patterns in a column.


Example:

SELECT * FROM employees WHERE name LIKE 'A%';

---
15. IS NULL / IS NOT NULL

Checks for NULL or non-NULL values.


Example:

SELECT * FROM orders WHERE delivery_date IS NULL;

---

16. CASE

Implements conditional logic in queries.


Example:

SELECT name,
CASE
WHEN salary > 50000 THEN 'High'
ELSE 'Low'
END AS salary_category
FROM employees;

---

17. AS

Used to rename a column or table with an alias.


Example:

SELECT name AS employee_name FROM employees;

---

18. WITH

Defines a Common Table Expression (CTE) for reuse within a query.


Example:
WITH recent_sales AS (
SELECT * FROM sales WHERE sale_date > '2024-01-01'
)
SELECT * FROM recent_sales;

---

19. EXISTS

Checks for the existence of rows returned by a subquery.


Example:

SELECT name FROM employees WHERE EXISTS (


SELECT 1 FROM departments WHERE employees.department_id = departments.id
);

---

20. ALL

Compares a value against all values in a list or subquery.


Example:

SELECT * FROM products WHERE price > ALL (SELECT price FROM discounts);

---

21. ANY

Compares a value against any value in a list or subquery.


Example:

SELECT * FROM products WHERE price > ANY (SELECT price FROM discounts);

---

22. INTERSECT
Returns rows that are present in both SELECT statements.
Example:

SELECT name FROM table1


INTERSECT
SELECT name FROM table2;

---

23. EXCEPT (or MINUS in some SQL dialects)

Returns rows from the first SELECT statement that are not in the second.
Example:

SELECT name FROM table1


EXCEPT
SELECT name FROM table2;

---

24. FETCH

Retrieves a specific number of rows after sorting (similar to LIMIT).


Example:

SELECT * FROM employees ORDER BY salary DESC FETCH FIRST 5 ROWS ONLY;

---

25. PARTITION BY

Divides data into partitions for window functions.


Example:

SELECT name, salary,


RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank
FROM employees;

---

26. PIVOT

Used to transform rows into columns (available in some SQL dialects like Oracle and SQL Server).
Example:

SELECT * FROM (
SELECT department, salary FROM employees
) PIVOT (
SUM(salary) FOR department IN ('HR', 'IT', 'Finance')
);

---

27. UNPIVOT

Transforms columns into rows (specific to certain SQL dialects).


Example:

SELECT * FROM sales


UNPIVOT (sales_value FOR product IN (product_a, product_b, product_c));

---

28. MERGE

Performs an upsert (insert or update) operation.


Example:

MERGE INTO employees AS target


USING new_employees AS source
ON target.id = source.id
WHEN MATCHED THEN UPDATE SET target.salary = source.salary
WHEN NOT MATCHED THEN INSERT (id, name, salary) VALUES (source.id, source.name, source.salary);
---

29. APPLY

Allows applying a table-valued function or query to each row from another query (specific to SQL Server).
Example:

SELECT e.name, d.total_sales


FROM employees e
CROSS APPLY (
SELECT SUM(sales) AS total_sales FROM sales WHERE sales.employee_id = e.id
) d;

---

30. RECURSIVE WITH (Recursive CTE)

Used for hierarchical or recursive queries.


Example:

WITH RECURSIVE employee_hierarchy AS (


SELECT id, name, manager_id FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees e
INNER JOIN employee_hierarchy h ON e.manager_id = h.id
)
SELECT * FROM employee_hierarchy;

COMMANDS

1. Data Definition Language (DDL) Commands

These commands define the structure of the database, such as tables, indexes, and schemas.

CREATE: Creates a new database object (table, view, index, etc.).


CREATE TABLE employees (id INT, name VARCHAR(50), age INT);

ALTER: Modifies an existing database object (e.g., adding a column).

ALTER TABLE employees ADD salary INT;

DROP: Deletes an existing database object.

DROP TABLE employees;

TRUNCATE: Removes all rows from a table without logging individual row deletions.

TRUNCATE TABLE employees;

RENAME: Renames a database object.

ALTER TABLE employees RENAME TO staff;

---

2. Data Manipulation Language (DML) Commands

These commands deal with manipulating data in the database.

SELECT: Retrieves data from one or more tables.

SELECT * FROM employees;

INSERT: Adds new rows to a table.

INSERT INTO employees (id, name, age) VALUES (1, 'John Doe', 30);

UPDATE: Modifies existing data in a table.

UPDATE employees SET age = 31 WHERE id = 1;

DELETE: Removes rows from a table.

DELETE FROM employees WHERE id = 1;


---

3. Data Control Language (DCL) Commands

These commands deal with access control and permissions.

GRANT: Gives permissions to users.

GRANT SELECT, INSERT ON employees TO user1;

REVOKE: Removes permissions from users.

REVOKE INSERT ON employees FROM user1;

---

4. Transaction Control Language (TCL) Commands

These commands manage transactions within a database.

COMMIT: Saves all changes made in the transaction.

COMMIT;

ROLLBACK: Undoes changes made in the transaction.

ROLLBACK;

SAVEPOINT: Sets a point within a transaction to which you can roll back.

SAVEPOINT save1;

SET TRANSACTION: Sets properties for a transaction.

SET TRANSACTION READ ONLY;

---

5. Data Query Language (DQL) Command


This is a subset of DML, used specifically for querying data.

SELECT: Retrieves data from the database.

SELECT name, age FROM employees WHERE age > 25;

---

6. Other SQL Commands

These commands are often specific to database management systems or advanced SQL usage.

EXPLAIN: Shows the execution plan for a query.

EXPLAIN SELECT * FROM employees;

DESCRIBE (or DESC): Displays the structure of a table.

DESCRIBE employees;

SHOW: Displays database objects or settings.

SHOW TABLES;

USE: Selects a database to work on.

USE company_db;

BACKUP DATABASE: Creates a backup of the database (specific to some DBMS).

BACKUP DATABASE company_db TO DISK = 'backup.bak';

RESTORE DATABASE: Restores a database from a backup (specific to some DBMS).

RESTORE DATABASE company_db FROM DISK = 'backup.bak';

---

7. Advanced Commands
These are used for advanced database operations.

MERGE: Performs an upsert operation (insert or update).

MERGE INTO employees USING new_employees ON employees.id = new_employees.id


WHEN MATCHED THEN UPDATE SET employees.salary = new_employees.salary
WHEN NOT MATCHED THEN INSERT (id, name, salary) VALUES (new_employees.id, new_employees.name,
new_employees.salary);

ANALYZE: Collects statistics about a table for query optimization (specific to some DBMS).

ANALYZE TABLE employees;

LOCK: Locks a table for a specific operation.

LOCK TABLE employees IN EXCLUSIVE MODE;

You might also like