In Mysql, how to fill a column with incremental integers? - mysql

I have a database named "planning" in which a column named "planning_id" is badly formatted, indeed it's only filled with 0s.
I would like to fill it incrementally with proper IDs; like 1, 2, 3, 4 etc.
I have think about a sql formula like this one:
BEGIN
DECLARE i INT DEFAULT 1;
WHILE (i <= 68) DO
UPDATE planning set planning_id = i;
SET i = i+1;
END WHILE;
END;
But it creates an error (I translate from french to english):
Unrecognized keywords. Near DECLARE.
Any idea ?

If you don't mind the sorting of your columns you can DROP the planning_id and add it again now as Primary Key and with auto_increment like :
ALTER TABLE planning DROP COLUMN planning_id,
ADD COLUMN planning_id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (planning_id);
This way your planning_id will refresh their values in an incremental order (1, 2, 3, 4 and so on).
Check MySQL AUTO INCREMENT Field
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table.
Often this is the primary key field that we would like to be created automatically every time a new record is inserted

ALTER TABLE table_name AUTO_INCREMENT = start_value;
use auto increment which is the attribute to use when you want MySQL to assign a sequence of numbers automatically to a field (in essence, creating an autonumber field).

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

Customize primary key in MySQL

How to create customize primary key in MySQL?, example i have table and the table name is X, I have a table field as ID,Code,Name.
I am afraid if I have 1000 users and when they input together will
result in destruction
and i want to :
INSERT INTO `X` (`ID`,`Code`,`Name`) VALUES
('P3K','Alex'), // this primary key is "P3K-1"
('SOS','Force'), // this primary key is "SOS-1"
('P3K','Bash'), // this primary key is "P3K-2"
Right now, i using TRIGGER (BEFORE INSERT) for this, like this one:
SET NEW.`ID` = CONCAT(NEW.`Code`,'-',IFNULL(SUBSTRING_INDEX((
SELECT `x`.`Code` FROM `X` WHERE
X.`Code` = NEW.`Code` and
ORDER BY X.`Code` DESC
LIMIT 1 ),'-',-1),0) + 1))
I did not try this code, but my point is:
User insert
Before insert I checking LAST Primary
IF Null then i set 0, else i cut the symbol (-) and take the last part
I increments (using [+ 1])
Final, i concat CODE and New Number.
am i misguided? LOL, and if true, how to create like this one?
(I THINK) We can do it and maybe no one knows about this, how does AI in MySQL work so perfectly?
Answer from him (https://stackoverflow.com/users/1133682/mjh)
InnoDB is very dependent on PRIMARY KEY using Auto Incremment, if you do not use Auto Incremment then you will spend space. each line by adding at least 6-8 bytes just to make the "HIDDEN PRIMARY KEY", and the best use of innoDB is USE Auto Incremment and do not disturb that key, if you want to add UNIQUE KEY then you just have to CONCAT
Instead of having the hyphenated string as the primary key, you can store the code and number as separate fields, use them together as the primary key, and optionally have the hyphenated string as a generated column. This is how CREATE TABLE would look for such a table
CREATE TABLE X (
Code CHAR(3),
Number INT,
Name VARCHAR(20),
CodeNumber VARCHAR(8) AS (CONCAT(Code, '-', Number)),
PRIMARY KEY (Code, Number)
);
Then you BEFORE INSERT trigger becomes
SET NEW.Number = (1 + IFNULL((SELECT Number FROM X WHERE Code = NEW.Code
ORDER BY Number DESC LIMIT 1), 0))

MySQL AUTO_INCREMENT=535

What does AUTO_INCREMENT=535 actually mean or do? I have seen this used when creating tables as shown below, but never knew what it does or is used for.
Create Table:
CREATE TABLE `my_table` (
`entry_id` int(11) NOT NULL auto_increment,
`address` varchar(512) NOT NULL,
PRIMARY KEY(entry_id)
) ENGINE=InnoDB AUTO_INCREMENT=535 DEFAULT CHARSET=utf8
Auto increment field allow automatic indexing of the records in a table. Usually serving as a Unique Key
Any table with definition like AUTO_INCREMENT=535 would mean that next auto-generated key will start from the 535.
This usually happen when you take backup from existing database. But also can be used in some special cases to have higher value of starting index.
Tells when to start with auto_increment counting. For example if you want to reserve some number of ID for some dedicated purposes.
The AUTO_INCREMENT attribute can be used to generate a unique identity
You can use a pair of statements: DROP TABLE and CREATE TABLE to reset the auto-increment column. Like the TRUNCATE TABLE statement, those statements removes all the data and reset the auto-increment value to zero.
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. If the column is declared NOT NULL, it is also ** possible to assign NULL ** to the column to generate sequence numbers.
You can retrieve the most recent AUTO_INCREMENT value with the LAST_INSERT_ID()
To start with an AUTO_INCREMENT value other than 1, you can set that value with CREATE TABLE or ALTER TABLE, like this:
mysql> ALTER TABLE tbl AUTO_INCREMENT = 100;
The AUTO INCREMENT interval value is controlled by the MySQL Server variable auto_increment_increment and applies globally. To change this to a number different from the default of 1, use the following command in MySQL:
mysql> SET ##auto_increment_increment = [interval number];
where [interval number] is the interval value you want to use. So, if we want to set the interval to be 5, we would issue the following command:
mysql> SET ##auto_increment_increment = 5;
refrence:-
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

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 Auto-Inc Bug?

In my MySQL table I've created an ID column which I'm hoping to auto-increment in order for it to be the primary key.
I've created my table:
CREATE TABLE `test` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 50 ) NOT NULL ,
`date_modified` DATETIME NOT NULL ,
UNIQUE (
`name`
)
) TYPE = INNODB;
then Inserted my records:
INSERT INTO `test` ( `id` , `name` , `date_modified` )
VALUES (
NULL , 'TIM', '2011-11-16 12:36:30'
), (
NULL , 'FRED', '2011-11-16 12:36:30'
);
I'm expecting that my ID's for the above are 1 and 2 (respectively). And so far this is true.
However when I do something like this:
insert into test (name) values ('FRED')
on duplicate key update date_modified=now();
then insert a new record, I'm expecting it to be 3, however now I'm shown an ID of 4; skipping the place spot for 3.
Normally this wouldn't be an issue but I'm using millions of records which have thousands of updates every day.. and I don't really want to even have to think about running out of ID's simply because I'm skipping a ton of numbers..
Anyclue to why this is happening?
MySQL version: 5.1.44
Thank you
My guess is that the INSERT itself kicks off the code that generates the next ID number. When the duplicate key is detected, and ON DUPLICATE KEY UPDATE is executed, the ID number is abandoned. (No SQL dbms guarantees that automatic sequences will be without gaps, AFAIK.)
MySQL docs say
In general, you should try to avoid using an ON DUPLICATE KEY UPDATE
clause on tables with multiple unique indexes.
That page also says
If a table contains an AUTO_INCREMENT column and INSERT ... ON
DUPLICATE KEY UPDATE inserts or updates a row, the LAST_INSERT_ID()
function returns the AUTO_INCREMENT value.
which stops far short of describing the internal behavior I guessed at above.
Can't test here; will try later.
Is it possible to change your key to unsigned bigint - 18,446,744,073,709,551,615 is a lot of records - thus delaying the running out of ID's
Found this in mysql manual http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html
Use a large enough integer data type for the AUTO_INCREMENT column 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. For example,
if you use TINYINT, the maximum permissible sequence number is 127.
For TINYINT UNSIGNED, the maximum is 255.
More reading here http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id it could be inferred that the insert to a transactional table is a rollback so the manual says "LAST_INSERT_ID() is not restored to that before the transaction"
What about for a possible solution to use a table to generate the ID's and then insert into your main table as the PK using LAST_INSERT_ID();
From the manual:
Create a table to hold the sequence counter and initialize it:
mysql> CREATE TABLE sequence (id INT NOT NULL);
mysql> INSERT INTO sequence VALUES (0);
Use the table to generate sequence numbers like this:
mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
mysql> SELECT LAST_INSERT_ID();
The UPDATE statement increments the sequence counter and causes the next call to
LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that
value. The mysql_insert_id() C API function can also be used to get the value.
See Section 20.9.3.37, “mysql_insert_id()”.
It's really a bug how you can see here: http://bugs.mysql.com/bug.php?id=26316
But, apparently, they fixed it on 5.1.47 and it was declared as INNODB plugin problem.
A duplicate, but same problem, you can see here too: http://bugs.mysql.com/bug.php?id=53791 referenced to the first page mentioned here in this answer.