Aug 23, 2013  The above code should give us auto generated primary key value. The one thing to note here is method prepareStatement. We passed two arguments first the insert query string and second an array of column name. The column name should be the primary key column name of table where you inserting the record.

  1. A primary key is a key chosen to be the primary means by which rows of a table are uniquely identified. Integrity Referential dictates that the foreign key must contain values that match the primary key in the related table, or must contain null.
  2. Updating an existing AUTOINCREMENT column value also resets the AUTOINCREMENT sequence. You can retrieve the most recent automatically generated AUTOINCREMENT value with the LASTINSERTID SQL function or the mysqlinsertid C API function. These functions are connection-specific, so their return values are not affected by another.

ValuesPrimary Key Constraint is defined by creating a primary key on a table. The value in primary key mustuniquely identify each row in the table. Primary Key Constraint enforces row integrity.

Consider the following facts when defining a primary key:

  • When you create a primary key on a table, a unique index (and hence unique constraint) is automatically and implicitly created which enforces uniqueness of data in this column.

  • Primary key column cannot contain NULL values. Database engine implicitly creates a NOT NULL constraint on the primary key column.

  • A table can only have one primary key defined on it.

  • A primary key can be formed by a single column or a composition of multiple columns (i.e. composite primary key).

  • If you insert a duplicated record in primary key, you'll get an error.

What is artificial primary key?

There are two types of primary key: artificial primary key and natural primary key.

Artificial primary key is an integer number that is system auto-generated, auto-incremented, and maintained by MySQL database engine.It is the preferred way of defining and creating primary key. Artificial primary key is also known as surrogate primary key.

In MySQL, when we define a primary key as auto_increment, it will automatically increment by 1 every time when we adda new record into the table. This number is just an integer number and have no meanings whatsoever - you can call it stupid key.

Defining primary key:

Data in primary key column CategoryID:

What is natural primary key?

As its name suggests, natural primary key takes the natural format of the data and often has business meanings associated with it.Natural primary key is also known as intelligent primary key.

Values For The Primary Key Should Be Generated Automatically In Word

For example, primary key CustomerID in customers table is a natural primary key. It uses a string of 5 characters which is abbreviated from the customer's company name.

Natural primary key:

Why we should use an artificial primary key

Values For The Primary Key Should Be Generated Automatically Work

From the example showing above for CustomerID, the drawback of using natural primary key is obvious. First, the primary key is created by shortening the company name. It's rather cumbersome to come up with a unique short name for a customer. Second, it's not flexible and is subject to business requirement changes.

  • Integer values are independent of the business requirements which often change from time to time.

    This is actually the disadvantage of using a natural primary key. When an organization goes thru functional changes, so do the primary key values. Artificial primary key does not suffer from this problem because integer values don't have business meanings and are not associated business changes.

  • Using integer values as primary key can often improve query performance.

To optimize the Customers table, we can create a new integer type CustomerID column in customers table as artificial primary key and remove the previous varchar type CustomerID. We then renamed the old varchar type CustomerID column to CustomerAbbr (if we still want to keep this column) which is short for customer abbreviation. We also added unique index to CustomerAbbr column.

Artificial primary key:

Automatically

Eos way to generate keys from source code. Dis-advantages of using artificial primary key:

The only disadvantage I can think of is when we retrieve data from tables by using joins, we'll have tojoin more tables than we need. The extra joins come from the lack of natural key in the foreign key tables.

The following two sets of screenshots illustrate how extra joins can occur.

Table 1: Use extra join to get CustomerID

CustomerID below is integer data type and so it's artificial primary key. To retrieve order information and CustomerAbbr data, we need to join the two tables together.

select b.OrderID, a.CustomerAbbr, b.OrderDate, b.RequiredDate
from customers as a
inner join orders as b on a.CustomerID=b.CustomerID

Customers table:
Orders table:
Table 2: No join is used to get CustomerAbbr

Here natural key Customer abbreviation is used as CustomerID and because it's used as foreign key in orders table, when we retrieve order information and Customer abbreviation data, we don't need to join the two tables together.

select OrderID, CustomerID as CustomerAbbr, OrderDate, RequiredDate
from orders

The queries in Table 1 and Table 2 return exactly the same result but Table 1 used JOIN but Table 2 didn't.

Unique Constraint

Unique Constraint defines that values in a column must be unique. No duplicate values are allowed in the column. Unique Constraint enforces row integrity.

Unique Constraint is created on a column when you want to guarantee that data in this column must be unique. For example, a unique constraint is created on CategoryName column in categories table. This is achieved by creating a unique index on CategoryName column.

