SQL Intermediate Flashcards
(40 cards)
What is a subquery in SQL?
A query nested inside another SQL query
How do you use a subquery in a WHERE clause?
SELECT * FROM employees WHERE department_id = (SELECT id FROM departments WHERE name = ‘Sales’);
What is a correlated subquery?
A subquery that uses values from the outer query and runs once per row
What is a common table expression (CTE)?
A temporary named result set defined using WITH
How do you define a CTE?
WITH temp AS (SELECT * FROM employees) SELECT * FROM temp;
What is the difference between a CTE and a subquery?
CTEs improve readability and can be reused; subqueries are embedded and more limited
What is a window function?
A function that performs calculations across a set of table rows related to the current row
What does ROW_NUMBER() do?
Assigns a unique sequential number to each row in the result set
What is PARTITION BY in window functions?
Divides rows into groups before applying the function
What does RANK() do?
Assigns a rank to rows within a partition
How do you find the second highest salary using RANK?
SELECT * FROM (SELECT salary
What is the purpose of COALESCE()?
Returns the first non-NULL value in a list
What does NVL() do in SQL?
Replaces NULL with a specified value (Oracle-specific; COALESCE is standard)
What is a self-join?
A table joined to itself
How do you perform a self-join?
Use table aliases: SELECT a.name
What does the IN operator do?
Checks if a value exists in a list or result of a subquery
What is the difference between IN and EXISTS?
IN compares values; EXISTS checks for row existence and can be faster for correlated subqueries
How do you enforce uniqueness in a column?
Use a UNIQUE constraint
What is a composite primary key?
A primary key made of more than one column
What are indexes in SQL?
Data structures that improve the speed of queries on a database table
How do you create an index on the name column?
CREATE INDEX idx_name ON employees(name);
What are the downsides of indexes?
They speed up reads but slow down writes and increase storage
What is normalization?
The process of organizing data to reduce redundancy and improve integrity
What is the goal of first normal form (1NF)?
Ensure each column contains atomic values and each row is unique