Auto create unique ID based on id - mysql

Based on my question above, I have a MySQL table called qrc_creation. This table consists of columns like id (auto increment), creation_code, and creation_name. For example, if I want to insert a new creation_name, the ID will auto 1. But, I also want the creation_code to become qrc_00000001, where 1 comes from ID.
Thus, can I know what is the query to do this? Thank you in advance!

You have two options. If you want, the column to autopopulate during insert, you can use MySQL generated columns while defining table schema. However, you cannot use Auto Increment column with this method.
CREATE TABLE `table_1` (
`id` INT(10) ZEROFILL NOT NULL,
`creation_name` VARCHAR(45) NOT NULL,
`creation_code` VARCHAR(55) GENERATED ALWAYS AS (CONCAT(`name`, '_', `id`)),
PRIMARY KEY (`id`));
If you don't want that dedicated column in your table, you can easily get calculated field on your SQL query by using a simple concat function.
SELECT
`id`, `creation_name`, CONCAT(`name`, '_', `id`) AS `creation_code`
FROM
table_1;
Hope it helps.

first of all you need to show your code so that stackoverflow community respond. But still i got your problem and given below is the solution-
CREATE TABLE qrc_creation
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
creation_code AS 'qrc' + RIGHT('0000000' + CAST(ID AS VARCHAR(7)), 7) PERSISTED,
creation_name varchar(255),
);
Select * from qrc_creation;
INSERT INTO qrc_creation(creation_name)
VALUES ('Monsen');
Select * from qrc_creation;
Hope you like my answer.

Related

How to set custom auto_increment value with initial value in MySQL [duplicate]

How do I set the initial value for an "id" column in a MySQL table that start from 1001?
I want to do an insert "INSERT INTO users (name, email) VALUES ('{$name}', '{$email}')";
Without specifying the initial value for the id column.
Use this:
ALTER TABLE users AUTO_INCREMENT=1001;
or if you haven't already added an id column, also add it
ALTER TABLE users ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT,
ADD INDEX (id);
MySQL - Setup an auto-incrementing primary key that starts at 1001:
Step 1, create your table:
create table penguins(
my_id int(16) auto_increment,
skipper varchar(4000),
PRIMARY KEY (my_id)
)
Step 2, set the start number for auto increment primary key:
ALTER TABLE penguins AUTO_INCREMENT=1001;
Step 3, insert some rows:
insert into penguins (skipper) values("We need more power!");
insert into penguins (skipper) values("Time to fire up");
insert into penguins (skipper) values("kowalski's nuclear reactor.");
Step 4, interpret the output:
select * from penguins
prints:
'1001', 'We need more power!'
'1002', 'Time to fire up'
'1003', 'kowalski\'s nuclear reactor'
MySQL Workbench
If you want to avoid writing sql, you can also do it in MySQL Workbench by right clicking on the table, choose "Alter Table ..." in the menu.
When the table structure view opens, go to tab "Options" (on the lower bottom of the view), and set "Auto Increment" field to the value of the next autoincrement number.
Don't forget to hit "Apply" when you are done with all changes.
PhpMyAdmin:
If you are using phpMyAdmin, you can click on the table in the lefthand navigation, go to the tab "Operations" and under Table Options change the AUTO_INCREMENT value and click OK.
With CREATE TABLE statement
CREATE TABLE my_table (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
) AUTO_INCREMENT = 100;
or with ALTER TABLE statement
ALTER TABLE my_table AUTO_INCREMENT = 200;
First you need to add column for auto increment
alter table users add column id int(5) NOT NULL AUTO_INCREMENT FIRST
This query for add column at first.
Now you have to reset auto increment initial value. So use this query
alter table users AUTO_INCREMENT=1001
Now your table started with 1001
You could also set it in the create table statement.
`CREATE TABLE(...) AUTO_INCREMENT=1000`
Alternatively, If you are too lazy to write the SQL query. Then this solution is for you.
Open phpMyAdmin
Select desired Table
Click on Operations tab
Set your desired initial Value for AUTO_INCREMENT
Done..!
For this you have to set AUTO_INCREMENT value
ALTER TABLE tablename AUTO_INCREMENT = <INITIAL_VALUE>
Example
ALTER TABLE tablename AUTO_INCREMENT = 101
Also , in PHPMyAdmin , you can select table from left side(list of tables) then do this by going there.
Operations Tab->Table Options->AUTO_INCREMENT.
Now, Set your values and then press Go under the Table Options Box.
SET GLOBAL auto_increment_offset=1;
SET GLOBAL auto_increment_increment=5;
auto_increment_increment: interval between successive column values
auto_increment_offset: determines the starting point for the AUTO_INCREMENT column value.
The default value is 1.
read more here

