DavidSzczesniak
1/25/2018 - 4:42 PM

AUTO_INCREMENT

Allows you to create a unique identifer for a row without running a SELECT query.

\!h How it works:
-- When a value isn't provided for whatver column(artist_id here), the value should be one more than the maximum currently stored in the table.
-- Begins at 1 for an empty table.

\!h Rules:
-- Column auto_incremented must be indexed
-- Column also can't have a DEFAULT value
-- Only one AUTO_INCREMENT column per table

\!h NOTE: Deleting some parts of the table will keep the counter where it left off.
However, truncating the whole table and removing all its current values, resets the counter back to 1.

\!h Example
-- Drop table
DROP TABLE artist;

-- Re-create table
CREATE TABLE artist (
artist_id SMALLINT(5) NOT NULL AUTO_INCREMENT, 
artist_name CHAR(128) DEFAULT NULL,
PRIMARY KEY (artist_id)
);

-- You can now insert rows, without putting in artist_id:
INSERT INTO artist VALUES(NULL, "The Shamen"); -- gets the id of '1'
INSERT INTO artist VALUES(NULL, "Probot"); -- gets id 2
INSERT INTO artist VALUES(NULL, "The Cult"); -- gets id 3

-- Outcome:
+-----------+-------------+
| artist_id | artist_name |
+-----------+-------------+
|         1 | The Shamen  |
|         2 | Probot      |
|         3 | The Cult    |
+-----------+-------------+