Sunday, August 11, 2013

Normalization

Each column must contain only 1 value

Bad:

mysql> CREATE TABLE customer
    -> (
    -> name VARCHAR(45) NOT NULL, Jose Mayorquin....

No repeating values

Bad:

mysql> CREATE TABLE customer
    -> (
    -> name VARCHAR(45) NOT NULL,
    -> address VARCHAR(1000) NOT NULL,
    -> phone1 VARCHAR(30) NOT NULL,
    -> phone2 VARCHAR(30) NOT NULL...........


It would be better to create another table that just contains phone numbers since people are likely to have multiple phone numbers, and break address up into 'address', 'street', 'city', 'state', and 'zip.'

If you want to escape from a mistake:

mysql> CREATE TABLE customer
    -> (
    -> name VARCHAR(45) NOT NULL,
    -> address VARCHAR(1000o0o0o0o) NOT NULL,
    -> phone1 VARCHAR(30) NOT NULL,
    -> phone2 VARCHAR(30) NOT NULL,#What do I do?
    -> \c

Better:

mysql> CREATE TABLE customer
    -> (
    -> first_name VARCHAR(15) NOT NULL,
    -> Last_name VARCHAR(25) NOT NULL,
    -> address VARCHAR(25) NOT NULL,
    -> street VARCHAR(40) NOT NULL,
    -> city VARCHAR(20) NOT NULL,
    -> state VARCHAR(2) NOT NULL,
    -> zip SMALLINT(5) NOT NULL,
    -> phone_id TINYINT(1) UNSIGNED NOT NULL,#Foreign Key
    -> order_id SMALLINT(5)#Another Foreign Key
    -> cust_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    -> PRIMARY KEY(cust_id)#Notify SQL what the primary key is
    -> );
This would be even better if the address columns were taken out and made into their own table. You can not have anything in  table that does not directly relate to the primary key: that is what the foreign keys are for. City, State and Zip are not personal to the customer and should therefore be in a separate table that is related by the address foreign key.

mysql> CREATE TABLE phone
    -> phone_id TINYINT(1) UNSIGNED NOT NULL AUTO_INCREMENT,
    -> number VARCHAR(40) NOT NULL,
    -> number VARCHAR(40) NOT NULL,
    -> PRIMARY KEY(phone_id)
    -> );

mysql> CREATE TABLE orders
    -> product number VARCHAR(40) NOT NULL,
    -> prod_quant SMALLINT(5) UNSIGNED NOT NULL,
    -> order_date DATE NOT NULL,
    -> price FLOAT NOT NULL,
    -> order_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    -> PRIMARY KEY(order_id)
    -> );#This is a bad example of an orders table

No comments:

Post a Comment