AUTO_INCREMENT in mysql can be signed by default?

i understand,below column will be signed int by default.
id INT(6);
Can an auto increment column specified below be signed by default? Mysql starts the value from 1 for an auto increment column.
id INT(6) AUTO_INCREMENT PRIMARY KEY
Yes, you can create an auto increment primary key with a signed int. Try this:
CREATE TABLE mytable( id int(6) AUTO_INCREMENT PRIMARY KEY);
Then the following queries are both valid
INSERT INTO mytable values();
INSERT INTO mytable values(-10);
This will result in the table having a row with -10 and another with 1 as values. But you will run into problems if you try this:
ALTER TABLE mytable AUTO_INCREMENT=-10;
yes, you cannot have auto increment values that are negative numbers.
After a lot of searches... I looked for a solution with a TRIGGER called BEFORE INSERT ! I found this : https://stackoverflow.com/a/43441586/2282880
Here is my variant :
CREATE TRIGGER `invertID`
BEFORE INSERT ON `<table>`
FOR EACH ROW SET NEW.id=CONCAT("-", (
SELECT `auto_increment`
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = '<table>')
)
It worked for me fine.
It was the best way I found to sync in both directions two databases with same schema without same ID's in my tables.

knowing next value from auto increment field mysql java

I want to know the next value of auto increment field
I wanted to test this :
select max(contactid) from contact
and I add 1
but I realized that it can give me an error
for exemple
if I insert one record and I delete it
so if I insert after the field will increase by two
how can I achieve that ?
thank you
There are multiple solutions to this problem:
1. (Preferable) Stop trying to predict auto-increment values
This is the more typical case, and basically is using auto-increment as designed. This assumes that you don't actually need the auto-increment value before you insert. What you can do is:
DROP TABLE IF EXISTS t;
CREATE TABLE t (id INT UNSIGNED NOT NULL auto_increment, x INT NOT NULL, PRIMARY KEY(id));
INSERT INTO t (x) VALUES (100);
SELECT LAST_INSERT_ID();
The call to SELECT LAST_INSERT_ID() will return the ID that was just generated for your INSERT.
2. Set up an ID generation table specifically to generate IDs
You can create a table with just an auto-increment column, like so:
DROP TABLE IF EXISTS id_generator;
CREATE TABLE id_generator (id INT UNSIGNED NOT NULL auto_increment, PRIMARY KEY(id));
You can then generate a new, unique ID with:
INSERT INTO id_generator (id) VALUES (NULL);
SELECT LAST_INSERT_ID();
And use that ID to insert into the table you're actually working with. As long as all generated IDs come from this ID generation table, there will be no conflicts. However there is a cost to generating these IDs, and auto-increment is not very efficient at it.
3. Use an external ID generation scheme
This is more or less similar to solution 2, but doesn't use MySQL at all for the ID generation. You can use something like a UUID/GUID scheme which generates a string, or you could use something like Snowflake to generate integer IDs.
You should use LAST_INSERT_ID like this:
SELECT LAST_INSERT_ID()
It will return the last value of AUTO_INCREMENT ID field.
More details here: http://goo.gl/RkmR5
This will give you the next id value that will be inserted:
SELECT LAST_INSERT_ID() + 1;

MySQL: Generate Autokey but use same for multiple rows

