SQL PHP HTML ASP JavaScript articles and free scripts to download
 
 

MySQL auto incremented field to generate unique ID for the record

We can get a unique auto generated number from MySQL by creating an auto incremented field. MySQL will generate a unique number by incrementing the last number of the table and will automatically add to the auto incremented field. This is the best way to generate a trouble ticket number for a help desk system. In a school if a new student joins then all details of the student we can feed to student table and while using the insert query, MySQL will add one auto generated unique number to this auto incremented field. We need not have to specify any thing in our query while adding the auto incremented field data. After successfully adding the record we can get this unique number by using mysql_insert_id(). Read the details on how to get this number by visiting the tutorial here. Now let us try how to create a such auto incremented field.

We have to make auto increment field integer ( obvious ) and also unique. The property set to auto increment. Here is the sql to create a student table with one auto increment field to assign one unique student ID.

CREATE TABLE `student` ( `student_id` INT( 3 ) NOT NULL AUTO_INCREMENT, `name` VARCHAR( 25 ) NOT NULL , `email` VARCHAR( 50 ) NOT NULL , UNIQUE ( `student_id` ) );
Related Tutorial
Get the auto increment number

Number of rows affected by a query


Now we will add one record to this table using one insert command.

INSERT INTO `student` ( `name` , `email` ) VALUES ( 'john', 'john@sitename.com' );

You will see automatically the student_id field will be added with 1 and for next record it will get the next incremented value 2.

This way we can generate auto increment id for each record in our table.

Read here on how to create one incremental auto generated record number in MSSQL table.

Discuss this tutorial at forum

List of SQL Tutorials


Further readings
MySQL Auto Increment field to generate unique record ID
How to start auto increment value from a predefined value ?
mysql_insert_id() to get the auto increment number of just inserted record
 
Scripts
PHP
JavaScript
HOME
SQL Tutorial List
SQL (Home)
SQL Commands
AVG
Alter Table
Between
Count
Copy Table
Create Table
Delete
Distinct
Group by
Having
Insert
Inner Join
IN
Left join
Limit
Like
MAX
MIN
Order By
OR AND
Rand
Replace
Rename Table
Select Query
Sum
Union
Update
Where
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.