/malwarebytes-premium-license-key-generator.html. Considerations when creating unique constraint:

  • Unique constraint is automatically created when you define a column as primary key.

  • Unique constraint can be created on one or more columns.

  • When on multiple columns, the combination of data on these columns must be unique. For example, we created a unique index on OrderID and ProductIDcolumn in order_details table.

  • Unique constraint is created implicitly by defining a unique index on the column(s).

  • NULL value is allowed by unique constraint.

  • One table can have more than one unique constraint.

On next page, we will look into details of Creating foreign key relationships and considerations.


Other tutorials in this category

1. How to Design Relational Database
2. Enforce Data Integrity by Database Constraints
3. How to Enforce Data Type Constraint
4. How to Enforce Defualt Constraint and Nullability Constraint
5. Foreign Key Relationships and Considerations

The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows:

Which returns:

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign 0 to the column to generate sequence numbers, unless the NO_AUTO_VALUE_ON_ZERO SQL mode is enabled. For example:

If the column is declared NOT NULL, it is also possible to assign NULL to the column to generate sequence numbers. For example:

When you insert any other value into an AUTO_INCREMENT column, the column is set to that value and the sequence is reset so that the next automatically generated value follows sequentially from the largest column value. For example:

Updating an existing AUTO_INCREMENT column value also resets the AUTO_INCREMENT sequence.

You can retrieve the most recent automatically generated AUTO_INCREMENT value with the LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function. These functions are connection-specific, so their return values are not affected by another connection which is also performing inserts.

Use the smallest integer data type for the AUTO_INCREMENT column that is large enough to hold the maximum sequence value you will need. When the column reaches the upper limit of the data type, the next attempt to generate a sequence number fails. Use the UNSIGNED attribute if possible to allow a greater range. For example, if you use TINYINT, the maximum permissible sequence number is 127. For TINYINT UNSIGNED, the maximum is 255. See Section 11.1.2, “Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT” for the ranges of all the integer types.

For a multiple-row insert, LAST_INSERT_ID() and mysql_insert_id() actually return the AUTO_INCREMENT key from the first of the inserted rows. This enables multiple-row inserts to be reproduced correctly on other servers in a replication setup.

To start with an AUTO_INCREMENT value other than 1, set that value with CREATE TABLE or ALTER TABLE, like this:

For information about AUTO_INCREMENT usage specific to InnoDB, see Section 15.6.1.6, “AUTO_INCREMENT Handling in InnoDB”.

  • For MyISAM tables, you can specify AUTO_INCREMENT on a secondary column in a multiple-column index. In this case, the generated value for the AUTO_INCREMENT column is calculated as MAX(auto_increment_column) + 1 WHERE prefix=given-prefix. This is useful when you want to put data into ordered groups.

    Which returns:

    In this case (when the AUTO_INCREMENT column is part of a multiple-column index), AUTO_INCREMENT values are reused if you delete the row with the biggest AUTO_INCREMENT value in any group. This happens even for MyISAM tables, for which AUTO_INCREMENT values normally are not reused.

  • If the AUTO_INCREMENT column is part of multiple indexes, MySQL generates sequence values using the index that begins with the AUTO_INCREMENT column, if there is one. For example, if the animals table contained indexes PRIMARY KEY (grp, id) and INDEX (id), MySQL would ignore the PRIMARY KEY for generating sequence values. As a result, the table would contain a single sequence, not a sequence per grp value.

Pengertian Primary Key

More information about AUTO_INCREMENT is available here:

Primary Key Adalah

  • How to assign the AUTO_INCREMENT attribute to a column: Section 13.1.20, “CREATE TABLE Statement”, and Section 13.1.9, “ALTER TABLE Statement”.

  • How AUTO_INCREMENT behaves depending on the NO_AUTO_VALUE_ON_ZERO SQL mode: Section 5.1.11, “Server SQL Modes”.

  • How to use the LAST_INSERT_ID() function to find the row that contains the most recent AUTO_INCREMENT value: Section 12.15, “Information Functions”.

  • Setting the AUTO_INCREMENT value to be used: Section 5.1.8, “Server System Variables”.

  • AUTO_INCREMENT and replication: Section 17.5.1.1, “Replication and AUTO_INCREMENT”.

  • Server-system variables related to AUTO_INCREMENT (auto_increment_increment and auto_increment_offset) that can be used for replication: Section 5.1.8, “Server System Variables”.

Coments are closed
Scroll to top