Make my own incrementing mysql id without auto increment - mysql

How can I duplicate the function of an auto incrementing Id field without making the field itself auto incrementing? I suppose on my INSERT statement, I would need to somehow grab the last id created, and add +1 on the new entry. But I don't know how. Any help is appreciated.
EDIT: I ended up taking ypercube's advice and keeping the id field as autoincrementing and making my searchstring unique. Thanks!

You'd need to select the highest current ID in one query, then use that when inserting using a second query.
To get round the race conditions, you could create a table lock (nasty) or use transactions (better, but not ideal)

Related

How to adjust Auto Increment?

Good day to all. So I have lots of data in excel that i needed to insert in the db but I didn't notice I inserted a duplicate value (cause hr didn't sort it out).
So anyways, here is the deal
[id][name]
[1][name1]
[2][name2] // I want to delete this row
[3][name3]
[4][name4]
I want to delete row 2. I want to make the id auto adjust like,
[id][name]
[1][name1]
[2][name3] // The id will adjust
[3][name4]
Is this possible to achieve? Or if not is there a work around I can do?
PS: My data is already at 50k and I want to delete the rows in the 7k
In general, you should avoid manually intervening with an auto increment column. This means, among other things, that when you insert data into your table, you should omit the auto increment column, thereby allowing MySQL to automatically assign a value to it.
Perhaps the best solution here would be to have a third timestamp column which records when each record were inserted. Then, you may use ROW_NUMBER to generate the sequence you want, e.g.
SELECT
ROW_NUMBER() OVER (ORDER BY ts_column) id,
name
FROM yourTable
ORDER BY
id;
You might be able to also order ROW_NUMBER using the id column, and get the same result. If you are using a version of MySQL earlier than 8+, then you may simulate ROW_NUMBER using user variables.

MySql Issue: Auto Incremented ID's are not working properly, ID's are getting misplaced

I have created one DB in Mysql;It is uploaded on server. But today i noticed one strange thing, that ID's from the same table are getting lost. I have set Auto_Increment for ID. So it will only Increment the ID's but now I can see that some of the records are being lost. In the place of that some other ID is there. For example: Order ID 1 should be in the first place but today some other ID lets call Order 5 was in place of ID 1. Well we can sort ID's anytime. But i didn't find Order ID 1 and Some other ID's like that anywhere.
I need help. What is wrong? any help will be fine.
You lost all the data of row or only lost the order of the ID field?
Example:
If only the order, in case of using Auto_Increment, any record that had removed (or delete), it's order will not auto create again. Are you only insert data from the table, or have some delete query too ?

Force auto increment to follow another suequence

I have a table containing invoices. Those invoices are inserted via a VB.NET program I have written. Using auto increment my invoices get their invoiceid.
I now have invoiceid's like
1055
1056
1057
...
I also have another database (from another bought software program) that generate invoices, and I use a cron job to import certain invoices into my main table, but they get the prefix 99. Those invoices do not have the same sequence. I do not use auto increment to number them, but I use the original ID (from the other database) + the 99 prefix. In my main table I have invoiceid's from the secondary database like this:
992013055
992013064
992013078
So, this makes that my main table looks like this:
992013055
1055
1056
992013064
1057
992013078
...
Now the thing is, I want the auto increment only follow the 'main' sequence. So in the example above, the next auto increment value should be 1058, but using normal auto increment it would be 992013079.
Is there a way to force this? Or should I "reset" the auto increment value after the cron job, something like "ALTER TABLE invoices AUTO_INCREMENT=bla +1". I guess 'bla' should be a new select to get the highest value in the column that does not start with 99, not sure how to do this. Off course when I get to invoice 9900, this would be a problem.
Thank you
i would create another column or table that links in this external id and do not try to layer them in to your id column like you are attempting.
for instance add a column called external_id and simply populate that one with the 99 values - and keep your autoincrement value chugging along properly with your regular numbers.
No you can't. Even if you tried the ALTER TABLE invoices AUTO_INCREMENT=bla +1 command, it would not work, as MySQL makes sure the value of AUTO_INCREMENT is higher than the highest value in the column.
Basically you shouldn't use the value in your autoincremented column for anything else than primary key, so that you don't really need to care about what these values are and what sequence they follow. After all nobody sees them and they're only used by computer.
If however you used these values for something that's visible for the end user... well your users will just need to adjust to the fact, that their invoces start from 99 now. Either that, or you need to renumber them, which is hell of a work and likely to introduce errors to your data.

