Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: what's the difference between INDEX, UNIQUE, FOREIGN KEY, and PRIMARY KEY?

Ok, so i'm a newbie here at SQL..

I'm settings up my tables, and i'm getting confused on indexes, keys, foreign keys..

I have a users table, and a projects table.

I want to use the users (id) to attach a project to a user.

This is what I have so far:

DROP TABLE IF EXISTS projects;

CREATE TABLE projects (
    id int(8) unsigned NOT NULL,
    user_id int(8),
    name varchar(120) NOT NULL,
    description varchar(300),
    created_at date,
    updated_at date,
    PRIMARY KEY (id),
    KEY users_id (user_id)
) ENGINE=InnoDB;

ALTER TABLE projects (
    ADD CONSTRAINT user_projects,
    FOREIGN KEY (user_id) REFERENCES users(id),
    ON DELETE CASCADE
)

So what I'm getting lost on is what is the differences between a key, an index, a constraint and a foreign key?

I've been looking online and can't find a newbie explanation for it.

PS. I'm using phpactiverecord and have the relationships set up in the models

user-> has_many('projects');

projects -> belongs_to('user');

Not sure if that has anything to do with it, but thought i'd throw it in there..

Thanks.

EDIT:

I thought it could possible be something to do with Navicat, so I went into WampServer -> phpMyAdmin and ran this...

DROP TABLE IF EXISTS projects;

CREATE TABLE projects (
    id int(8) unsigned NOT NULL,
    user_id int(8) NOT NULL,
    name varchar(120) NOT NULL,
    description varchar(300),
    created_at date,
    updated_at date,
    PRIMARY KEY (id),
    KEY users_id (user_id),
    FOREIGN KEY (user_id) REFERENCES users(id)
) ENGINE=InnoDB;

Still nothing... :(

like image 444
Jake Chapman Avatar asked Dec 02 '12 21:12

Jake Chapman


People also ask

What is difference between primary key and unique key and foreign key?

A primary key is used to ensure data in the specific column is unique. A foreign key is a column or group of columns in a relational database table that provides a link between data in two tables. It uniquely identifies a record in the relational database table.

What are the differences between a primary key and a unique index?

Primary key will not accept NULL values whereas Unique key can accept NULL values. A table can have only one primary key whereas there can be multiple unique key on a table. A Clustered index automatically created when a primary key is defined whereas Unique key generates the non-clustered index.

What is difference between primary key and unique key in mysql?

The primary key is accepted as a unique or sole identifier for every record in the table. In the case of a primary key, we cannot save NULL values. In the case of a unique key, we can save a null value, however, only one NULL value is supported.

Is unique same as foreign key?

A foreign key can refer to either a unique or a primary key of the parent table. If the foreign key refers to a non-primary unique key, you must specify the column names of the key explicitly.


1 Answers

Expanding on Shamil's answers:

INDEX is similar to the index at the back of a book. It provides a simplified look-up for the data in that column so that searches on it are faster. Fun details: MyISAM uses a hashtable to store indexes, which keys the data, but is still linearly proportional in depth to the table size. InnoDB uses a B-tree structure for its indexes. A B-tree is similar to a nested set - it breaks down the data into logical child groups, meaning search depth is significantly smaller. As such, lookups by ranges are faster in a InnoDB, whereas lookups of a single key are faster in MyISAM (try to remember the Big O of hashtables and binary trees).

UNIQUE INDEX is an index in which each row in the database must have a unique value for that column or group of columns. This is useful for preventing duplication, e.g. for an email column in a users table where you want only one account per email address. Important note that in MySQL, an INSERT... ON DUPLICATE KEY UPDATE statement will execute the update if it finds a duplicate unique index match, even if it's not your primary key. This is a pitfall to be aware of when using INSERT... UPDATE statements on tables with uniques. You may wind up unintentionally overwriting records! Another note about Uniques in MySQL - per the ANSI-92 standard, NULL values are not to be considered unique, which means you can have multiple NULL values in a nullable unique-indexed column. Although it's a standard, some other RDBMSes differ on implementation of this.

PRIMARY KEY is a UNIQUE INDEX that is the identifier for any given row in the table. As such, it must not be null, and is saved as a clustered index. Clustered means that the data is written to your filesystem in ascending order on the PK. This makes searches on primary key significantly faster than any other index type (as in MySQL, only the PK may be your clustered index). Note that clustering also causes concerns with INSERT statements if your data is not AUTO_INCREMENTed, as MySQL will have to shift data around on the filesystem if you insert a new row with a PK with a lower ordinal value. This could hamper your DB performance. So unless you're certain you know what you're doing, always use an auto-incremented value for your PK in MySQL.

FOREIGN KEY is a reference to a column in another table. It enforces Referential Integrity, which means that you cannot create an entry in a column which has a foreign key to another table if the entered value does not exist in the referenced table. In MySQL, a FOREIGN KEY does not improve search performance. It also requires that both tables in the key definition use the InnoDB engine, and have the same data type, character set, and collation.

like image 154
Steven Moseley Avatar answered Oct 06 '22 20:10

Steven Moseley