Coding questions · Meta
Find Values Owned Only by the Selected User
Use PostgreSQL to find values belonging to one selected user and no other user, while handling repeated values and shared ownership.
Find the values associated with a chosen user that are not associated with any other user.
Input Tables
user_values
| Column | Type | Meaning |
|---|---|---|
row_id | INTEGER | Primary key |
user_id | INTEGER | Non-null user identifier |
item_value | TEXT | Non-null value associated with that user |
selected_user contains exactly one row with one non-null INTEGER column, user_id.
These tables are an explicit relational representation of a mapping from users to their values. A user may have repeated rows for the same value.
Output Contract
Write one read-only PostgreSQL query returning a single column, item_value. Return each value owned by the selected user exactly once only if no different user owns that value. Sort values ascending. Compare values exactly as stored.
Example
selected_user contains user_id = 10.
| row_id | user_id | item_value |
|---|---|---|
| 1 | 10 | apple |
| 2 | 10 | pear |
| 3 | 10 | pear |
| 4 | 20 | apple |
| 5 | 30 | plum |
Expected result:
| item_value |
|---|
| pear |
Constraints and Clarifications
- Repeated ownership by the selected user does not disqualify a value.
- Ownership by even one different user disqualifies it.
- A selected user with no values produces no rows.
- Values are nonempty lowercase English strings; there are no null values.
Hint: Separate repetition from shared ownership
Several rows for one user are different from a matching row for another user. Check the identity of the owner when excluding shared values.
Values Owned Only by the Selected User
Table user_values
| column | type | constraints |
|---|---|---|
| row_id | INTEGER | PRIMARY KEY |
| user_id | INTEGER | NOT NULL |
| item_value | TEXT | NOT NULL |
Sample data:
| item_value | row_id | user_id |
|---|---|---|
| kiwi | 1 | 42 |
| apple | 2 | 42 |
| mango | 3 | 42 |
| mango | 4 | 42 |
| apple | 5 | 17 |
| banana | 6 | 42 |
| banana | 7 | 23 |
| banana | 8 | 23 |
| cherry | 9 | 17 |
| cherry | 10 | 23 |
| grape | 11 | 42 |
| grapefruit | 12 | 17 |
| lemon | 13 | 58 |
| fig | 14 | 42 |
| lemon | 15 | 58 |
Table selected_user
| column | type | constraints |
|---|---|---|
| user_id | INTEGER | NOT NULL |
Sample data:
| user_id |
|---|
| 42 |
Expected output
| item_value |
|---|
| fig |
| grape |
| kiwi |
| mango |
Hints
- Separate repetition from shared ownership: several rows for one user are different from a matching row for another user. Check the identity of the owner when excluding shared values.