Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL relational tables and Primary Keys data types

I'm working on building a MySQL database that will have many related tables. I know I can create a primary key that is unique and auto increments, then reference that Primary Key as a Foreign Key in the related table. My question is what are best practices for Primary/Foreign key data types (int, varchar, etc..). I want to make sure I get this right the first time.

Thank you

like image 958
ItsPronounced Avatar asked Aug 12 '11 19:08

ItsPronounced


People also ask

Is primary key a data type in MySQL?

What is a primary key in MySQL? In MySQL, a primary key is a single field or combination of fields that uniquely defines a record. None of the fields that are part of the primary key can contain a NULL value. A table can have only one primary key.

Do relational tables need a primary key?

Every table can have (but does not have to have) a primary key. The column or columns defined as the primary key ensure uniqueness in the table; no two rows can have the same key.

What data type is a primary key?

A primary key (PK) is a specific type of database constraint. It guarantees that the column (or columns) that are part of it do not accept NULL values and that the value (or combination of values) entered for each row is unique. Tables may have multiple UNIQUE keys (which accept NULLs), but only one primary key.

Which are the primary categories of data types in MySQL?

MySQL supports SQL data types in several categories: numeric types, date and time types, string (character and byte) types, spatial types, and the JSON data type.


1 Answers

In MySQL most commonly used datatype is INT UNSIGNED. It's 4 bytes long and can store numbers up to 4 billion which is more than enough for majority of applications. Using BIGINT (8B - 18446744073709551615 range) is usually an overkill when just starting with your application. Before your database gets too large for INT primary key, you'll need to hire a professional DBA anyway to help you with other issues.

CHAR or BINARY datatypes can be used, when GUID type Primary key is used - such keys make it easier to shard data across multiple database instances, however with MySQL a multi master replication is more often seen.

When using InnoDB tables it's good to remember, that PK will be implicitly the last column in all other indexes created on specific table. This makes it important to use reasonably short datatype for PK (again 4B INT usually does its job well).

like image 199
Mchl Avatar answered Nov 15 '22 19:11

Mchl