0
0
PostgreSQLquery~10 mins

DISTINCT ON for unique per group in PostgreSQL - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to select unique users by their country using DISTINCT ON.

PostgreSQL
SELECT DISTINCT ON ([1]) user_id, country FROM users ORDER BY country, user_id;
Drag options to blanks, or click blank then click option'
Auser_id
Bcountry
Cuser_name
Demail
Attempts:
3 left
💡 Hint
Common Mistakes
Using a column not in ORDER BY with DISTINCT ON.
Selecting DISTINCT ON without specifying the column.
2fill in blank
medium

Complete the code to order users by signup date within each country.

PostgreSQL
SELECT DISTINCT ON (country) user_id, country, signup_date FROM users ORDER BY country, [1] DESC;
Drag options to blanks, or click blank then click option'
Aemail
Buser_id
Ccountry
Dsignup_date
Attempts:
3 left
💡 Hint
Common Mistakes
Ordering by a column not related to the selection.
Not ordering by the same column as DISTINCT ON.
3fill in blank
hard

Fix the error in the query to correctly select the first order per customer.

PostgreSQL
SELECT DISTINCT ON (customer_id) order_id, customer_id, order_date FROM orders ORDER BY [1];
Drag options to blanks, or click blank then click option'
Acustomer_id
Border_id
Corder_date
Dorder_status
Attempts:
3 left
💡 Hint
Common Mistakes
Ordering only by order_date without customer_id.
Using columns in ORDER BY not matching DISTINCT ON.
4fill in blank
hard

Fill both blanks to select the earliest order per customer sorted by order date.

PostgreSQL
SELECT DISTINCT ON ([1]) order_id, [2], order_date FROM orders ORDER BY customer_id, order_date;
Drag options to blanks, or click blank then click option'
Acustomer_id
Border_id
Corder_date
Dcustomer_name
Attempts:
3 left
💡 Hint
Common Mistakes
Using order_date in DISTINCT ON instead of customer_id.
Selecting customer_name instead of order_id.
5fill in blank
hard

Fill all three blanks to select the latest login per user with their email.

PostgreSQL
SELECT DISTINCT ON ([1]) [2], email, login_time FROM logins ORDER BY [3] DESC;
Drag options to blanks, or click blank then click option'
Auser_id
Clogin_time
Demail
Attempts:
3 left
💡 Hint
Common Mistakes
Ordering by email instead of login_time.
Using email in DISTINCT ON instead of user_id.