![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add a column to a MySQL table which is the result of concatenation of text and value from another auto increment column?
For this, you can use LAST_INSERT_ID(). Let us first create a table −
mysql> create table DemoTable ( UserId int(6) unsigned zerofill NOT NULL AUTO_INCREMENT, UserAutoIncrement char(100) default null, PRIMARY KEY(UserId) ); Query OK, 0 rows affected (0.72 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+--------+-------------------+ | UserId | UserAutoIncrement | +--------+-------------------+ | 000001 | NULL | +--------+-------------------+ 1 row in set (0.00 sec)
Following is the query to add a column to a MySQL table which is the result of concatenation −
mysql> update DemoTable set UserAutoIncrement=CONCAT('USER-', UserId) WHERE UserId = LAST_INSERT_ID(); Query OK, 1 row affected (0.20 sec) Rows matched: 1 Changed: 1 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
Output
+--------+-------------------+ | UserId | UserAutoIncrement | +--------+-------------------+ | 000001 | USER-000001 | +--------+-------------------+ 1 row in set (0.00 sec)
Advertisements