I have a mysql table that stores a mapping from an ID to a set of values:
CREATE TABLE `mapping` (
`ID` bigint(20) unsigned NOT NULL,
`Value` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This table is a list of values and the ID of a row selects the set, this value belongs to.
So the column ID is unique per set, but not unique per row.
I insert data into the table using the following statement:
INSERT INTO `mapping`
SELECT 5, `value` FROM `set1`;
In this example I calculated and set the ID manually to 5.
It would be great if mysql could set this ID automatically. I know the autokey feature, but using it will not work, because all rows inserted with the same insert statement should have the same ID.
So each insert statement should generate a new ID and then use it for all inserted rows.
Is there a way to accomplish this?
I am not convinced to it (I'm not sure whether locking table is good idea, I think it's not), but this might help:
lock tables `mapping` as m write, m as m1 read;
insert into m
select (select max(id) + 1 from m1), `value` from `set1`;
ulock tables;
One option is to have an additional table with an autogenerated key on single rows. Insert (with or without an necessary or appropriate other data) into that table, thus generating the new ID, and then use the generated key to insert into the mapping table.
This moves you to a world where the non-unique id is a foreign key reference to a truly unique key. Much more in keeping with typical relational database thinking.

How to set initial value and auto increment in MySQL?

How do I set the initial value for an "id" column in a MySQL table that start from 1001?
I want to do an insert "INSERT INTO users (name, email) VALUES ('{$name}', '{$email}')";
Without specifying the initial value for the id column.
Use this:
ALTER TABLE users AUTO_INCREMENT=1001;
or if you haven't already added an id column, also add it
ALTER TABLE users ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT,
ADD INDEX (id);
MySQL - Setup an auto-incrementing primary key that starts at 1001:
Step 1, create your table:
create table penguins(
my_id int(16) auto_increment,
skipper varchar(4000),
PRIMARY KEY (my_id)
)
Step 2, set the start number for auto increment primary key:
ALTER TABLE penguins AUTO_INCREMENT=1001;
Step 3, insert some rows:
insert into penguins (skipper) values("We need more power!");
insert into penguins (skipper) values("Time to fire up");
insert into penguins (skipper) values("kowalski's nuclear reactor.");
Step 4, interpret the output:
select * from penguins
prints:
'1001', 'We need more power!'
'1002', 'Time to fire up'
'1003', 'kowalski\'s nuclear reactor'
MySQL Workbench
If you want to avoid writing sql, you can also do it in MySQL Workbench by right clicking on the table, choose "Alter Table ..." in the menu.
When the table structure view opens, go to tab "Options" (on the lower bottom of the view), and set "Auto Increment" field to the value of the next autoincrement number.
Don't forget to hit "Apply" when you are done with all changes.
PhpMyAdmin:
If you are using phpMyAdmin, you can click on the table in the lefthand navigation, go to the tab "Operations" and under Table Options change the AUTO_INCREMENT value and click OK.
With CREATE TABLE statement
CREATE TABLE my_table (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
) AUTO_INCREMENT = 100;
or with ALTER TABLE statement
ALTER TABLE my_table AUTO_INCREMENT = 200;
First you need to add column for auto increment
alter table users add column id int(5) NOT NULL AUTO_INCREMENT FIRST
This query for add column at first.
Now you have to reset auto increment initial value. So use this query
alter table users AUTO_INCREMENT=1001
Now your table started with 1001
You could also set it in the create table statement.
`CREATE TABLE(...) AUTO_INCREMENT=1000`
Alternatively, If you are too lazy to write the SQL query. Then this solution is for you.
Open phpMyAdmin
Select desired Table
Click on Operations tab
Set your desired initial Value for AUTO_INCREMENT
Done..!
For this you have to set AUTO_INCREMENT value
ALTER TABLE tablename AUTO_INCREMENT = <INITIAL_VALUE>
Example
ALTER TABLE tablename AUTO_INCREMENT = 101
Also , in PHPMyAdmin , you can select table from left side(list of tables) then do this by going there.
Operations Tab->Table Options->AUTO_INCREMENT.
Now, Set your values and then press Go under the Table Options Box.
SET GLOBAL auto_increment_offset=1;
SET GLOBAL auto_increment_increment=5;
auto_increment_increment: interval between successive column values
auto_increment_offset: determines the starting point for the AUTO_INCREMENT column value.
The default value is 1.
read more here