Auto Increment Manually

There is a table with an int field - field_1.
I want to insert a new row.
The field_1 value will be Maximum value from all the entries plus one.
I've tried:
INSERT INTO table (field names, `field_1`)
VALUES (values, '(SELECT MAX(field_1) FROM table)');
I get '0' in the field_1.
I know I can do it in separate queries.
Is there a way to perform this action with one query? I mean one call from php.
I have an auto-increment field 'id' and I want to add 'position' field. I want to be able to make changes in position but the new item will always have highest position
Whatever it is that you are trying to do, it will not work, because it is not guaranteed to be atomic. So two instances of this query executing in parallel are guaranteed to mess each other up at some random point in time, resulting in skipped numbers and duplicate numbers.
The reason why databases offer auto-increment is precisely so as to solve this problem, by guaranteeing atomicity in the generation of these incremented values.
(Finally, 'Auto Increment Manually' is an oxymoron. It is either going to be 'Auto Increment', or it is going to be 'Manual Increment'. Just being a smart ass here.)
EDIT (after OP's edit)
One inefficient way to solve your problem would be to leave the Position field zero or NULL, and then execute UPDATE table SET Position = Id WHERE Position IS NULL. (Assuming Id is the autonumber field in your table.)
An efficient but cumbersome way would be to leave the Position field NULL when you have not modified it, and give it a value only when you decide to modify it. Then, every time you want to read the Position field, use a CASE statement: if the Position field is NULL, then use the value of Id; otherwise, use the value of Position.
EDIT2 (after considering OP's explanation in the comments)
If you only have 30 rows I do not see why you are even trying to keep the order right on the database. Just load all rows in an array, programmatically assign incrementing values to any Position fields that are found to be NULL, and when the order of the rows in your array changes, just fix the Position values and update all 30 rows in the database.
Try this:
INSERT INTO table (some_random_field, field_to_increment)
SELECT 'some_random_value', IF(MAX(field_to_increment) IS NULL, 1, MAX(field_to_increment) + 1)
FROM table;
Or this:
INSERT `table`
SET
some_random_field = 'some_random_value',
field_to_increment = (SELECT IF(MAX(field_to_increment) IS NULL, 1, MAX(field_to_increment) + 1) FROM table t);
P.S. I know it's 4 years late but I was looking for the same answer. :)
ALTER TABLE table_name AUTO_INCREMENT = 1 allows the database to reset the AUTO_INCREMENT to:
MAX(auto_increment_column)+1
It does not reset it to 1.
This prevents any duplication of AUTO_INCREMENT values. Also, since
AUTO_INCREMENT values are either primary/unique, duplication would
never happen anyway. The method to do this is available for a reason.
It will not alter any database records; simply the internal counter so
that it points to the max value available. As stated earlier by
someone, don't try to outsmart the database... just let it handle it.
It handles the resetting of AUTO_INCREMENT very well. See gotphp

mysql prevent insert row auto sorting

I use Codeigniter to perform insert to mysql (not sure if relevant), I have table column and some data like this after I insert:
[invoice_id][product_id][unit_cost][quantity]
[42][1][50][2]
[42][2][100][3]
[42][5][45][1]
The problem is mysql auto sort it by invoice_id first then product_id like the above.
Before I insert them, my invoice item-list position was :
[42][5][45][1]
[42][1][50][2]
[42][2][100][3]
I do not want any of this auto-sort because when I retrieve them, they went like the list in database not as in the invoice. I dont think I can use sort for a particular column because they are all random in the first place.
I can only start thinking to add another column [position] contain number just for the sake of sorting it later, or is there a better way without it?
Thanks in advance for any reply.
You are not guaranteed the order of MySql resultsets unless you specify an ORDER BY clause. The only way to do it if you cannot sort with the parameters you already have would be to add another column to the table. Typically this would be an autoincrement integer field. You would then be able to order by id, and return the rows in the order they were entered.