← Back to SQL, page 24

sql-0463 · Easy fresher

How would you store postal addresses for customers in many countries?

Use flexible fields: address lines, locality, administrative area, postal code and an ISO country code, with most fields optional because formats differ by country. Validate per country in the application or with a postal service. Copy the address onto orders at purchase time so later edits do not rewrite history.

Full answer
text
addresses(id, customer_id FK, label, line1, line2, locality, admin_area,
          postal_code, country_code CHAR(2) NOT NULL, created_at)

Why flexible:

  • Not every country uses postal codes, states or the same order of fields.
  • Indian addresses often include landmarks; Japanese addresses order from large to small areas.
  • A strict zip CHAR(5) breaks for UK codes like 'SW1A 1AA'.

Decisions:

  • country_code uses ISO 3166-1 alpha-2 and drives validation and formatting.
  • Keep a customer's addresses in their own table (several per customer, with a default flag).
  • Snapshot the shipping address onto each order; an order must show where it was actually shipped.
  • Geocode (latitude, longitude) separately if delivery routing needs it.

Key points

  • Flexible, mostly optional fields
  • ISO country codes
  • Validate per country
  • Several addresses per customer
  • Snapshot addresses on orders

Common mistakes

  • US-only fields like ZIP and state for everyone
  • Orders that reference editable addresses

Follow-ups

  • How would you format an address for printing?
  • How would you deduplicate addresses?

Tips

  • Explain the snapshot on orders