Detailed_SQL_Interview_Questions
Detailed_SQL_Interview_Questions
SQL (Structured Query Language) is a standard language for managing relational databases. It is
crucial in data analytics for retrieving, filtering, aggregating, and analyzing structured data efficiently.
Example Query:
SELECT * FROM employees WHERE department = 'Sales';
2. Difference between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN
SQL joins are used to combine records from multiple tables based on a related column.
- INNER JOIN: Returns only matching rows.
- LEFT JOIN: Returns all rows from the left table and matching rows from the right.
- RIGHT JOIN: Returns all rows from the right table and matching rows from the left.
- FULL OUTER JOIN: Returns all rows when there is a match in either table.
Example:
SELECT employees.name, departments.department_name FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
Example:
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) >
5;
GROUP BY is used to group rows with similar values, and HAVING filters those groups.
Example:
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary)
> 50000;
SELECT name, COUNT(*) FROM employees GROUP BY name HAVING COUNT(*) > 1;
6. Retrieve unique values from a table
Example:
SELECT department, SUM(salary) FROM employees GROUP BY department;
Example:
SELECT DISTINCT job_title FROM employees;
SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1;
Example:
SELECT name FROM employees WHERE salary = (SELECT MAX(salary) FROM employees);
Example:
WITH dept_salary AS (SELECT department, AVG(salary) AS avg_salary FROM employees
GROUP BY department)
SELECT * FROM dept_salary WHERE avg_salary > 50000;
Example:
SELECT name, department, salary, RANK() OVER (PARTITION BY department ORDER BY salary
DESC) AS rank FROM employees;
Example:
SELECT name FROM employees WHERE department = 'Sales'
UNION
SELECT name FROM employees WHERE department = 'Marketing';
Example:
CREATE INDEX idx_employee_name ON employees(name);
- Use indexes.
- Avoid SELECT *.
- Optimize joins and subqueries.
- Use EXPLAIN PLAN for query optimization.
2. Views in SQL
Example:
CREATE VIEW high_salary_employees AS SELECT * FROM employees WHERE salary > 70000;
Example:
SELECT name, department, salary, RANK() OVER (PARTITION BY department ORDER BY salary
DESC) AS rank FROM employees;
Example:
SELECT name, COALESCE(salary, 0) FROM employees;