Challenge - 5 Problems
NTILE Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Understanding NTILE distribution buckets
Given the table sales with columns
id and amount, what is the output of this query?SELECT id, amount, NTILE(3) OVER (ORDER BY amount) AS bucket FROM sales ORDER BY id;
PostgreSQL
CREATE TABLE sales (id INT, amount INT); INSERT INTO sales VALUES (1, 100), (2, 200), (3, 300), (4, 400), (5, 500), (6, 600), (7, 700); SELECT id, amount, NTILE(3) OVER (ORDER BY amount) AS bucket FROM sales ORDER BY id;
Attempts:
2 left
💡 Hint
NTILE divides rows into equal groups as evenly as possible, ordered by the specified column.
✗ Incorrect
NTILE(3) splits 7 rows into 3 buckets. The first bucket gets 3 rows, the next two buckets get 2 rows each. Rows are ordered by amount ascending.
❓ query_result
intermediate2:00remaining
NTILE with ties in ordering column
Consider the table
scores with columns player and score. What is the output of this query?SELECT player, score, NTILE(4) OVER (ORDER BY score DESC) AS quartile FROM scores ORDER BY player;
PostgreSQL
CREATE TABLE scores (player TEXT, score INT); INSERT INTO scores VALUES ('Alice', 90), ('Bob', 80), ('Charlie', 80), ('David', 70), ('Eve', 60), ('Frank', 50), ('Grace', 40), ('Heidi', 30); SELECT player, score, NTILE(4) OVER (ORDER BY score DESC) AS quartile FROM scores ORDER BY player;
Attempts:
2 left
💡 Hint
NTILE assigns rows evenly but does not group ties together; ordering is strict.
✗ Incorrect
NTILE(4) divides 8 rows into 4 buckets of 2 rows each ordered by score descending. So first 2 rows bucket 1, next 2 bucket 2, etc. Bob and Charlie both have 80 but are split across buckets 1 and 2.
📝 Syntax
advanced1:30remaining
Identify the syntax error in NTILE usage
Which option contains a syntax error when using NTILE in PostgreSQL?
Attempts:
2 left
💡 Hint
NTILE requires a number inside the parentheses.
✗ Incorrect
NTILE() without a number inside parentheses is a syntax error. It must be NTILE(n) where n is a positive integer.
❓ optimization
advanced2:00remaining
Optimizing NTILE calculation on large data
You want to assign NTILE(10) buckets on a large table
transactions ordered by transaction_date. Which approach is most efficient?Attempts:
2 left
💡 Hint
Indexes help speed up ORDER BY operations used in window functions.
✗ Incorrect
Creating an index on the ordering column helps PostgreSQL efficiently order rows for NTILE calculation, improving performance on large tables.
🧠 Conceptual
expert1:30remaining
NTILE behavior with uneven row counts
If a table has 11 rows and you use
NTILE(4), how many rows will be in each bucket?Attempts:
2 left
💡 Hint
NTILE tries to distribute rows as evenly as possible, with earlier buckets getting the extra rows.
✗ Incorrect
11 rows divided into 4 buckets means 2 or 3 rows per bucket. The first buckets get the extra rows, so buckets 1, 2, and 3 have 3 rows, bucket 4 has 2 rows.