Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three customer addresses in one table or in separate tables?

In my application I have a Customer class and an Address class. The Customer class has three instances of the Address class: customerAddress, deliveryAddress, invoiceAddress.

Whats the best way to reflect this structure in a database?

  • The straightforward way would be a customer table and a separate address table.
  • A more denormalized way would be just a customer table with columns for every address (Example for "street": customer_street, delivery_street, invoice_street)

What are your experiences with that? Are there any advantages and disadvantages of these approaches?

like image 230
Daniel Rikowski Avatar asked Nov 22 '08 08:11

Daniel Rikowski


People also ask

When should I put an attribute in a separate table?

You should put an attribute in a separate table whenever you expect that one person could have multiple of that attribute. Otherwise, there's not much reason to separate it, and there can be some conceptual overhead in doing so.

What are customer tables?

The customer table contains a list of all customers. The customer table is referred to in the payment and rental tables and refers to the address and store tables using foreign keys.


2 Answers

If you are 100% certain that a customer will only ever have the 3 addresses you described then this is OK:

CREATE TABLE Customer
(
    ID int not null IDENTITY(1,1) PRIMARY KEY,
    Name varchar(60) not null,
    customerAddress int not null
        CONSTRAINT FK_Address1_AddressID FOREIGN KEY References Address(ID),
    deliveryAddress int null
            CONSTRAINT FK_Address2_AddressID FOREIGN KEY References Address(ID),
    invoiceAddress int null
            CONSTRAINT FK_Address3_AddressID FOREIGN KEY References Address(ID),
    -- etc
)

CREATE TABLE Address
(
    ID int not null IDENTITY(1,1) PRIMARY KEY,
    Street varchar(120) not null
    -- etc
)

Otherwise I would model like this:

CREATE TABLE Customer
(
    ID int not null IDENTITY(1,1) PRIMARY KEY,
    Name varchar(60) not null
    -- etc
)

CREATE TABLE Address
(
    ID int not null IDENTITY(1,1) PRIMARY KEY,
    CustomerID int not null
        CONSTRAINT FK_Customer_CustomerID FOREIGN KEY References Customer(ID),
    Street varchar(120) not null,
    AddressType int not null 
    -- etc
)
like image 177
Mitch Wheat Avatar answered Sep 20 '22 21:09

Mitch Wheat


I'd go (as database theory teaches) for two separate tables: Customer and Address.

The idea of putting three fields in the Customer table is bad, as you say, because it would violate normalization rules (and fail when addresses would become more than three).

edit: also, I'd split the Address table record in several fields, one for the toponomastic prefix, one for the street, etc. and put a unique key on those. Otherwise, you'd end with a database full of duplicates.

like image 43
friol Avatar answered Sep 19 '22 21:09

friol