Basic SQL Functions SQL Topic exerciseMediumVerified answerSQLite + PostgreSQL + MySQL + SQL Server live · 1 guided

Choose the First Usable Contact

Return the first nonblank trimmed email, or 'unreachable' when neither address is usable.

  • String functions
  • NULL handling
  • Sorting

Exercise brief

Understand the request

Notification platform engineer A notification export should use the primary email, then the backup, then a clear fallback.

A notification export should use the primary email, then the backup, then a clear fallback. Return the first nonblank trimmed email, or 'unreachable' when neither address is usable.

Return

  • Return record_id and contact_email.
  • Order by record_id ascending.

Constraints

  • Convert empty or whitespace-only values to NULL with NULLIF.
  • Use COALESCE in primary, backup, literal order.

Data you will use

Review the relevant tables before deciding how to join, filter, or aggregate them.

function_cases

  • record_idINTEGER
  • first_nameTEXT
  • last_nameTEXT
  • labelTEXT
  • emailTEXT
  • backup_emailTEXT
  • phoneTEXT
  • raw_unitsTEXT
  • raw_quantityTEXT
  • raw_statusTEXT
  • actual_valueREAL
  • target_valueREAL
  • completed_unitsREAL
  • elapsed_hoursREAL

Hints, when you need them

Open one clue at a time so you still do the reasoning.

Hint 1

COALESCE treats only NULL as missing; an empty string may need normalization first.

Hint 2

NULLIF(TRIM(value), '') turns blank text into NULL.

Hint 3

Place normalized primary, normalized backup, then the literal fallback in COALESCE.

Verified SQL answer

Attempt the problem first, then compare structure and reasoning—not just syntax.

Reveal solution and explanation
SELECT record_id, COALESCE(NULLIF(TRIM(email), ''), NULLIF(TRIM(backup_email), ''), 'unreachable') AS contact_email FROM function_cases ORDER BY record_id;

Why this works

Combining NULLIF with COALESCE distinguishes usable text from empty placeholders and implements a portable priority chain.

Success check

Blank strings never win the fallback chain and every record receives one contact_email.

Expected result

Use this output to verify values, aliases, ordering, and row count.

record_idcontact_email
101Alice.NG@Example.COM
102bob.backup@example.com
103unreachable
104dave.smith@example.com
105eve.li@example.com
106not-an-email
107grace@sub.example.com
108heidi@example.com

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics:

Continue practicing

SQL Practice Online

Open the interactive workspace and practice across SQL topics.