Showing posts with label CTE. Show all posts
Showing posts with label CTE. Show all posts

Sunday, May 17, 2026

Window Functions (79–88)

 

Window Functions (79–88)

  1. What is a window function?
    It performs calculations across rows without collapsing them.
  2. What is ROW_NUMBER()?
    Assigns unique row number.
  3. What is RANK()?
    Assigns rank with gaps for ties.
  4. What is DENSE_RANK()?
    Assigns rank without gaps.
  5. Difference between RANK and DENSE_RANK?
    RANK skips numbers after tie; DENSE_RANK does not.
  6. What is PARTITION BY?
    Divides result set into groups for window functions.
  7. Find highest salary in each department.
    Use RANK() with PARTITION BY dept.
  8. What is LEAD()?
    Fetches next row value.
  9. What is LAG()?
    Fetches previous row value.
  10. Scenario: Compare current month sales with previous month.
    Use LAG(sales).

Saturday, May 16, 2026

Subqueries & CTEs (66–78)

 

  1. What is a subquery?
    A query inside another query.
  2. Types of subqueries?
    Single-row, multi-row, correlated.
  3. What is correlated subquery?
    A subquery that depends on outer query.
  4. What is CTE?
    Common Table Expression is a temporary result set.
  5. Why use CTE?
    Improves readability and simplifies complex queries.
  6. Difference between CTE and subquery?
    CTE is reusable in same query; subquery is not.
  7. Can CTE be recursive?
    Yes.
  8. Find 2nd highest salary using subquery.
    SELECT MAX(salary) FROM emp WHERE salary < (SELECT MAX(salary) FROM emp);
  9. Find employees earning above average salary.
    Use subquery with AVG(salary).
  10. What is EXISTS?
    Checks if subquery returns rows.
  11. What is NOT EXISTS?
    Checks if subquery returns no rows.
  12. Difference between IN and EXISTS?
    IN compares values; EXISTS checks row existence.
  13. Which performs better: IN or EXISTS?
    EXISTS is better for large datasets.