8. Merge Multiple Address Fields
Beginner Mode
Objective
Write an SQL query to retrieve each customer's ID, first name, last name, and a consolidated full address. The full address should seamlessly combine the street address, city, state, and postal code, properly handling cases where some address components may be missing. Ensure that the results are sorted by the customer ID in ascending order.
Additional information
- If an address component (street address, city, state, or postal code) is
NULL, it should be excluded from thefull_address. - Use commas and spaces to separate the available address components appropriately.
- Insert a comma and space after the street address if city, state, or postal code is present.
- Insert a comma and space after the city if state or postal code is present.
- Insert a space between the state and postal code if both are present.
- If all address components are missing, the
full_addressshould be an empty string. - The final output should include the columns:
customer_id,first_name,last_name, andfull_address. - Order the resulting records by
customer_idin ascending order.
Examples
Example 1:
Output:
Input:
| customers | ||||||
|---|---|---|---|---|---|---|
| city | customer_id | first_name | last_name | postal_code | state | street_address |
| Boston | 1 | John | Smith | 02108 | MA | 123 Main St |
| Chicago | 2 | Mary | Johnson | null | IL | 456 Oak Ave |
| Miami | 3 | Peter | Brown | 33101 | FL | null |
| null | 4 | Sarah | Davis | null | null | 789 Pine Rd |
| customer_id | first_name | full_address | last_name |
|---|---|---|---|
| 1 | John | 123 Main St, Boston, MA 02108 | Smith |
| 2 | Mary | 456 Oak Ave, Chicago, IL | Johnson |
| 3 | Peter | Miami, FL 33101 | Brown |
| 4 | Sarah | 789 Pine Rd | Davis |
Code Environment
Sign in or try as guest to run your code.
Essential
SQL 0/33
Spark 0/20
Snowflake 0/22
Python 0/24
Need more practice in this area? Explore more questions →
Datadog
Revolut
Accenture
Adobe
Google
LinkedIn
Samsung
Wix
Dropbox
Meta
OpenAI
Hulu
Uber
X
DoorDash
Anthropic
Amazon
ActivisionBlizzard
Vercel
Crypto.Com
Zscaler
DeutscheBank
Apple
GoDaddy
GitLab
BMW
PayPal
Snowflake
AMD
Twilio
Atlassian
JPMorgan
NVIDIA
IBM
Databricks
Coinbase
Cisco
Robinhood
Twitter
Microsoft
Palantir
Netflix
VMware
Cloudflare
Stripe
Lyft
Salesforce
GitHub
Bloomberg
Airbnb
Walmart
SAP
HashiCorp
Instacart
Mastercard
Intel
Visa
Tesla