id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),
ten VARCHAR(30) NOT NULL,
ngaysinh DATE NOT NULL,
quequan VARCHAR(30) NOT NULL
);
Query OK, 0 rows affected (0.02 sec)
mysql> INSERT INTO NHANVIEN (id,ten,ngaysinh,quequan) VALUES
(NULL,'Huy','1999-06-23','Hanoi'),
INSERT INTO NHANVIEN (id,ten,ngaysinh,quequan) VALUES
(NULL,'Hung','1990-05-21','Haiduong'),
INSERT INTO NHANVIEN (id,ten,ngaysinh,quequan) VALUES
(NULL,'Huyen','1995-02-12','Hanoi');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM NHANVIEN ORDER BY id; +----+-------------+------------+------------+ | id | ten | ngaysinh | quequan | +----+-------------+------------+------------+ | 1 | Huy | 1999-06-23 | Hanoi | | 2 | Hung | 1990-05-21 | Haiduong | | 3 | Huyen | 1995-02-12 | Hanoi | +----+-------------+------------+------------+ 3 rows in set (0.00 sec)
There will be cases where you have to delete multiple records from a table and want to reorder the records. To do this you just need to use a simple tip, but be careful and check if your table is joining another table.
If you have decided to renumber an AUTO_INCREMENT column, you do so by deleting this column from the table, then adding it again. The following example illustrates how to renumber id values in the NHANVIEN table by using this technique.
The following example illustrates how to re-number id values in the NHANVIEN table using this technique:
mysql> ALTER TABLE NHANVIEN DROP id;
mysql> ALTER TABLE NHANVIEN
ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (id);
By default, MySQL will start SEQUENCE from 1, but you can also specify any other number at the time of creating the table.
The following example will start SEQUENCE from 100:
mysql> CREATE TABLE NHANVIEN (
id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100,
PRIMARY KEY (id),
ten VARCHAR(30) NOT NULL,
ngaysinh DATE NOT NULL,
quequan VARCHAR(30) NOT NULL
);
Alternatively, you can create the table and then set the initialization value for SEQUENCE with the ALTER TABLE command.
mysql> ALTER TABLE t AUTO_INCREMENT = 100;
Previous article: Subquery - SUBQUERY in SQL