Fun with Learning Technology
LearnCoursesQuestionsTracksToolsNewsExplorePractice
Fun with Learning Technology

A new problem, explained clearly, every day.

Subscribe
Learn
  • Lessons
  • Topics
  • News
  • Tools
  • Courses
  • Career tracks
  • Everything
Site
  • About
  • Contact
  • Support
  • Privacy
  • Terms
Get the daily one

One email per new problem. No spam.

Request a tutorial

Requests shape what gets made next.

© 2026 Fun with Learning TechnologyRSS
Home›SQL›Quiz

SQL quiz

Ten questions at a time, drawn from 160. Every answer is explained. Nothing is saved and no account is needed.

Question 1 of 10Score 0

Which of the following best describes the role of a schema in a relational database?

Practice quiz for SQL. Scores are not saved.

Study first?

Every question comes from a lesson in the SQL course.

Read the course →

Interview prep

Written questions with full answers.

SQL interview questions →

All SQL quiz questions and answers

  1. Which of the following best describes the role of a schema in a relational database?

    • A physical storage device for data files
    • A logical container that organizes tables and other database objects
    • A set of rules that defines how a query is executed
    • A tool used to generate reports from database records

    Answer: A logical container that organizes tables and other database objects. A schema acts as a namespace or container to group tables logically, which helps in organization and security. It is not physical hardware (option 0), it is not a query optimizer (option 2), and it is not a reporting tool (option 3).

    From lesson: SQL Overview — Databases and Tables

  2. If you want to ensure that a column in a table never contains a missing value, which constraint should you apply?

    • PRIMARY KEY
    • UNIQUE
    • NOT NULL
    • DEFAULT

    Answer: NOT NULL. NOT NULL specifically prohibits the inclusion of missing data in a column. While PRIMARY KEY implies NOT NULL, it also enforces uniqueness and indexing, which might not be needed. UNIQUE only ensures no duplicates, and DEFAULT provides a value only if one isn't specified.

    From lesson: SQL Overview — Databases and Tables

  3. In a database table, what is the primary purpose of defining a data type for a column?

    • To define the storage size for the entire table
    • To dictate how the database engine interprets and validates the data
    • To encrypt the data automatically
    • To determine the primary key of the table

    Answer: To dictate how the database engine interprets and validates the data. Data types define the domain of values (e.g., integers, dates, strings), allowing the engine to store data efficiently and perform valid operations. Option 0 is incorrect because storage size depends on rows, not just column types; option 2 is unrelated to encryption; option 3 is not the primary purpose of data types.

    From lesson: SQL Overview — Databases and Tables

  4. When querying a database, why is it considered better practice to explicitly list column names instead of using the asterisk (*) wildcard?

    • It makes the result set return faster by ignoring hidden columns
    • It prevents errors if the table structure changes and improves code readability
    • It automatically filters out NULL values from the result
    • It allows the database to ignore the WHERE clause entirely

    Answer: It prevents errors if the table structure changes and improves code readability. Explicitly listing columns ensures your application logic remains stable if table columns are added or reordered. The wildcard returns all current columns, which can lead to unexpected data in downstream code. The other options are incorrect as they do not impact speed, filtering, or query clauses.

    From lesson: SQL Overview — Databases and Tables

  5. Consider a table named 'Employees'. If you need to filter rows based on a specific department, which clause do you use?

    • SELECT
    • FROM
    • WHERE
    • GROUP BY

    Answer: WHERE. The WHERE clause is specifically designed to filter rows based on conditions. SELECT dictates which columns to show, FROM identifies the table source, and GROUP BY is used to aggregate data, not filter individual rows.

    From lesson: SQL Overview — Databases and Tables

  6. If you need to retrieve all records from a 'customers' table where the 'age' is over 25, why is 'SELECT * FROM customers WHERE age > 25' preferred over 'SELECT * FROM customers' and filtering manually?

    • The database engine handles filtering more efficiently than application code
    • The syntax is shorter
    • It prevents data from being duplicated
    • It is the only way to retrieve specific rows

    Answer: The database engine handles filtering more efficiently than application code. Option 0 is correct because databases are optimized to filter data at the storage level, reducing network traffic. Option 1 is subjective, option 2 is incorrect, and option 3 is false as SQL does not automatically deduplicate without DISTINCT.

    From lesson: SELECT, FROM, WHERE — Core Querying

  7. A query is written as: SELECT name AS full_name FROM users WHERE full_name = 'John'. Why will this query fail?

    • The WHERE clause must come before the SELECT clause
    • Aliases created in the SELECT clause are not yet visible to the WHERE clause
    • You cannot use strings in the WHERE clause
    • The AS keyword is not supported in the SELECT clause

    Answer: Aliases created in the SELECT clause are not yet visible to the WHERE clause. Option 1 is correct because the execution order places FROM and WHERE before SELECT. Options 0, 2, and 3 are factually incorrect regarding SQL syntax rules.

    From lesson: SELECT, FROM, WHERE — Core Querying

  8. When querying a column 'status' for rows that do not have a value, why does 'WHERE status != 'active'' miss rows where 'status' is NULL?

    • NULL values require a specific wildcard character
    • The != operator only works on numeric types
    • NULL represents an unknown value, so comparing it to a known string results in UNKNOWN
    • The database only stores non-NULL values

    Answer: NULL represents an unknown value, so comparing it to a known string results in UNKNOWN. Option 2 is correct because NULL is not a value that can be compared using standard operators. Options 0, 1, and 3 misrepresent how NULLs and operators function in relational databases.

    From lesson: SELECT, FROM, WHERE — Core Querying

  9. Which of the following is the most efficient way to select specific columns 'first_name' and 'last_name' from an 'employees' table?

    • SELECT * FROM employees
    • SELECT first_name, last_name FROM employees
    • SELECT employees.first_name, employees.last_name FROM employees
    • SELECT ALL first_name, last_name FROM employees

    Answer: SELECT first_name, last_name FROM employees. Option 1 is the most concise and efficient practice. Option 0 fetches extra data, option 2 is redundant by specifying the table name unnecessarily, and option 3 uses a redundant keyword.

    From lesson: SELECT, FROM, WHERE — Core Querying

  10. In a query 'SELECT * FROM orders WHERE order_date = '2023-01-01'', what does the 'WHERE' clause perform?

    • It changes the sorting of the output
    • It filters the result set to include only rows satisfying the condition
    • It defines which columns are included in the output
    • It limits the number of rows returned

    Answer: It filters the result set to include only rows satisfying the condition. Option 1 is the definition of WHERE. Option 0 describes ORDER BY, option 2 describes the SELECT clause, and option 3 describes LIMIT/TOP.

    From lesson: SELECT, FROM, WHERE — Core Querying

  11. If you want to retrieve rows where 'price' is between 10 and 20, which of the following is logically equivalent to the BETWEEN operator?

    • price > 10 AND price < 20
    • price >= 10 AND price <= 20
    • price >= 10 OR price <= 20
    • price > 10 OR price < 20

    Answer: price >= 10 AND price <= 20. BETWEEN is inclusive, meaning it checks for values greater than or equal to the start and less than or equal to the end. The first option excludes the bounds, the third creates an overly broad condition, and the fourth creates a near-universal match.

    From lesson: Filtering — AND, OR, NOT, IN, BETWEEN, LIKE

  12. Which query correctly finds names that start with 'J' and contain an 'n' anywhere after the 'J'?

    • name LIKE 'J%n%'
    • name LIKE 'J_n'
    • name LIKE 'J%n'
    • name LIKE 'J_n%'

    Answer: name LIKE 'J%n%'. The first option uses % to represent any number of characters between J and n, and after n. The second and fourth options enforce only a single character between them, and the third fails if there are characters after the 'n'.

    From lesson: Filtering — AND, OR, NOT, IN, BETWEEN, LIKE

  13. Why would the clause 'WHERE status IN ('Open', 'Closed', NULL)' fail to return rows where status is NULL?

    • NULL cannot be used inside an IN clause
    • The IN clause treats NULL as an empty string
    • NULL is not equal to any value, so it must be checked with IS NULL
    • The SQL engine automatically ignores NULLs in lists

    Answer: NULL is not equal to any value, so it must be checked with IS NULL. In SQL, NULL represents an unknown value. Comparisons using = or IN are never true for NULL. You must explicitly use 'OR status IS NULL' to catch those records.

    From lesson: Filtering — AND, OR, NOT, IN, BETWEEN, LIKE

  14. Given 'WHERE x > 5 OR y < 10 AND z = 1', how does SQL evaluate this due to operator precedence?

    • (x > 5 OR y < 10) AND z = 1
    • x > 5 OR (y < 10 AND z = 1)
    • (x > 5 OR y) < (10 AND z = 1)
    • The query will throw a syntax error

    Answer: x > 5 OR (y < 10 AND z = 1). SQL processes AND before OR. Therefore, the y and z condition is evaluated first as a single logical unit before being ORed with the x condition.

    From lesson: Filtering — AND, OR, NOT, IN, BETWEEN, LIKE

  15. Which condition effectively selects all rows except those where 'category' is 'Electronics'?

    • NOT category = 'Electronics'
    • category != 'Electronics'
    • category <> 'Electronics'
    • All of the above

    Answer: All of the above. All three expressions are valid standard SQL ways to express inequality. They will all correctly exclude 'Electronics' but, importantly, they will also exclude NULL values in the 'category' column.

    From lesson: Filtering — AND, OR, NOT, IN, BETWEEN, LIKE

  16. Which of the following best describes the default behavior of ORDER BY in SQL?

    • It sorts results in ascending order, treating NULL values as the lowest possible value.
    • It sorts results in descending order, putting NULL values at the end of the list.
    • It sorts results in ascending order, ignoring NULL values entirely.
    • It returns results in a random order unless a specific index is applied.

    Answer: It sorts results in ascending order, treating NULL values as the lowest possible value.. Option 0 is correct because standard SQL defaults to ASC, placing NULLs at the start. Option 1 is wrong because it defaults to ASC, not DESC. Option 2 is wrong because NULLs are included, not ignored. Option 3 is wrong because SQL does not guarantee random order without explicit instructions.

    From lesson: Sorting with ORDER BY

  17. When sorting by multiple columns, e.g., 'ORDER BY department, salary DESC', what is the priority?

    • It sorts by salary first, then department.
    • It sorts by department, then by salary in descending order within each department.
    • It only sorts by department; salary is ignored.
    • It sorts by the sum of department and salary.

    Answer: It sorts by department, then by salary in descending order within each department.. Option 1 is correct: SQL applies the first criterion fully, then applies subsequent criteria to resolve ties within the first group. Option 0 is wrong because order is defined left-to-right. Option 2 and 3 are incorrect because they ignore the explicit instructions provided in the query syntax.

    From lesson: Sorting with ORDER BY

  18. If you have a table of 'ProductIDs' stored as TEXT, how do you ensure they sort numerically (1, 2, 10 instead of 1, 10, 2)?

    • ORDER BY ProductID ASC
    • ORDER BY LENGTH(ProductID), ProductID
    • ORDER BY CAST(ProductID AS UNSIGNED)
    • ORDER BY ProductID COLLATE NUMERIC

    Answer: ORDER BY CAST(ProductID AS UNSIGNED). Option 2 is correct as casting the string to a numeric type forces mathematical sorting. Option 0 sorts lexicographically. Option 1 sorts by length, which is not the same as numerical order. Option 3 is non-standard syntax that may not be supported by all database engines.

    From lesson: Sorting with ORDER BY

  19. Why might a query fail if you try to 'ORDER BY' an alias created in the SELECT clause?

    • Aliases cannot be used in sorting under any circumstances.
    • The ORDER BY clause is processed after the SELECT clause, making the alias available.
    • The ORDER BY clause is logically processed before the SELECT clause in the SQL execution order, so the alias may not be recognized.
    • Aliases can only be used in the WHERE clause, never in the ORDER BY clause.

    Answer: The ORDER BY clause is logically processed before the SELECT clause in the SQL execution order, so the alias may not be recognized.. Option 2 is correct because, in the logical order of operations, SELECT comes after WHERE but before ORDER BY in some contexts, yet standard SQL scoping varies; referring to the alias is standard, but the logical execution order is why it might fail in specific restricted environments. Options 0, 1, and 3 are conceptually incorrect regarding the order of operations.

    From lesson: Sorting with ORDER BY

  20. What is the result of using 'ORDER BY 1 DESC' in a query selecting 'Name, Age FROM Users'?

    • The result set will be sorted by Name in descending order.
    • The result set will be sorted by Age in descending order.
    • The query will fail because 1 is not a valid column name.
    • The result set will be sorted by the number 1, which does nothing.

    Answer: The result set will be sorted by Name in descending order.. Option 0 is correct because '1' refers to the first column selected (Name). Option 1 is wrong because 1 refers to the first column, not the second. Option 2 is wrong because ordinal references are standard. Option 3 is wrong because ordinals definitely perform a sort.

    From lesson: Sorting with ORDER BY

  21. Which of the following is the most reliable way to implement pagination in SQL?

    • Using LIMIT without any other clauses
    • Using OFFSET only to navigate to specific page numbers
    • Using ORDER BY a unique column, followed by LIMIT and OFFSET
    • Using a WHERE clause to filter IDs without sorting

    Answer: Using ORDER BY a unique column, followed by LIMIT and OFFSET. Option 3 is correct because sorting by a unique column ensures the order of rows remains stable between pagination requests. Option 1 is unreliable due to non-deterministic row order. Option 2 is incorrect as OFFSET alone cannot define the number of items returned. Option 4 does not guarantee the sequence of rows retrieved.

    From lesson: Limiting Results — LIMIT and OFFSET

  22. If you have 100 rows and execute 'SELECT * FROM users ORDER BY id LIMIT 10 OFFSET 20', which rows are returned?

    • Rows 20 through 30
    • Rows 21 through 30
    • Rows 1 through 10
    • Rows 10 through 20

    Answer: Rows 21 through 30. Option 2 is correct because OFFSET 20 skips the first 20 rows, and LIMIT 10 fetches the next 10 (rows 21-30). Option 1 is incorrect because it confuses OFFSET with 1-based indexing. Option 3 ignores the OFFSET, and Option 4 misinterprets the syntax.

    From lesson: Limiting Results — LIMIT and OFFSET

  23. Why is ORDER BY mandatory when using OFFSET for pagination?

    • To improve the performance of the query execution
    • To ensure that the database engine can find the offset point
    • To guarantee that rows are skipped consistently across multiple queries
    • To prevent the error that occurs when OFFSET is used without sorting

    Answer: To guarantee that rows are skipped consistently across multiple queries. Option 3 is correct because relational databases do not have a natural order; without sorting, the 'previous' page and 'next' page might return the same rows. Option 1 is incorrect as sorting usually adds overhead. Option 2 and 4 are false as most engines do not require ORDER BY for syntax, but for logical consistency.

    From lesson: Limiting Results — LIMIT and OFFSET

  24. What happens if the LIMIT value is greater than the number of remaining rows after applying the OFFSET?

    • The query returns an error
    • The database returns all remaining rows up to the end of the set
    • The query returns an empty result set
    • The query hangs until more data is inserted

    Answer: The database returns all remaining rows up to the end of the set. Option 2 is correct; LIMIT specifies the maximum number of rows, so if fewer rows exist, the engine returns all available rows. Option 1 and 3 are incorrect as the query remains valid and yields existing data. Option 4 is false as SQL queries are independent of future data state.

    From lesson: Limiting Results — LIMIT and OFFSET

  25. If a table has 50 rows and you use 'LIMIT 10 OFFSET 45', what is the result?

    • The query returns 10 rows
    • The query returns 5 rows
    • The query returns an error because 45+10 > 50
    • The query returns 0 rows

    Answer: The query returns 5 rows. Option 2 is correct because after skipping 45 rows, only 5 rows remain, so the database returns all of them. Option 1 is incorrect as it assumes the LIMIT overrides availability. Option 3 is false as there is no overflow error. Option 4 is incorrect because there is data left after the offset.

    From lesson: Limiting Results — LIMIT and OFFSET

  26. What is the result of the expression '5 + NULL' in SQL?

    • 5
    • 0
    • NULL
    • Error

    Answer: NULL. In SQL, any arithmetic operation involving NULL results in NULL because the unknown value makes the entire result unknown. Option 0 and 5 are incorrect because they assume NULL is treated as zero, which it is not in standard math. Error is incorrect as it is a valid SQL expression.

    From lesson: NULL Values and IS NULL

  27. If you want to count the number of rows where the 'email' column is not empty, which query is most accurate?

    • SELECT COUNT(email) FROM users
    • SELECT COUNT(*) FROM users WHERE email IS NOT NULL
    • SELECT COUNT(email) FROM users WHERE email != NULL
    • SELECT COUNT(*) FROM users

    Answer: SELECT COUNT(*) FROM users WHERE email IS NOT NULL. Option 1 counts rows but might be ambiguous; Option 2 explicitly filters NULLs and counts the rows. Option 3 is wrong because comparison with NULL using != is invalid. Option 4 counts every row including those with NULL, failing the requirement to exclude them.

    From lesson: NULL Values and IS NULL

  28. Why does a subquery using 'WHERE id NOT IN (SELECT parent_id FROM items)' potentially return zero rows if 'parent_id' contains a NULL?

    • SQL ignores the NULL automatically
    • The expression evaluates to unknown, which is treated as false
    • The subquery creates a syntax error
    • The database engine optimizes out the NULL values

    Answer: The expression evaluates to unknown, which is treated as false. When comparing against a set containing NULL, the NOT IN logic becomes unknown for those rows, and since unknown is not true, the records are excluded. Option 1 and 4 are wrong because SQL treats NULL explicitly. Option 3 is wrong because the syntax is perfectly valid.

    From lesson: NULL Values and IS NULL

  29. Which function is the standard way to replace a NULL value with a specific default during a SELECT query?

    • IFNULL
    • ISNULL
    • COALESCE
    • NVL

    Answer: COALESCE. COALESCE is the standard ANSI SQL function that takes multiple arguments and returns the first non-NULL value. IFNULL, ISNULL, and NVL are vendor-specific functions (MySQL, SQL Server, and Oracle, respectively) and are not part of the standard SQL specification.

    From lesson: NULL Values and IS NULL

  30. What is the logical result of the condition 'NULL IS NULL'?

    • TRUE
    • FALSE
    • NULL
    • Unknown

    Answer: TRUE. The 'IS NULL' operator is a specific predicate designed to test for the presence of NULL; it returns TRUE if the value is NULL and FALSE otherwise. Option 1 is correct. Options 2, 3, and 4 are incorrect because they confuse the 'IS' operator with equality comparison logic.

    From lesson: NULL Values and IS NULL

  31. If a column 'score' has values [10, NULL, 20], what will SELECT AVG(score) FROM table return?

    • 10
    • 15
    • 30
    • NULL

    Answer: 15. AVG() ignores NULL values and calculates the average of [10, 20], which is 15. Option 10 is wrong because it assumes NULL is 0. Option 30 is the sum, not the average. NULL is incorrect because aggregate functions exclude missing data from calculations.

    From lesson: Aggregation Functions — COUNT, SUM, AVG, MIN, MAX

  32. Which of the following clauses is used to filter records AFTER an aggregation has been performed?

    • WHERE
    • GROUP BY
    • HAVING
    • ORDER BY

    Answer: HAVING. HAVING is specifically designed to filter groups created by aggregate functions. WHERE filters row-by-row before aggregation, GROUP BY organizes the data, and ORDER BY sorts the final output.

    From lesson: Aggregation Functions — COUNT, SUM, AVG, MIN, MAX

  33. You want to find the number of unique cities in a table. Which syntax is correct?

    • COUNT(city)
    • COUNT(DISTINCT city)
    • DISTINCT COUNT(city)
    • SUM(DISTINCT city)

    Answer: COUNT(DISTINCT city). COUNT(DISTINCT city) ensures each city name is counted only once. COUNT(city) counts duplicates. The other options are syntactically incorrect or perform the wrong mathematical operation.

    From lesson: Aggregation Functions — COUNT, SUM, AVG, MIN, MAX

  34. Given a table of employees, why would 'SELECT department, MAX(salary) FROM employees' fail in many SQL modes?

    • MAX cannot be used on numerical columns.
    • The query is missing a GROUP BY clause for the department column.
    • MAX must be used with a WHERE clause.
    • You cannot select columns alongside aggregate functions.

    Answer: The query is missing a GROUP BY clause for the department column.. To select an aggregate alongside a non-aggregated column, the non-aggregated column must appear in the GROUP BY clause. Without it, the engine cannot map the maximum salary to the correct department. The other options are false; MAX works on numbers and can be used without WHERE.

    From lesson: Aggregation Functions — COUNT, SUM, AVG, MIN, MAX

  35. What is the result of COUNT(*) on a table containing 10 rows, where 3 rows have a NULL value in the 'price' column?

    • 3
    • 7
    • 10
    • 13

    Answer: 10. COUNT(*) counts all rows regardless of NULL values. Therefore, all 10 rows are counted. 7 would be the result if you used COUNT(price), and 3 is incorrect as it represents only the NULL count.

    From lesson: Aggregation Functions — COUNT, SUM, AVG, MIN, MAX

  36. Which of the following scenarios best justifies the use of a HAVING clause instead of a WHERE clause?

    • Removing rows where the user's age is less than 18.
    • Filtering results to show only departments with a total salary expenditure exceeding $100,000.
    • Limiting the result set to rows created within the current calendar year.
    • Excluding records that contain NULL values in a specific column.

    Answer: Filtering results to show only departments with a total salary expenditure exceeding $100,000.. Filtering by total salary (an aggregate) requires HAVING because the total is calculated after grouping. The other options are row-level filters that should be handled by WHERE for better performance.

    From lesson: GROUP BY and HAVING

  37. Consider a table of sales. Which query will successfully identify products that have been sold more than 50 times in total?

    • SELECT product_id FROM sales WHERE COUNT(product_id) > 50 GROUP BY product_id
    • SELECT product_id FROM sales GROUP BY product_id HAVING COUNT(product_id) > 50
    • SELECT product_id FROM sales HAVING COUNT(product_id) > 50
    • SELECT product_id FROM sales GROUP BY product_id WHERE COUNT(product_id) > 50

    Answer: SELECT product_id FROM sales GROUP BY product_id HAVING COUNT(product_id) > 50. Correct structure is GROUP BY followed by HAVING for the aggregate condition. The first is wrong because WHERE cannot contain aggregates; the third is wrong because HAVING needs a GROUP BY; the fourth has the clauses in the incorrect order.

    From lesson: GROUP BY and HAVING

  38. What happens if you run: SELECT category, SUM(price) FROM products GROUP BY category WHERE price > 10?

    • It returns the sum of prices for each category for products priced over 10.
    • It returns the sum of prices for categories where the total sum is over 10.
    • It generates a syntax error because WHERE must appear before GROUP BY.
    • It returns an error because price is not an aggregate function.

    Answer: It generates a syntax error because WHERE must appear before GROUP BY.. SQL requires the WHERE clause to come before the GROUP BY clause. The others describe logical outcomes that won't happen because the query is syntactically invalid.

    From lesson: GROUP BY and HAVING

  39. If you want to group by 'department' and display the average salary, which SELECT statement is valid?

    • SELECT department, name, AVG(salary) FROM employees GROUP BY department
    • SELECT department, AVG(salary) FROM employees GROUP BY department
    • SELECT department, AVG(salary) FROM employees
    • SELECT department, AVG(salary) FROM employees GROUP BY salary

    Answer: SELECT department, AVG(salary) FROM employees GROUP BY department. Option 2 is valid because every non-aggregated column in the SELECT is included in the GROUP BY. Option 1 is invalid due to 'name', 3 is invalid due to missing GROUP BY, and 4 groups by the wrong column.

    From lesson: GROUP BY and HAVING

  40. When is an alias defined in the SELECT clause accessible in the HAVING clause?

    • Always, because the SELECT clause is processed before the HAVING clause.
    • Only when using specific database systems that support alias recognition in HAVING.
    • Never, because HAVING is logically evaluated before the SELECT clause in SQL.
    • Only if the alias is used inside an aggregate function.

    Answer: Never, because HAVING is logically evaluated before the SELECT clause in SQL.. Standard SQL evaluates SELECT after HAVING, so aliases are typically not available. While some engines allow it as an extension, it is not standard, making 'Only when using specific databases' the accurate technical assessment.

    From lesson: GROUP BY and HAVING

  41. If you run SELECT DISTINCT first_name, last_name FROM employees;, what determines if a row is considered a duplicate?

    • Only the first_name must be unique.
    • Only the last_name must be unique.
    • The combination of both first_name and last_name must be unique.
    • The entire row including hidden primary key columns must be unique.

    Answer: The combination of both first_name and last_name must be unique.. DISTINCT applies to the entire tuple of selected columns. Option 0 and 1 are wrong because the modifier is not restricted to one column. Option 3 is wrong because DISTINCT ignores columns not explicitly listed in the SELECT clause.

    From lesson: DISTINCT — Removing Duplicates

  42. What is the result of SELECT DISTINCT department FROM staff; if there are three employees in the 'Sales' department and two in 'HR'?

    • Sales, Sales, Sales, HR, HR
    • Sales, HR
    • Sales, HR, 5
    • An error, because there are multiple values for each department.

    Answer: Sales, HR. DISTINCT removes all duplicate values from the result set. Option 0 is wrong as it doesn't remove duplicates. Option 2 and 3 are wrong because there is no aggregation occurring here.

    From lesson: DISTINCT — Removing Duplicates

  43. How does SQL handle NULL values when the DISTINCT keyword is applied to a column containing them?

    • It removes all NULL values from the result.
    • It treats every NULL as a unique value, keeping all of them.
    • It treats all NULL values as duplicates of each other and returns one NULL.
    • It ignores the column entirely if it contains a NULL.

    Answer: It treats all NULL values as duplicates of each other and returns one NULL.. In SQL, NULLs are treated as duplicates of each other in the context of DISTINCT. Option 0 is wrong because they aren't removed, 1 is wrong because they are grouped, and 3 is wrong because the column is still processed.

    From lesson: DISTINCT — Removing Duplicates

  44. Which of the following is functionally equivalent to SELECT DISTINCT status FROM orders;?

    • SELECT status FROM orders GROUP BY status;
    • SELECT status FROM orders ORDER BY status;
    • SELECT status FROM orders HAVING COUNT(status) > 0;
    • SELECT ALL status FROM orders;

    Answer: SELECT status FROM orders GROUP BY status;. GROUP BY status creates one row per unique status value, identical to the behavior of DISTINCT. Option 1 doesn't remove duplicates, 2 doesn't filter, and 3 is a filter that doesn't handle duplicates.

    From lesson: DISTINCT — Removing Duplicates

  45. You want to know the number of unique cities where customers are located. Which query is correct?

    • SELECT DISTINCT COUNT(city) FROM customers;
    • SELECT COUNT(DISTINCT city) FROM customers;
    • SELECT COUNT(*) FROM (DISTINCT city) FROM customers;
    • SELECT DISTINCT (COUNT(city)) FROM customers;

    Answer: SELECT COUNT(DISTINCT city) FROM customers;. COUNT(DISTINCT column) is the standard syntax for counting unique occurrences. Option 0 counts all and then tries to apply distinct (invalid), 2 is syntactically incorrect, and 3 applies distinct to a single aggregate result.

    From lesson: DISTINCT — Removing Duplicates

  46. If multiple conditions in a CASE statement evaluate to true for a single row, which result is returned?

    • The result of the first condition that evaluates to true
    • The result of the last condition that evaluates to true
    • A concatenation of all true condition results
    • An error due to conflicting logic

    Answer: The result of the first condition that evaluates to true. SQL stops evaluating once the first true condition is met. The first option is correct because the engine processes conditions top-down. The others are wrong because SQL does not aggregate or error out on subsequent matches; it simply ignores them.

    From lesson: CASE WHEN — Conditional Logic

  47. What is the result of a CASE statement that lacks an ELSE clause when none of the WHEN conditions are met?

    • 0
    • An empty string
    • NULL
    • An error

    Answer: NULL. By default, if no conditions are matched and no ELSE is provided, the expression returns NULL. 0 and empty string are incorrect because they are specific values not implicitly assumed, and it is not an error.

    From lesson: CASE WHEN — Conditional Logic

  48. Which of the following is the valid structure for a CASE expression?

    • CASE WHEN condition THEN result ELSE result END
    • CASE (condition) ? (result) : (result)
    • CASE condition THEN result END
    • IF CASE condition THEN result ELSE result

    Answer: CASE WHEN condition THEN result ELSE result END. The first option follows standard SQL syntax. The second is common in other programming languages, the third is missing the ELSE keyword (though optional, the first is more complete), and the fourth uses non-existent syntax.

    From lesson: CASE WHEN — Conditional Logic

  49. Why might you get a data type conversion error when using a CASE statement?

    • Because the conditions are evaluated in the wrong order
    • Because the THEN clauses return different, incompatible data types
    • Because the alias provided for the CASE column is invalid
    • Because the END keyword is missing

    Answer: Because the THEN clauses return different, incompatible data types. SQL expects all possible outputs of a single CASE expression to be castable to the same type. If one branch returns a string and another returns an integer, an error occurs. The other options describe syntax errors or logical sequence issues, not type conflicts.

    From lesson: CASE WHEN — Conditional Logic

  50. How can you use a CASE statement to effectively categorize numerical values into ranges?

    • By nesting multiple CASE statements inside the SELECT list
    • By using CASE WHEN inside a GROUP BY clause
    • By evaluating ranges with sequential WHEN conditions and an ELSE clause
    • By using CASE WHEN inside a WHERE clause without aliases

    Answer: By evaluating ranges with sequential WHEN conditions and an ELSE clause. Defining sequential ranges (e.g., WHEN val < 10, WHEN val < 20) is the standard way to categorize data. Nesting is unnecessary and inefficient, GROUP BY usually needs the alias, and WHERE clauses don't use CASE statements for categorization in this manner.

    From lesson: CASE WHEN — Conditional Logic

  51. What is the result of an INNER JOIN between Table A (5 rows) and Table B (5 rows) if none of the join keys match?

    • 25 rows
    • 10 rows
    • 0 rows
    • 5 rows

    Answer: 0 rows. An INNER JOIN returns only rows where there is a match in both tables. If there are zero matches, the result set is empty (0 rows). It is not a Cartesian product (25) or a sum of rows (10 or 5).

    From lesson: INNER JOIN

  52. Which of the following describes the fundamental purpose of an INNER JOIN?

    • To combine all rows from two tables regardless of matches
    • To retrieve only rows that have corresponding values in both tables
    • To return all rows from the left table and matching rows from the right
    • To merge tables based on identical column names only

    Answer: To retrieve only rows that have corresponding values in both tables. INNER JOIN is strictly an intersection operation. It filters out any rows that do not have a counterpart in the other table. Option 1 describes a Cross Join, Option 3 describes a Left Join, and Option 4 is an unnecessary restriction.

    From lesson: INNER JOIN

  53. If you perform an INNER JOIN and the resulting record count is higher than the count of either individual table, what does this imply?

    • The JOIN operation failed
    • There is a many-to-many relationship involving duplicate keys
    • The query requires a DISTINCT keyword to be valid
    • The join condition is missing

    Answer: There is a many-to-many relationship involving duplicate keys. This happens when there are duplicate keys in the joining columns, causing a one-to-many or many-to-many relationship that multiplies the result rows. It is not an error (failed) or a missing condition; it is a mathematical consequence of the data distribution.

    From lesson: INNER JOIN

  54. Why is it recommended to use the 'ON' clause instead of the 'WHERE' clause for join conditions?

    • The WHERE clause is not supported for joins
    • The ON clause makes the intent clearer and improves maintainability
    • The WHERE clause is significantly slower in all SQL engines
    • The ON clause allows for filtering after the join is complete

    Answer: The ON clause makes the intent clearer and improves maintainability. Using ON is the modern SQL standard that separates the join logic from the filtering logic. While WHERE can technically function for simple joins, it lacks clarity. Option 1 is false, and Option 3 is an exaggeration.

    From lesson: INNER JOIN

  55. When you have two tables, Users and Orders, what will 'SELECT * FROM Users INNER JOIN Orders ON Users.id = Orders.user_id' return?

    • All users, even those without orders
    • All orders, even those without users
    • Only users who have placed at least one order
    • All users and all orders combined

    Answer: Only users who have placed at least one order. Because it is an INNER JOIN, it excludes any User who has no corresponding entry in the Orders table (and vice-versa). Thus, only users with orders appear. Options 1 and 2 describe Outer Joins, and Option 4 describes a full data dump.

    From lesson: INNER JOIN

  56. If Table A has 10 rows and Table B has 5 rows, and 3 rows match based on the join key, how many rows will result from a LEFT JOIN (A LEFT JOIN B)?

    • 3 rows
    • 8 rows
    • 10 rows
    • 15 rows

    Answer: 10 rows. A LEFT JOIN returns all rows from the left table (10) regardless of matches. For the 3 matching rows, data from B is joined; for the 7 non-matching rows, columns from B are NULL. The others are wrong because 3 represents an INNER JOIN, 8 is a miscalculation, and 15 is the sum of rows not accounting for the join logic.

    From lesson: LEFT, RIGHT, and FULL OUTER JOIN

  57. Why would moving a condition from a WHERE clause to an ON clause change the result of a LEFT JOIN?

    • It changes the sorting order of the final result set.
    • Conditions in WHERE filter rows after the join is performed, while ON filters them during the join process.
    • It is faster for the database engine to execute.
    • There is no difference in the result set.

    Answer: Conditions in WHERE filter rows after the join is performed, while ON filters them during the join process.. In a LEFT JOIN, a WHERE clause filters the entire result set, potentially removing the 'padded' rows with NULLs. An ON clause filters only the right table before the join occurs, preserving the left table rows. The other options are incorrect because performance differences are secondary and the result set differs significantly.

    From lesson: LEFT, RIGHT, and FULL OUTER JOIN

  58. What is the primary characteristic of a FULL OUTER JOIN?

    • It returns only rows where there is a match in both tables.
    • It returns all rows from the right table and matching rows from the left.
    • It returns all rows from both tables, filling with NULLs where no match exists.
    • It returns all possible combinations of rows from both tables.

    Answer: It returns all rows from both tables, filling with NULLs where no match exists.. FULL OUTER JOIN is the combination of LEFT and RIGHT joins, showing all data from both sides. Option 0 describes INNER JOIN, option 1 describes RIGHT JOIN, and option 3 describes CROSS JOIN.

    From lesson: LEFT, RIGHT, and FULL OUTER JOIN

  59. Which scenario best justifies the use of a LEFT JOIN over an INNER JOIN?

    • When you need to count the total number of items in both tables combined.
    • When you want to identify records in the left table that have no corresponding record in the right table.
    • When the tables contain duplicate keys that need to be removed.
    • When you need to ensure the query returns the smallest possible result set.

    Answer: When you want to identify records in the left table that have no corresponding record in the right table.. LEFT JOINs are ideal for 'missing' data reports because the NULLs generated on the right side indicate a lack of correspondence. INNER JOINs discard non-matching rows. The other options do not specifically benefit from the OUTER JOIN logic.

    From lesson: LEFT, RIGHT, and FULL OUTER JOIN

  60. You perform a query where Table A is LEFT JOINed to Table B. If you want to find rows in Table A that have no match in Table B, how do you modify the query?

    • Add WHERE TableB.id IS NOT NULL
    • Add WHERE TableB.id IS NULL
    • Change the join to a CROSS JOIN
    • Remove the ON clause from the query

    Answer: Add WHERE TableB.id IS NULL. When a match is missing in a LEFT JOIN, the right-side columns are filled with NULL. Checking for IS NULL on a right-side column isolates these rows. IS NOT NULL would return only matched rows, and the other options would either cause errors or produce incorrect cross-product data.

    From lesson: LEFT, RIGHT, and FULL OUTER JOIN

  61. You need to pair every product from a 'Products' table with every department from a 'Departments' table to create a master schedule. Which approach is most efficient?

    • INNER JOIN on a non-existent column
    • CROSS JOIN
    • SELF JOIN
    • LEFT JOIN with an ON 1=1 clause

    Answer: CROSS JOIN. CROSS JOIN is designed specifically to produce the Cartesian product of two sets. INNER JOIN requires a matching predicate, and SELF JOIN is for joining a table to itself. While LEFT JOIN with ON 1=1 technically works, CROSS JOIN is the semantic standard for this operation.

    From lesson: CROSS JOIN and SELF JOIN

  62. A table contains 'EmployeeID' and 'ManagerID'. You want to display the employee's name alongside their manager's name. How do you structure the query?

    • CROSS JOIN the table to itself
    • Perform a SELF JOIN using an INNER or LEFT JOIN
    • Use a subquery for the manager name without joining
    • Perform an INNER JOIN using the primary key on both sides

    Answer: Perform a SELF JOIN using an INNER or LEFT JOIN. A SELF JOIN is required to look up a manager's name within the same table. A CROSS JOIN would produce incorrect pairings. Joining on primary keys would only match an employee to themselves, not their manager.

    From lesson: CROSS JOIN and SELF JOIN

  63. What is the primary difference between a CROSS JOIN and an INNER JOIN?

    • CROSS JOIN returns more columns than an INNER JOIN
    • INNER JOIN requires a join condition, whereas CROSS JOIN does not
    • CROSS JOIN only works on tables with equal row counts
    • INNER JOIN is significantly slower than CROSS JOIN

    Answer: INNER JOIN requires a join condition, whereas CROSS JOIN does not. INNER JOIN requires an ON or USING clause to filter results, whereas CROSS JOIN performs a blind multiplication of rows. CROSS JOIN does not require equal row counts, and performance depends entirely on the size of the tables and the efficiency of the join predicate.

    From lesson: CROSS JOIN and SELF JOIN

  64. If Table A has 10 rows and Table B has 5 rows, how many rows will result from a CROSS JOIN?

    • 50
    • 15
    • 5
    • 0

    Answer: 50. A CROSS JOIN produces the Cartesian product: 10 multiplied by 5 equals 50. 15 would be the result of a UNION, and 5 is incorrect as it implies a standard join filter.

    From lesson: CROSS JOIN and SELF JOIN

  65. In a SELF JOIN, why must you use table aliases like 'A' and 'B'?

    • To increase query execution speed
    • To avoid creating a circular reference error
    • To distinguish between the two instances of the same table
    • To allow the use of window functions

    Answer: To distinguish between the two instances of the same table. Without aliases, the database engine cannot determine which table instance a column refers to, resulting in an 'ambiguous column' error. Aliases have no impact on execution speed, circular references, or window function availability.

    From lesson: CROSS JOIN and SELF JOIN

  66. If you perform an INNER JOIN between a Table A (100 rows) and Table B (50 rows), and 20 rows in A have no match in B, how many rows will the result set contain?

    • 150 rows
    • 80 rows
    • 30 rows
    • 50 rows

    Answer: 80 rows. An INNER JOIN only returns rows where there is a match in both tables. Since 20 rows in Table A have no match, only 80 rows (100 - 20) are returned. Other options fail because they either add rows, guess wrong, or ignore the matching constraint.

    From lesson: Joining Multiple Tables

  67. What is the primary difference between a LEFT JOIN and an INNER JOIN regarding the returned result set?

    • LEFT JOIN includes all rows from the left table, even if no match exists in the right table.
    • INNER JOIN includes all rows from both tables even if no match exists.
    • LEFT JOIN only returns rows where the left table is empty.
    • There is no difference in the result set; only syntax varies.

    Answer: LEFT JOIN includes all rows from the left table, even if no match exists in the right table.. LEFT JOIN ensures all records from the primary (left) table are kept, filling missing matches with NULL. INNER JOIN excludes non-matching records entirely. Other options incorrectly describe the behavior or claim no difference.

    From lesson: Joining Multiple Tables

  68. When joining three tables (A, B, and C), what happens if you use a LEFT JOIN for A to B, and then an INNER JOIN for B to C?

    • The entire result set effectively becomes an INNER JOIN, excluding rows that don't match table C.
    • The result set remains a full list of A, regardless of matches in C.
    • The database will throw a syntax error because JOIN types cannot be mixed.
    • Only rows from C that match A are returned.

    Answer: The entire result set effectively becomes an INNER JOIN, excluding rows that don't match table C.. The INNER JOIN to C filters out any rows from the intermediate set (A-B) that do not have a corresponding record in C. Because the subsequent filter is restrictive, it overrides the inclusive nature of the previous LEFT JOIN. Other options are incorrect as they ignore the restrictive nature of INNER JOIN.

    From lesson: Joining Multiple Tables

  69. Why should you use table aliases (e.g., 'FROM orders o') in a query involving multiple joins?

    • To make the query run faster on the server.
    • To allow the database to ignore duplicate column names.
    • To improve code readability and explicitly identify which table a column belongs to.
    • To bypass security restrictions on column naming conventions.

    Answer: To improve code readability and explicitly identify which table a column belongs to.. Aliases make the code concise and prevent 'ambiguous column' errors when different tables share identical column names. Aliases do not impact execution speed or bypass security, and they do not 'ignore' duplicate names; they resolve them.

    From lesson: Joining Multiple Tables

  70. You need a list of all customers, including those who have never placed an order. Which join approach is correct?

    • INNER JOIN on the orders table.
    • LEFT JOIN from customers to orders.
    • RIGHT JOIN from customers to orders.
    • CROSS JOIN between customers and orders.

    Answer: LEFT JOIN from customers to orders.. A LEFT JOIN keeps every row from the 'customers' table. If no match is found in the 'orders' table, the join columns appear as NULL, which is the desired behavior for a list including those without orders. INNER JOIN excludes these customers, RIGHT JOIN would require the orders table to be the primary, and CROSS JOIN creates an invalid combination of all rows.

    From lesson: Joining Multiple Tables

  71. Which type of subquery must return exactly one row and one column to be used in a SELECT list or a WHERE clause with a comparison operator?

    • Table subquery
    • Row subquery
    • Scalar subquery
    • Correlated subquery

    Answer: Scalar subquery. A scalar subquery returns a single value (one row, one column). Table subqueries return multiple rows/columns, and row subqueries return one row with multiple columns. Correlated subqueries are a method of execution, not a return type.

    From lesson: Subqueries — Scalar, Row, Table

  72. When using a subquery in a FROM clause (a derived table), what is the most important requirement for it to function correctly in most SQL dialects?

    • The subquery must return a single scalar value.
    • The subquery must be assigned a unique table alias.
    • The subquery cannot contain a GROUP BY clause.
    • The subquery must be correlated to the outer query.

    Answer: The subquery must be assigned a unique table alias.. Derived tables (table subqueries) require an alias so the outer query can reference the resulting set. Scalar requirements apply to SELECT clauses, and correlation is optional, not mandatory.

    From lesson: Subqueries — Scalar, Row, Table

  73. If you need to compare a tuple of two columns (e.g., department_id and salary) against the results of a subquery, which type are you using?

    • Scalar subquery
    • Table subquery
    • Row subquery
    • Correlated subquery

    Answer: Row subquery. A row subquery returns a single row consisting of multiple columns, allowing for direct tuple comparison against an outer row. A scalar returns only one value, and a table subquery usually requires operators like IN or EXISTS.

    From lesson: Subqueries — Scalar, Row, Table

  74. What happens if a subquery used with the '=' operator returns more than one row?

    • The database engine automatically picks the first row returned.
    • The database engine returns NULL.
    • The query executes but ignores all rows except the last one.
    • The query fails with a runtime error.

    Answer: The query fails with a runtime error.. The '=' operator expects a single scalar value. If the subquery returns multiple rows, the engine cannot equate a single value to a set, resulting in an error. It does not default to the first/last row.

    From lesson: Subqueries — Scalar, Row, Table

  75. Which of the following is true regarding a correlated subquery compared to a non-correlated subquery?

    • It can be executed independently of the outer query.
    • It references one or more columns from the outer query.
    • It is always faster because it processes fewer rows.
    • It is restricted to returning only scalar values.

    Answer: It references one or more columns from the outer query.. A correlated subquery is dependent on the outer query because it references columns from the outer scope, meaning it cannot be run standalone. Non-correlated subqueries can be run independently.

    From lesson: Subqueries — Scalar, Row, Table

  76. What is the primary benefit of using a CTE instead of a subquery in a SELECT statement?

    • CTEs automatically cache the data on the disk for faster retrieval
    • CTEs improve code readability and allow for self-referencing via recursion
    • CTEs are required for all aggregate functions to work correctly
    • CTEs allow you to bypass primary key constraints during a join

    Answer: CTEs improve code readability and allow for self-referencing via recursion. CTEs provide a clear, linear structure for complex logic, and they are the only mechanism for recursive queries. Options 1, 3, and 4 are false as CTEs do not cache on disk, are not required for aggregates, and do not bypass constraints.

    From lesson: CTEs — Common Table Expressions (WITH)

  77. How do you define multiple CTEs in a single SQL statement?

    • By repeating the WITH keyword for each expression
    • By defining them in separate batches using the GO command
    • By separating the expressions with a comma after the first WITH
    • By nesting each CTE inside the previous one's body

    Answer: By separating the expressions with a comma after the first WITH. Standard SQL syntax for multiple CTEs uses a single 'WITH' followed by comma-separated definitions. Option 1 is invalid syntax, option 2 breaks the statement scope, and option 4 is not how SQL handles multiple result sets.

    From lesson: CTEs — Common Table Expressions (WITH)

  78. Which of the following is required for a recursive CTE to function correctly?

    • A constant hardcoded table reference
    • An anchor member, a recursive member, and UNION ALL
    • A stored procedure to handle the loop index
    • The use of the RECURSIVE keyword in all SQL dialects

    Answer: An anchor member, a recursive member, and UNION ALL. Recursive CTEs must have a base case (anchor), a recursive part that references the CTE itself, and the UNION ALL operator. Other options are irrelevant or syntactically incorrect for standard SQL implementations.

    From lesson: CTEs — Common Table Expressions (WITH)

  79. What happens to the data defined in a CTE once the main query completes?

    • It is saved as a temporary table in the tempdb
    • It remains in memory until the database session is closed
    • It is discarded immediately as it exists only for the duration of the query
    • It is moved to a permanent audit table

    Answer: It is discarded immediately as it exists only for the duration of the query. CTEs are volatile and scope-limited; they vanish as soon as the statement finishes. They are not saved to disk or persistent memory as described in the other choices.

    From lesson: CTEs — Common Table Expressions (WITH)

  80. If you have a CTE named 'Sales_CTE', where can you reference it?

    • Only in the immediate query that follows the CTE definition
    • In any subsequent query executed by any user in the database
    • Only within the stored procedure where it was defined
    • In the FROM clause of the main query or subsequent CTEs

    Answer: In the FROM clause of the main query or subsequent CTEs. A CTE is scoped to the query it belongs to; it can be referenced in the main query or in later CTE definitions within the same WITH block. It is not global (option 2) and is not restricted to stored procedures (option 3).

    From lesson: CTEs — Common Table Expressions (WITH)

  81. A sales manager wants to assign a unique ID to every single order from 1 to N based on the date, regardless of whether multiple orders have the same date. Which function should they use?

    • RANK()
    • DENSE_RANK()
    • ROW_NUMBER()
    • NTILE()

    Answer: ROW_NUMBER(). ROW_NUMBER() generates a unique, sequential integer for every row, even if there are ties. RANK() and DENSE_RANK() would assign the same number to identical values, failing the requirement for a unique ID per order.

    From lesson: Window Functions — ROW_NUMBER, RANK, DENSE_RANK

  82. If your dataset has three products tied for 1st place in sales, how will RANK() and DENSE_RANK() differ in the assignment of the next rank?

    • RANK() will give 4th, DENSE_RANK() will give 4th
    • RANK() will give 2nd, DENSE_RANK() will give 4th
    • RANK() will give 4th, DENSE_RANK() will give 2nd
    • Both will give 2nd

    Answer: RANK() will give 4th, DENSE_RANK() will give 2nd. RANK() skips numbers (1, 1, 1, 4), so the next is 4th. DENSE_RANK() does not skip (1, 1, 1, 2), so the next is 2nd. The other options misidentify the sequence logic.

    From lesson: Window Functions — ROW_NUMBER, RANK, DENSE_RANK

  83. What is the primary reason you must include an ORDER BY clause inside the OVER() function when using these ranking functions?

    • To define the scope of the calculation
    • To ensure the ranking is deterministic and reproducible
    • To optimize the speed of the query engine
    • To prevent errors in the SELECT list

    Answer: To ensure the ranking is deterministic and reproducible. Without ORDER BY, the engine does not know how to rank the rows, making the output non-deterministic. The other options refer to performance or syntax, which are not the primary purpose of the ordering requirement.

    From lesson: Window Functions — ROW_NUMBER, RANK, DENSE_RANK

  84. You need to identify the top-performing employee in each department. Which structure is most appropriate?

    • PARTITION BY department ORDER BY sales DESC
    • PARTITION BY sales ORDER BY department DESC
    • ORDER BY department, sales DESC
    • PARTITION BY employee_id ORDER BY sales DESC

    Answer: PARTITION BY department ORDER BY sales DESC. PARTITION BY department ensures the ranking resets for every department. Ordering by sales DESC brings the best performance to the top. The other options either sort incorrectly or fail to group by department.

    From lesson: Window Functions — ROW_NUMBER, RANK, DENSE_RANK

  85. You have a query that calculates a rank for students based on test scores. Why does filtering for 'WHERE rank_col = 1' fail in the same query block?

    • Because ranks cannot be filtered by equality
    • Because the order of operations processes WHERE before the window function
    • Because rank_col must be a CTE result
    • Because window functions require HAVING clauses

    Answer: Because the order of operations processes WHERE before the window function. SQL processes WHERE clauses before the windowing functions are calculated. Therefore, the engine doesn't recognize the alias created by the window function in the WHERE clause. The other options are incorrect interpretations of SQL lifecycle or function usage.

    From lesson: Window Functions — ROW_NUMBER, RANK, DENSE_RANK

  86. You need to compare each employee's salary to their predecessor's salary in the same department. Which clause must be included in your OVER statement to ensure accuracy?

    • PARTITION BY department_id ORDER BY hire_date
    • GROUP BY department_id
    • ORDER BY salary DESC
    • ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING

    Answer: PARTITION BY department_id ORDER BY hire_date. Partitioning by department isolates the scope, and ordering by hire_date defines what 'predecessor' means. The other options either fail to define the relative order or interfere with the window scope.

    From lesson: LAG, LEAD, FIRST_VALUE, LAST_VALUE

  87. You attempt to get the maximum value of a column over the entire partition using LAST_VALUE, but you keep getting the value of the current row. What is the cause?

    • The table lacks a primary key.
    • The default frame clause limits the window to the current row.
    • LAST_VALUE only works with numeric data types.
    • The partition is not ordered.

    Answer: The default frame clause limits the window to the current row.. The default window frame is 'RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW', which excludes future rows. The other options do not dictate why LAST_VALUE stops at the current row.

    From lesson: LAG, LEAD, FIRST_VALUE, LAST_VALUE

  88. If you want to filter for employees whose salary is lower than the person hired immediately before them, where should the LAG function be placed?

    • In the WHERE clause of the main query.
    • In the HAVING clause of the main query.
    • In an outer query that selects from a subquery or CTE where the LAG was calculated.
    • Directly in the SELECT list, then referenced by name in the WHERE clause.

    Answer: In an outer query that selects from a subquery or CTE where the LAG was calculated.. SQL processes WHERE clauses before window functions. Wrapping in a subquery/CTE allows the engine to calculate the LAG result first, making it available for filtering. The other options cause syntax errors.

    From lesson: LAG, LEAD, FIRST_VALUE, LAST_VALUE

  89. What is the primary functional difference between using a self-join to compare adjacent rows versus using LAG/LEAD?

    • Self-joins are faster on large datasets.
    • LAG/LEAD can handle duplicates without extra logic, whereas joins cannot.
    • LAG/LEAD avoids Cartesian product issues and is more readable when maintaining partitioning.
    • Self-joins cannot be used for time-series data.

    Answer: LAG/LEAD avoids Cartesian product issues and is more readable when maintaining partitioning.. Window functions like LAG/LEAD were specifically designed to avoid the performance and logic complexities of self-joining. Joins don't have built-in partitioning and can easily result in duplicates if keys are not unique.

    From lesson: LAG, LEAD, FIRST_VALUE, LAST_VALUE

  90. Consider a query with FIRST_VALUE(salary) OVER (ORDER BY salary). If two employees have the same minimum salary, what will the output look like?

    • The engine will return NULL for the second employee.
    • Both employees will show the same minimum salary.
    • The function will return the salary of the employee with the lower ID.
    • The query will throw an error due to non-deterministic results.

    Answer: Both employees will show the same minimum salary.. FIRST_VALUE retrieves the first value in the defined window. If both have the same salary, they are equal in the sort order, so the function returns the value regardless of the duplicate. It does not return NULL or error out.

    From lesson: LAG, LEAD, FIRST_VALUE, LAST_VALUE

  91. If you perform a query with 'SUM(sales) OVER(PARTITION BY region)', what is the impact on the number of rows returned?

    • The number of rows will decrease to one per region.
    • The number of rows remains identical to the original table structure.
    • The number of rows will double to include a subtotal row.
    • The number of rows will increase based on the number of sales per region.

    Answer: The number of rows remains identical to the original table structure.. The correct answer is that the row count remains the same. Unlike GROUP BY, window functions perform calculations without collapsing rows. Option 0 describes GROUP BY behavior, Option 2 describes ROLLUP behavior, and Option 3 is unrelated to the logic of a single aggregation.

    From lesson: PARTITION BY with Window Functions

  92. What is the primary difference between a partition and a window frame when using an ORDER BY clause?

    • Partition defines the scope of data, while a window frame defines the specific set of rows relative to the current row.
    • Partition is mandatory, while a window frame is optional.
    • A window frame can only be used if there is no PARTITION BY clause.
    • Partition limits the output columns, while the frame limits the input rows.

    Answer: Partition defines the scope of data, while a window frame defines the specific set of rows relative to the current row.. The partition creates the scope (the 'bucket') and the frame defines the sliding window within that bucket. Option 1 is wrong because PARTITION BY is often optional. Option 2 is wrong because frames exist with partitions. Option 3 is incorrect as they serve different purposes.

    From lesson: PARTITION BY with Window Functions

  93. You need to find the percentage of a user's total spending compared to their total monthly spending. Why should you use 'PARTITION BY user_id, month'?

    • To group all spending into a single numeric average.
    • To ensure the denominator for the percentage calculation is isolated to that specific user and month.
    • To remove duplicate spending records from the output.
    • To sort the user's spending chronologically before calculating the percentage.

    Answer: To ensure the denominator for the percentage calculation is isolated to that specific user and month.. By partitioning by both ID and month, the aggregate function treats that specific group as the scope for the calculation. Option 0 is wrong because we are partitioning, not grouping. Option 2 describes DISTINCT. Option 3 describes ORDER BY.

    From lesson: PARTITION BY with Window Functions

  94. Why does a query containing 'WHERE rank() OVER(PARTITION BY dept) = 1' fail in SQL?

    • The PARTITION BY clause is invalid when used with ranking functions.
    • Window functions cannot be used in the WHERE clause because they are evaluated after filtering.
    • The rank function requires an ORDER BY clause in the window definition.
    • The syntax for partitioning is incorrect.

    Answer: Window functions cannot be used in the WHERE clause because they are evaluated after filtering.. SQL executes WHERE clauses before window functions. Therefore, the function cannot be evaluated at that stage. Option 0 is wrong because PARTITION BY works with rank. Option 2 is a true statement about ranking but not the reason for the WHERE clause failure. Option 3 is syntax, which is correct here.

    From lesson: PARTITION BY with Window Functions

  95. If you omit the PARTITION BY clause but keep the OVER() clause, what is the default behavior?

    • The calculation is performed over the entire dataset as one single partition.
    • The query returns a syntax error.
    • The calculation is performed on a row-by-row basis without context.
    • The window function reverts to acting like a standard aggregate function.

    Answer: The calculation is performed over the entire dataset as one single partition.. Omitting PARTITION BY treats the entire table as a single group. Option 1 is wrong because it is valid SQL. Option 2 is wrong because the function uses all data, not just the single row. Option 3 is close, but 'aggregate' implies a single value result, whereas window functions return the value per row.

    From lesson: PARTITION BY with Window Functions

  96. Which data type is most appropriate for storing a product price that requires exact precision without rounding errors?

    • FLOAT
    • DECIMAL(10,2)
    • VARCHAR(10)
    • INTEGER

    Answer: DECIMAL(10,2). DECIMAL ensures fixed-point precision necessary for financial data. FLOAT is approximate and can cause rounding errors; VARCHAR is for text; INTEGER cannot store fractional values.

    From lesson: CREATE TABLE and Data Types

  97. When creating a table, what is the primary purpose of defining a column as the PRIMARY KEY?

    • To ensure the column contains only unique, non-null values for identifying rows.
    • To define the column that will be used for search filtering only.
    • To allow the column to contain duplicate values for easier grouping.
    • To automatically sort the data in ascending order physically on the disk.

    Answer: To ensure the column contains only unique, non-null values for identifying rows.. A PRIMARY KEY uniquely identifies each record in a table and implicitly enforces NOT NULL. The other options are incorrect because primary keys are not for grouping, don't guarantee physical sort order, and must be unique.

    From lesson: CREATE TABLE and Data Types

  98. A user wants to store 'Active' or 'Inactive' status flags for thousands of records. Which data type is the most storage-efficient choice?

    • VARCHAR(255)
    • TEXT
    • CHAR(8)
    • BOOLEAN

    Answer: BOOLEAN. BOOLEAN is the most efficient choice as it is designed specifically for binary states. CHAR(8) uses unnecessary space, while VARCHAR and TEXT are overkill for simple binary flags.

    From lesson: CREATE TABLE and Data Types

  99. If you need to ensure that a 'UserEmail' column never contains an empty value, which constraint should you include in the CREATE TABLE statement?

    • UNIQUE
    • DEFAULT
    • NOT NULL
    • CHECK

    Answer: NOT NULL. NOT NULL specifically prevents a record from being inserted with a null value. UNIQUE only prevents duplicate values but allows nulls; DEFAULT provides a value if one is missing; CHECK is for logic validation.

    From lesson: CREATE TABLE and Data Types

  100. Why should you avoid using VARCHAR(MAX) for a column intended to store short country codes like 'US' or 'GB'?

    • It consumes more memory in the buffer pool and can cause index performance issues.
    • It forces the database to reject strings shorter than 10 characters.
    • It is technically impossible to use VARCHAR on primary keys.
    • It disables the ability to use the LIKE operator on that column.

    Answer: It consumes more memory in the buffer pool and can cause index performance issues.. Variable-length columns with large definitions often force the engine to allocate more overhead, impacting memory and query performance. The other options are false; VARCHAR works fine with short strings and LIKE operators.

    From lesson: CREATE TABLE and Data Types

  101. You need to update the email address for a specific user. Which approach best ensures data integrity?

    • Run the UPDATE statement without any conditions to reset the table.
    • Use a SELECT query with the unique ID first to confirm the exact row, then execute the UPDATE.
    • Perform a DELETE and then an INSERT to replace the record.
    • Update the entire table and hope the database engine keeps the original values.

    Answer: Use a SELECT query with the unique ID first to confirm the exact row, then execute the UPDATE.. Verifying the target with a SELECT statement is the safest practice. The first and fourth options will overwrite all data, leading to catastrophe. The third is inefficient and risks data loss if the insert fails.

    From lesson: INSERT, UPDATE, DELETE

  102. What is the result of executing 'DELETE FROM Employees' without a WHERE clause?

    • It deletes only the first row of the table.
    • It removes the table structure itself.
    • It deletes all records from the table but keeps the structure.
    • It throws an error and performs no action.

    Answer: It deletes all records from the table but keeps the structure.. In standard SQL, a DELETE statement without a WHERE clause acts on all rows in the table. It does not drop the table structure. Option 1 is incorrect because it lacks a filter, and option 4 is incorrect because the statement is syntactically valid.

    From lesson: INSERT, UPDATE, DELETE

  103. Which statement correctly adds a new employee named 'John' with ID 101?

    • INSERT INTO Employees VALUES ('John', 101);
    • INSERT Employees (Name, ID) VALUES (John, 101);
    • INSERT INTO Employees (Name, ID) VALUES ('John', 101);
    • UPDATE Employees SET Name = 'John' WHERE ID = 101;

    Answer: INSERT INTO Employees (Name, ID) VALUES ('John', 101);. Option 3 correctly specifies column names and uses quotes for the string literal. Option 1 assumes column order which is risky. Option 2 fails to quote the string 'John'. Option 4 is an update, not an insertion.

    From lesson: INSERT, UPDATE, DELETE

  104. When performing an UPDATE on multiple columns, which syntax is correct?

    • UPDATE Table SET Col1 = 'A', Col2 = 'B' WHERE Id = 1;
    • UPDATE Table SET Col1 = 'A' AND SET Col2 = 'B' WHERE Id = 1;
    • UPDATE Table SET Col1 = 'A'; SET Col2 = 'B' WHERE Id = 1;
    • UPDATE Table WHERE Id = 1 SET Col1 = 'A', Col2 = 'B';

    Answer: UPDATE Table SET Col1 = 'A', Col2 = 'B' WHERE Id = 1;. Standard SQL requires comma separation for multiple columns in a single SET clause. Option 1 follows this. Options 2 and 3 use invalid syntax (AND/semicolon), and Option 4 has the WHERE clause in the wrong sequence.

    From lesson: INSERT, UPDATE, DELETE

  105. Why is it important to use a transaction when performing a large DELETE operation?

    • It makes the deletion process run faster than a single statement.
    • It allows you to undo the deletion if you realize you targeted the wrong rows.
    • It automatically adds a WHERE clause to your statement.
    • It converts the DELETE operation into an UPDATE operation.

    Answer: It allows you to undo the deletion if you realize you targeted the wrong rows.. Transactions provide atomicity and the ability to rollback. Option 1 is false (transactions often add overhead), Option 3 is false, and Option 4 is logically incorrect as DELETE and UPDATE perform different functions.

    From lesson: INSERT, UPDATE, DELETE

  106. Which of the following describes the functional difference between TRUNCATE and DROP TABLE?

    • TRUNCATE preserves table structure, while DROP removes the structure entirely.
    • DROP preserves table structure, while TRUNCATE removes the structure entirely.
    • TRUNCATE is a DML statement, whereas DROP is a DDL statement.
    • There is no functional difference; both delete data and the schema definition.

    Answer: TRUNCATE preserves table structure, while DROP removes the structure entirely.. TRUNCATE removes all rows while keeping the schema intact, whereas DROP removes the definition and the data. The third option is incorrect because both are typically classified as DDL.

    From lesson: ALTER TABLE and DROP

  107. When modifying a column using ALTER TABLE, what is the most common reason for a 'null value' error?

    • The column name already exists in the table.
    • The table is currently locked by another transaction.
    • Existing rows contain NULL values, and you are trying to add a NOT NULL constraint without providing a default.
    • The table has an index on the column being modified.

    Answer: Existing rows contain NULL values, and you are trying to add a NOT NULL constraint without providing a default.. Adding a NOT NULL constraint requires all existing rows to satisfy the condition; without a default, the existing NULLs trigger a constraint violation. The other options refer to metadata conflicts or locking, not row-level data violations.

    From lesson: ALTER TABLE and DROP

  108. If you need to rename a column in a SQL table, which approach is considered standard?

    • Use ALTER TABLE table_name SET COLUMN new_name = old_name.
    • Use ALTER TABLE table_name RENAME COLUMN old_name TO new_name.
    • Use MODIFY TABLE table_name CHANGE old_name new_name.
    • Use UPDATE table_name SET COLUMN_NAME = new_name.

    Answer: Use ALTER TABLE table_name RENAME COLUMN old_name TO new_name.. The standard SQL syntax for renaming a column is RENAME COLUMN. The other options use invalid syntax or confuse column renaming with data updates.

    From lesson: ALTER TABLE and DROP

  109. What happens if you attempt to DROP a table that contains data referenced by a foreign key in another table?

    • The table is dropped and the foreign key constraint is automatically converted to NULL.
    • The database operation fails due to a foreign key constraint violation.
    • The database drops the table and orphans the data in the child table.
    • The database automatically drops the child table as well.

    Answer: The database operation fails due to a foreign key constraint violation.. Relational databases enforce integrity; dropping a parent table while children exist violates the constraint. The other options suggest unsafe automated behavior that databases avoid to prevent data corruption.

    From lesson: ALTER TABLE and DROP

  110. When altering a column data type from a larger capacity to a smaller one (e.g., VARCHAR(255) to VARCHAR(10)), what is the primary risk?

    • The column name will be reset to default.
    • All indexes associated with the column are dropped.
    • Data truncation if existing values exceed the new smaller capacity.
    • The table will automatically convert to a READ-ONLY state.

    Answer: Data truncation if existing values exceed the new smaller capacity.. Reducing capacity risks losing data that does not fit in the new constraints. The other options are incorrect as renaming, indexes, and read-only states are not the primary risk of type capacity changes.

    From lesson: ALTER TABLE and DROP

  111. What happens if you attempt to insert a duplicate value into a column defined with a UNIQUE constraint that currently contains no NULL values?

    • The database allows the insert but marks it with a warning.
    • The database truncates the duplicate value to fit.
    • The database rejects the insert and throws an integrity violation error.
    • The database automatically creates a new row with a modified value.

    Answer: The database rejects the insert and throws an integrity violation error.. A UNIQUE constraint enforces data integrity by preventing identical values in a column. Option 2 is correct because the database engine will block the transaction. Options 0, 1, and 3 are incorrect because SQL constraints are absolute rules that do not permit data modification or warnings to bypass the uniqueness requirement.

    From lesson: Constraints — PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL

  112. Consider a table 'Orders' with a FOREIGN KEY referencing 'Customers(id)'. What occurs if you try to delete a customer record that still has associated orders?

    • The customer is deleted and orders are deleted automatically.
    • The deletion is blocked to prevent orphaned records in the Orders table.
    • The orders are moved to a temporary archive table.
    • The foreign key is temporarily disabled to allow the deletion.

    Answer: The deletion is blocked to prevent orphaned records in the Orders table.. Referential integrity dictates that a child record cannot exist without a valid parent. Option 1 is correct because the database prevents the deletion. Options 0, 2, and 3 are incorrect because cascading is not automatic unless explicitly defined (ON DELETE CASCADE), and the database does not archive or disable constraints on its own.

    From lesson: Constraints — PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL

  113. Why is it best practice to define a column as NOT NULL even if a UNIQUE constraint exists on it?

    • It increases the storage efficiency of the database table.
    • It allows the query optimizer to perform faster index scans.
    • It prevents ambiguity regarding the identity of the records.
    • It automatically upgrades the UNIQUE constraint to a PRIMARY KEY.

    Answer: It prevents ambiguity regarding the identity of the records.. A primary goal of database design is ensuring every record is identifiable. Option 2 is correct because NOT NULL forces explicit data entry, avoiding the ambiguity of NULL values. Options 0 and 1 are secondary performance concerns, while option 3 is false as a UNIQUE constraint never automatically becomes a PRIMARY KEY.

    From lesson: Constraints — PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL

  114. If a table has a composite PRIMARY KEY consisting of (OrderID, ProductID), what does this imply?

    • Each OrderID must be unique across the entire table.
    • Each ProductID must be unique across the entire table.
    • The combination of OrderID and ProductID must be unique for every row.
    • The table cannot have any foreign keys referencing it.

    Answer: The combination of OrderID and ProductID must be unique for every row.. A composite PRIMARY KEY treats the group of columns as a single identifier. Option 2 is correct because it ensures that the tuple (OrderID, ProductID) is unique. Options 0 and 1 are incorrect because individual columns in a composite key can repeat as long as the pair does not. Option 3 is incorrect as composite keys can be referenced by foreign keys.

    From lesson: Constraints — PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL

  115. Which scenario best describes the intended use of a FOREIGN KEY constraint?

    • To ensure that values in a child table correspond to existing values in a parent table.
    • To make sure that column names are consistent across all tables in the database.
    • To allow a column to store multiple values in a single row.
    • To replace the need for a JOIN statement when querying data.

    Answer: To ensure that values in a child table correspond to existing values in a parent table.. The FOREIGN KEY is the primary mechanism for establishing relationships between tables. Option 0 is correct because it links tables through referential integrity. Option 1 relates to naming conventions, option 2 describes arrays (which SQL tables don't use), and option 3 is false because foreign keys facilitate joins rather than replace them.

    From lesson: Constraints — PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL

  116. A table contains an 'OrderItems' column that stores a comma-separated list of product IDs. Which Normal Form is violated and why?

    • 1NF, because values must be atomic.
    • 2NF, because of partial dependency.
    • 3NF, because of transitive dependency.
    • BCNF, because of candidate key overlap.

    Answer: 1NF, because values must be atomic.. 1NF requires that all attributes contain atomic (indivisible) values; storing multiple IDs in one cell violates this. The other options are incorrect because those forms deal with dependencies between columns rather than the atomicity of data within a column.

    From lesson: Normalization — 1NF, 2NF, 3NF

  117. A table uses (StudentID, CourseID) as a primary key. The attribute 'InstructorOffice' is stored here, but it only depends on 'CourseID'. Which Normal Form is violated?

    • 1NF
    • 2NF
    • 3NF
    • It is in 3NF

    Answer: 2NF. This violates 2NF because 'InstructorOffice' has a partial dependency on the composite key (it depends on only part of the key). 1NF is satisfied as values are atomic; 3NF is not reached because 2NF is failed; it is not in 3NF because it fails 2NF.

    From lesson: Normalization — 1NF, 2NF, 3NF

  118. Consider a table: {OrderID, CustomerID, CustomerZipCode}. If CustomerZipCode is determined by CustomerID, which form does this violate?

    • 1NF
    • 2NF
    • 3NF
    • This table is in 3NF

    Answer: 3NF. This is a transitive dependency (OrderID -> CustomerID -> ZipCode). Since ZipCode is a non-key attribute depending on another non-key attribute (CustomerID), it fails 3NF. It satisfies 1NF (atomic) and 2NF (full key dependency).

    From lesson: Normalization — 1NF, 2NF, 3NF

  119. When moving from 2NF to 3NF, what is the primary goal regarding column relationships?

    • Removing all multi-valued attributes.
    • Ensuring every column depends only on the primary key.
    • Eliminating transitive dependencies between non-key attributes.
    • Combining all related tables into a single wide table.

    Answer: Eliminating transitive dependencies between non-key attributes.. 3NF specifically addresses the removal of transitive dependencies. The first option is the goal of 1NF; the second is the goal of 2NF; the fourth is the opposite of normalization, which increases redundancy.

    From lesson: Normalization — 1NF, 2NF, 3NF

  120. Which of the following scenarios best represents a table that is in 2NF but NOT in 3NF?

    • A table where a column depends on only part of a composite key.
    • A table where an attribute is not atomic.
    • A table where a non-key column depends on another non-key column.
    • A table with no primary key defined.

    Answer: A table where a non-key column depends on another non-key column.. If a non-key column depends on another non-key column, it has a transitive dependency, violating 3NF, but if all non-key columns depend on the full primary key, it remains in 2NF. The other options describe violations of 1NF or 2NF.

    From lesson: Normalization — 1NF, 2NF, 3NF

  121. A query performs a full table scan even though an index exists on the 'status' column. Which query is most likely causing this?

    • SELECT * FROM orders WHERE status = 'SHIPPED'
    • SELECT * FROM orders WHERE status LIKE 'SHIP%'
    • SELECT * FROM orders WHERE status + 1 = 2
    • SELECT * FROM orders WHERE status IN ('SHIPPED', 'PENDING')

    Answer: SELECT * FROM orders WHERE status + 1 = 2. Applying math to a column in a WHERE clause makes the index unusable because the database must calculate the value for every row. The other options are SARGable (Search ARGumentable) and allow the engine to perform index seeks.

    From lesson: Indexes and Query Performance

  122. Which scenario best justifies the creation of a composite index on (last_name, first_name)?

    • Frequent queries filtering by first_name only
    • Queries searching for a specific first_name and sorting by last_name
    • Frequent queries filtering by last_name, or both last_name and first_name
    • Queries that perform an aggregate COUNT(*) on the entire table

    Answer: Frequent queries filtering by last_name, or both last_name and first_name. Composite indexes work on the leftmost prefix rule. It supports filtering by the first column alone or both, but not the second column alone. Option 1 and 2 violate the order, while option 4 is usually better handled by a single-column index or a primary key.

    From lesson: Indexes and Query Performance

  123. How does an excessive number of indexes impact database performance during DML operations?

    • It increases the time required to perform INSERT and UPDATE operations
    • It decreases the storage requirements of the database
    • It speeds up SELECT queries by providing more access paths
    • It eliminates the need for table locks

    Answer: It increases the time required to perform INSERT and UPDATE operations. Every index must be updated whenever data changes, which creates overhead. Options 1 is correct; option 2 is false as indexes take space, option 3 is misleading because the optimizer only picks the 'best' index, and option 4 is irrelevant.

    From lesson: Indexes and Query Performance

  124. When is a 'Covering Index' most beneficial for query performance?

    • When the index contains all columns mentioned in the SELECT, JOIN, and WHERE clauses
    • When the index is built on a column with many null values
    • When the table is small enough to fit entirely in memory
    • When the query requires a full table scan

    Answer: When the index contains all columns mentioned in the SELECT, JOIN, and WHERE clauses. A covering index allows the engine to retrieve all requested data directly from the index tree without fetching the actual table row, drastically reducing I/O. Other options are incorrect as they don't describe the benefit of data inclusion.

    From lesson: Indexes and Query Performance

  125. Why might an optimizer choose to perform a full table scan instead of using an existing index?

    • The index is too small to be useful
    • The query is retrieving a very large percentage of the total table rows
    • The index was not recently defragmented
    • The database is using a non-relational storage engine

    Answer: The query is retrieving a very large percentage of the total table rows. If a query returns a high percentage of rows, the overhead of performing index lookups (B-tree traversal plus heap fetching) is higher than just reading the entire table sequentially. The other choices are generally not primary factors for ignoring an index.

    From lesson: Indexes and Query Performance

  126. When querying a standard view, what is the database actually executing?

    • A pre-computed snapshot of the result set
    • The underlying SELECT query defined in the view
    • A cached result stored in temporary memory
    • A direct reference to a physical table created by the view

    Answer: The underlying SELECT query defined in the view. Standard views are virtual; option 1 and 3 describe Materialized Views, and option 4 is incorrect because views do not store physical data.

    From lesson: Views and Materialized Views

  127. Which scenario best justifies the creation of a Materialized View over a standard view?

    • When the base data changes every millisecond
    • When you need to ensure the data is always 100% current
    • When running complex, resource-heavy aggregations on static historical data
    • When you need to perform INSERT operations on the view

    Answer: When running complex, resource-heavy aggregations on static historical data. Materialized Views are optimized for read-heavy, complex queries that don't need real-time data, whereas the other options are better served by standard views or direct table access.

    From lesson: Views and Materialized Views

  128. Why might a database engine reject an UPDATE statement directed at a view?

    • The view is based on multiple tables with a JOIN
    • The view uses the DISTINCT keyword
    • The view contains aggregate functions like SUM()
    • All of the above

    Answer: All of the above. Views become 'non-updatable' when the mapping between a row in the view and a row in a base table is ambiguous, which happens in all three listed scenarios.

    From lesson: Views and Materialized Views

  129. If you add a new row to a base table, what happens to existing Materialized Views?

    • The new row is automatically reflected in the view
    • The view is dropped and must be recreated
    • The view remains unchanged until a manual or scheduled refresh is performed
    • The view throws an error until the data is synchronized

    Answer: The view remains unchanged until a manual or scheduled refresh is performed. Materialized Views are static snapshots; they are not updated until an explicit refresh command is executed, unlike standard views which are dynamic.

    From lesson: Views and Materialized Views

  130. What is the primary security benefit of using a view?

    • It encrypts the underlying data in the base tables
    • It allows you to restrict user access to specific rows and columns
    • It hides the database server's IP address
    • It prevents SQL injection attacks automatically

    Answer: It allows you to restrict user access to specific rows and columns. Views act as a security layer by exposing only necessary data; they do not provide encryption (option 1), network security (option 3), or protection against code-level injection (option 4).

    From lesson: Views and Materialized Views

  131. What is the primary architectural difference between a stored procedure and a user-defined function regarding usage in a query?

    • Functions can be called within a SELECT statement, whereas procedures cannot.
    • Procedures can return table values, whereas functions are limited to scalar values.
    • Functions support transaction control, whereas procedures do not.
    • Procedures are pre-compiled, whereas functions are interpreted at runtime.

    Answer: Functions can be called within a SELECT statement, whereas procedures cannot.. Functions are designed for calculations used within queries, so they can appear in the SELECT list; procedures perform actions and cannot be directly invoked as part of a SELECT expression. Option 1 is wrong because functions can return tables. Option 2 is wrong because procedures cannot be used in SELECT. Option 3 is wrong because both are pre-compiled.

    From lesson: Stored Procedures and Functions

  132. When should you choose a stored procedure over a function for a specific business requirement?

    • When you need to perform calculations that will be used inside a WHERE clause.
    • When you need to modify multiple tables and manage transactional scope within the routine.
    • When the routine needs to return a single deterministic value based on input parameters.
    • When the code needs to be executed as part of an inline view.

    Answer: When you need to modify multiple tables and manage transactional scope within the routine.. Stored procedures allow for transaction control (COMMIT/ROLLBACK) and multiple DML operations, which are prohibited in functions. Options 0, 2, and 3 describe use cases specifically suited for functions, as they involve querying data rather than modifying it.

    From lesson: Stored Procedures and Functions

  133. What happens if a function attempts to modify data in an underlying table?

    • The operation succeeds but slows down the query performance significantly.
    • The database management system automatically converts the function into a procedure.
    • The operation is rejected because functions cannot have side effects on the database state.
    • The data is updated, but the change is rolled back after the function returns.

    Answer: The operation is rejected because functions cannot have side effects on the database state.. SQL standards enforce that functions must be deterministic and side-effect-free, meaning they cannot perform INSERT, UPDATE, or DELETE operations. The other options are incorrect because the DBMS prevents the execution entirely rather than allowing it or converting it.

    From lesson: Stored Procedures and Functions

  134. Why is it generally recommended to avoid row-by-row processing (cursors) inside stored procedures?

    • Cursors are only compatible with scalar-valued functions.
    • Cursors lock the entire database for the duration of the process.
    • Set-based operations allow the query optimizer to choose the most efficient execution plan.
    • Cursors require more memory than what is typically allocated to the database session.

    Answer: Set-based operations allow the query optimizer to choose the most efficient execution plan.. Set-based logic allows the optimizer to handle data retrieval efficiently, whereas cursors force serial execution, which ignores the optimization engine. Cursors are not limited to functions (0), do not lock the whole DB (1), and are not primarily constrained by memory (3).

    From lesson: Stored Procedures and Functions

  135. If you need a routine to perform a task that requires temporary storage of intermediate results followed by multiple conditional updates, what is the best practice?

    • Use a series of scalar functions chained together in a single SELECT query.
    • Use a stored procedure to encapsulate the logic and transaction management.
    • Use a view because views can handle complex logic through subqueries.
    • Use an inline table-valued function because it is faster than a procedure.

    Answer: Use a stored procedure to encapsulate the logic and transaction management.. Stored procedures are designed to handle complex business logic, conditional branching, and temporary state management. Functions (0, 3) cannot perform updates, and views (2) are for data presentation, not procedural control flow.

    From lesson: Stored Procedures and Functions

  136. If a transaction updates a bank balance but the server loses power before the final commit, what property prevents the partial data from being saved?

    • Atomicity
    • Consistency
    • Isolation
    • Durability

    Answer: Atomicity. Atomicity ensures that all parts of a transaction succeed or none do. Consistency ensures the database follows rules, Isolation handles concurrency, and Durability guarantees committed data persists. Atomicity is the reason the partial update is rolled back.

    From lesson: Transactions and ACID Properties

  137. Which scenario best illustrates the 'Isolation' property?

    • Two users modifying the same row, where the database forces one to wait for the other.
    • A script automatically backing up the database to a remote server every night.
    • The database rejecting an 'UPDATE' that violates a foreign key constraint.
    • A system crash occurring and the data being restored correctly after restart.

    Answer: Two users modifying the same row, where the database forces one to wait for the other.. Isolation prevents transactions from interfering with each other's intermediate states. Option 1 describes concurrency control. The others relate to Durability, Consistency, and Durability respectively.

    From lesson: Transactions and ACID Properties

  138. What is the primary result of setting a transaction isolation level to 'Read Uncommitted'?

    • It prevents all other users from reading data until the transaction completes.
    • It improves performance by allowing dirty reads where a transaction reads uncommitted changes.
    • It ensures that the database stays perfectly consistent with strict rules.
    • It allows the database to process transactions in parallel without any logging.

    Answer: It improves performance by allowing dirty reads where a transaction reads uncommitted changes.. Read Uncommitted prioritizes performance at the cost of correctness by allowing dirty reads. It does not provide total isolation, nor does it guarantee consistency or remove logging requirements.

    From lesson: Transactions and ACID Properties

  139. When does the 'Durability' property of a transaction officially start being enforced?

    • When the first DML statement is executed.
    • When the transaction reaches the end of the script block.
    • Immediately upon issuing the COMMIT command.
    • Once the database administrator runs a manual flush command.

    Answer: Immediately upon issuing the COMMIT command.. Durability is only guaranteed once a transaction is committed, ensuring the data is moved to stable storage. It is not enforced during execution, at the end of a block, or by manual administrative flushes.

    From lesson: Transactions and ACID Properties

  140. A transaction moves money from Account A to Account B. If the database crashes after the deduction from A but before the addition to B, what prevents the money from disappearing?

    • The isolation level will automatically retry the transaction.
    • The Consistency property forces the database to balance the ledger.
    • The transaction log is used during recovery to rollback the unfinished state.
    • The primary key constraint will detect the error and block the commit.

    Answer: The transaction log is used during recovery to rollback the unfinished state.. The transaction log allows the recovery manager to undo the partial transaction (rollback) to restore the database to a valid state. Consistency defines the target, but the log/Atomicity mechanism performs the recovery.

    From lesson: Transactions and ACID Properties

  141. Which of the following best describes the difference between the WHERE and HAVING clauses?

    • WHERE filters rows before grouping, while HAVING filters groups after aggregation.
    • HAVING is used for string comparisons, while WHERE is used for numeric comparisons.
    • WHERE requires an index, whereas HAVING works on any column.
    • HAVING is used to order the final output, while WHERE is used to select columns.

    Answer: WHERE filters rows before grouping, while HAVING filters groups after aggregation.. WHERE filters individual rows before any grouping occurs. HAVING acts on the result of a GROUP BY clause to filter aggregate values. Other options incorrectly describe their functional purposes.

    From lesson: SQL Interview Questions — Basics

  142. If you want to count every row in a table including those with NULL values in specific columns, which syntax should you use?

    • COUNT(column_name)
    • COUNT(*)
    • SUM(1)
    • COUNT(DISTINCT column_name)

    Answer: COUNT(*). COUNT(*) counts the total number of rows regardless of NULL values. COUNT(column_name) skips rows where the column is NULL. The other options either require a specific column or perform unnecessary logic.

    From lesson: SQL Interview Questions — Basics

  143. What is the result of 'SELECT 10 + NULL' in a standard SQL environment?

    • 10
    • 0
    • NULL
    • Error

    Answer: NULL. In SQL, any arithmetic operation performed on a NULL value results in NULL because the missing value prevents a definitive calculation. It does not default to 0 or throw an error.

    From lesson: SQL Interview Questions — Basics

  144. When performing a LEFT JOIN, what happens when there is no matching record in the right-hand table?

    • The row from the left table is excluded from the result set.
    • The entire query returns an error.
    • The query returns NULL for all columns selected from the right-hand table.
    • The query creates a duplicate row with default values like 0 or empty strings.

    Answer: The query returns NULL for all columns selected from the right-hand table.. A LEFT JOIN preserves all rows from the left table; if no match is found, the columns from the right table are filled with NULL. It does not exclude the left row nor default to zero.

    From lesson: SQL Interview Questions — Basics

  145. Why is the use of 'SELECT *' generally discouraged in production environments?

    • It is syntactically invalid in most modern SQL databases.
    • It prevents the use of WHERE clauses.
    • It causes the database to return unnecessary data, increasing network traffic and potentially breaking code if the schema changes.
    • It forces the database to perform an automatic ORDER BY operation, slowing down performance.

    Answer: It causes the database to return unnecessary data, increasing network traffic and potentially breaking code if the schema changes.. SELECT * fetches every column, which can be inefficient and creates a brittle dependency on the table's exact column order or structure. The other options are false as it is valid, compatible with WHERE, and does not trigger automatic ordering.

    From lesson: SQL Interview Questions — Basics

  146. When comparing a NULL value using the standard equals operator in a WHERE clause, what is the result?

    • True
    • False
    • Unknown
    • Null

    Answer: Unknown. In SQL, NULL represents an unknown value. Comparing anything to NULL using '=' results in 'Unknown' (or UNKNOWN), which evaluates to false in a WHERE filter. 'False' and 'Null' are incorrect because they imply a boolean or defined result, while the standard defines this state as Unknown.

    From lesson: SQL Interview Questions — Advanced

  147. What is the primary difference between a RANK() and a DENSE_RANK() window function?

    • RANK() skips numbers, DENSE_RANK() does not
    • DENSE_RANK() skips numbers, RANK() does not
    • RANK() works on strings, DENSE_RANK() only on numbers
    • They are identical in functionality

    Answer: RANK() skips numbers, DENSE_RANK() does not. RANK() leaves gaps in the ranking sequence when ties occur (e.g., 1, 2, 2, 4), whereas DENSE_RANK() continues the sequence without gaps (e.g., 1, 2, 2, 3). Option 1 describes this correctly, while others misidentify the behavior or capabilities.

    From lesson: SQL Interview Questions — Advanced

  148. How does a Common Table Expression (CTE) differ from a subquery?

    • CTEs are always faster than subqueries
    • CTEs can be referenced multiple times within a single statement
    • Subqueries cannot be used in JOIN clauses
    • CTEs must be written as materialized tables

    Answer: CTEs can be referenced multiple times within a single statement. The key advantage of a CTE is its ability to be referenced multiple times within the same query, improving readability and modularity. CTEs are not inherently faster, subqueries can be joined, and CTEs are typically not materialized unless specified by the engine.

    From lesson: SQL Interview Questions — Advanced

  149. Which of the following describes the execution order of a SQL query involving GROUP BY?

    • SELECT -> FROM -> WHERE -> GROUP BY
    • FROM -> WHERE -> GROUP BY -> SELECT
    • FROM -> SELECT -> WHERE -> GROUP BY
    • WHERE -> FROM -> GROUP BY -> SELECT

    Answer: FROM -> WHERE -> GROUP BY -> SELECT. SQL logically processes the FROM clause first, then filters via WHERE, groups rows with GROUP BY, and finally projects the columns via SELECT. Other options reverse or mix these steps, which is logically impossible for the engine.

    From lesson: SQL Interview Questions — Advanced

  150. When using an INNER JOIN, what happens to rows in either table that do not have a match in the other?

    • They are included with NULL values for the missing data
    • They cause an error
    • They are excluded from the result set
    • They are included but marked with a flag

    Answer: They are excluded from the result set. INNER JOIN only returns rows where there is a match in both participating tables. NULL padding only occurs in OUTER JOINs. No error is thrown, and no flags are applied; the rows simply do not meet the join criteria.

    From lesson: SQL Interview Questions — Advanced

  151. Which approach is most efficient for finding the 'top 3' sales per department?

    • A self-join on the sales table comparing values
    • A window function using DENSE_RANK() partitioned by department
    • Multiple UNION ALL statements for each department
    • Using a correlated subquery in the WHERE clause

    Answer: A window function using DENSE_RANK() partitioned by department. Window functions are purpose-built for ranking within partitions. Self-joins perform poorly on large datasets, UNION ALL is unmaintainable, and correlated subqueries trigger row-by-row processing, which is slow.

    From lesson: SQL Coding Challenges — Top-N, Gaps, Deduplication

  152. To identify gaps in a sequence of numbers, which function is the most effective for comparing a row with its successor?

    • LAG()
    • LEAD()
    • RANK()
    • NTILE()

    Answer: LEAD(). LEAD() accesses data from the following row, allowing you to compare current and next values. LAG() looks backwards, RANK() ranks rows, and NTILE() buckets data, none of which directly simplify gap analysis as well as LEAD().

    From lesson: SQL Coding Challenges — Top-N, Gaps, Deduplication

  153. When deleting duplicate rows based on a specific column, why is a CTE with ROW_NUMBER() preferred over DISTINCT?

    • DISTINCT cannot be used in a DELETE statement
    • ROW_NUMBER() is faster than DISTINCT
    • DISTINCT removes the entire row, whereas ROW_NUMBER() allows you to target one record to keep while removing others
    • DISTINCT requires a GROUP BY clause that prevents deletion

    Answer: DISTINCT removes the entire row, whereas ROW_NUMBER() allows you to target one record to keep while removing others. DISTINCT filters unique result sets but cannot pinpoint specific duplicates for deletion. ROW_NUMBER() assigns a unique identifier to duplicates, allowing you to isolate one record to keep (e.g., where row_num = 1) and delete the rest.

    From lesson: SQL Coding Challenges — Top-N, Gaps, Deduplication

  154. What is the primary risk of using 'ID = ID + 1' to find gaps in a sequence?

    • It only works if the table has an auto-incrementing primary key
    • It performs a full table scan that is computationally expensive
    • It fails if the sequence has multiple missing numbers in a row
    • It creates a Cartesian product that crashes the database

    Answer: It fails if the sequence has multiple missing numbers in a row. Checking ID+1 only identifies immediate next-neighbor gaps. If two or more consecutive IDs are missing, this logic fails to identify the magnitude of the gap, whereas set-based comparison via LEAD() is more robust.

    From lesson: SQL Coding Challenges — Top-N, Gaps, Deduplication

  155. When ranking items with tied values, what is the functional difference between ROW_NUMBER() and DENSE_RANK()?

    • ROW_NUMBER() generates consecutive integers; DENSE_RANK() leaves gaps in ranking for tied values
    • ROW_NUMBER() leaves gaps; DENSE_RANK() generates consecutive integers
    • DENSE_RANK() requires an ORDER BY clause, while ROW_NUMBER() does not
    • ROW_NUMBER() is faster because it does not handle ties

    Answer: ROW_NUMBER() leaves gaps; DENSE_RANK() generates consecutive integers. ROW_NUMBER() provides unique sequential integers even for ties. DENSE_RANK() assigns the same rank to ties but does not skip the next rank, making it 'dense' compared to standard RANK(), which does skip ranks after ties.

    From lesson: SQL Coding Challenges — Top-N, Gaps, Deduplication

  156. An application requires complex reporting and joins across five distinct entities. Which data model is most appropriate?

    • A key-value store
    • A relational database
    • A document store without relationships
    • An object-storage bucket

    Answer: A relational database. The relational model is designed for set-based operations and joins; the others struggle with multi-entity joins, which would require expensive application-level processing.

    From lesson: NoSQL vs SQL — Key Differences

  157. What is the primary trade-off when selecting a strictly relational database versus a non-relational document store?

    • Computational complexity vs storage capacity
    • ACID compliance vs flexible horizontal scalability
    • Query execution speed vs index creation time
    • Data security vs server accessibility

    Answer: ACID compliance vs flexible horizontal scalability. Relational systems prioritize ACID (atomicity, consistency, isolation, durability) and referential integrity, while many NoSQL systems sacrifice immediate consistency for easier horizontal scaling.

    From lesson: NoSQL vs SQL — Key Differences

  158. In which scenario would a relational database architecture be considered superior to a document-based NoSQL architecture?

    • When the data schema changes hourly
    • When data is purely log files without structure
    • When transactional integrity across multiple tables is critical
    • When the system needs to run on limited hardware

    Answer: When transactional integrity across multiple tables is critical. Relational databases provide Foreign Key constraints and transactions that maintain integrity across multiple tables; document stores are poor at cross-document consistency.

    From lesson: NoSQL vs SQL — Key Differences

  159. A system requires a single consistent view of financial account balances across the entire cluster at all times. What is the limitation of many distributed NoSQL designs?

    • They often use eventual consistency, which may show stale balances
    • They are unable to perform math on integer values
    • They cannot store decimal numbers accurately
    • They require more memory than relational systems

    Answer: They often use eventual consistency, which may show stale balances. Many distributed non-relational systems prioritize availability over immediate consistency, whereas relational databases are built for strict consistency in financial operations.

    From lesson: NoSQL vs SQL — Key Differences

  160. Why might a developer choose to use a JSON-supporting relational database rather than a traditional document-only store?

    • To avoid learning any query languages
    • To combine structured ACID-compliant data with unstructured dynamic attributes
    • To reduce the server hardware requirements to zero
    • To eliminate the need for indexing any fields

    Answer: To combine structured ACID-compliant data with unstructured dynamic attributes. Relational databases with JSON support allow for structured schemas to handle primary entities while using flexible fields for dynamic attributes, maintaining the best of both worlds.

    From lesson: NoSQL vs SQL — Key Differences