cswork / libraryOpen practice workspace

Coding questions · Agoda

Return Every Employee with a Mapped or Default Unique ID

Join employees to unique-ID mappings while preserving unmatched employees and applying an explicit fallback identifier.

Return every employee together with their mapped unique identifier. When an employee has no mapping, use a supplied default identifier.

Input Tables

employees(employee_id INTEGER PRIMARY KEY, employee_name TEXT NOT NULL)

employee_id_mapping(employee_id INTEGER PRIMARY KEY, unique_id INTEGER NOT NULL)

id_policy(default_unique_id INTEGER NOT NULL) contains exactly one row.

Each mapping row references an existing employee. The policy table supplies the otherwise unspecified fallback value for this exercise.

Output Contract

Write one read-only PostgreSQL query returning employee_id, employee_name, and unique_id, with one row for every employee and rows ordered by employee_id ascending. Use the mapped identifier when present and the policy's default otherwise.

Example

employees:

employee_idemployee_name
1Employee A
2Employee B

employee_id_mapping contains (employee_id = 2, unique_id = 902). id_policy contains default_unique_id = -1.

Expected result:

employee_idemployee_nameunique_id
1Employee A-1
2Employee B902

Constraints and Clarifications

  • Employee names need not be unique.
  • Missing mappings must not remove employees from the result.
  • A mapped value of zero is valid and must not be treated as missing.
  • There is at most one mapping per employee.

Hint: Preserve the employee side of the relationship

A lookup that requires both sides to match drops exactly the employees who need the fallback value.

Employees With Mapped Unique Identifiers

Table employees

columntypeconstraints
employee_idINTEGERPRIMARY KEY
employee_nameTEXTNOT NULL

Sample data:

employee_idemployee_name
104Priya Raman
101Marcus Lee
106Aisha Bello
103Priya Raman
102Dana Ortiz
105Tomas Novak

Table employee_id_mapping

columntypeconstraints
employee_idINTEGERPRIMARY KEY
unique_idINTEGERNOT NULL

Sample data:

employee_idunique_id
10550027
10150011
1030
106-1

Table id_policy

columntypeconstraints
default_unique_idINTEGERNOT NULL

Sample data:

default_unique_id
-1

Expected output

employee_idemployee_nameunique_id
101Marcus Lee50011
102Dana Ortiz-1
103Priya Raman0
104Priya Raman-1
105Tomas Novak50027
106Aisha Bello-1

Hints

  1. Preserve the employee side of the relationship: a lookup that requires both sides to match drops exactly the employees who need the fallback value.