SQL CTE, ROW_NUMBER(), and Subqueries Flashcards
From GPT
Q: What does CTE stand for in SQL?
A: Common Table Expression.
Q: What keyword is used to define a CTE?
A: WITH.
Q: True or False: A CTE is a temporary result set that can only be used within the query it’s defined in.
A: True.
Q: How do you structure a basic CTE in SQL?
WITH CTE_name AS (
SELECT column1, column2, …
FROM table_name
WHERE conditions
)
SELECT column1, column2
FROM CTE_name;
Q: True or False: A CTE can reference itself in a recursive query.
A: True.
Q: What is the purpose of the ROW_NUMBER() function in SQL?
A: It assigns a unique, sequential integer to rows within a partition of a result set.
Q: What SQL clause is required with ROW_NUMBER() to define how the rows should be numbered?
A: ORDER BY.
Q: What is the purpose of the PARTITION BY clause with ROW_NUMBER()?
A: It divides the result set into partitions, and the row numbers reset for each partition.
Q: Write a SQL query using ROW_NUMBER() to rank employees by salary in each department.
SELECT department, name, salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS row_num
FROM employees;
Q: True or False: A subquery is a query embedded within another SQL query.
A: True.
Q: Name three places where you can use a subquery in SQL.
A: In the SELECT, FROM, and WHERE clauses.
Q: What’s a scalar subquery?
A: A subquery that returns a single value, often used in the SELECT or WHERE clause.
Q: Write an example of a subquery to find employees with salaries above the average salary.
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Q: What is a correlated subquery?
A: A subquery that references columns from the outer query, recalculating for each row in the outer query.
Q: True or False: A correlated subquery may run multiple times, impacting performance.
A: True.