Add from the 5th value - mysql

The goal
Add from the 5th value.
The problem
There is a table on my database called markets. Within it, there are 5 values:
+----+------+
| Id | Name |
+----+------+
| 0 | NULL |
+----+------+
| 1 | A |
+----+------+
| 2 | B |
+----+------+
| 3 | C |
+----+------+
| 4 | D |
+----+------+
Id is a primary key and auto-incremented column and its start by zero (I added it manually to use as default). When I add some market to this table, seems that MySQL adds the market in question with 0 as Id — and I want to set the Id as 5 to continue the table's logic. So I ask: how can I add some value from the 5th Id?
What I've already tried
I already set the auto_increment value for 5, but without success. The query that I used is the following:
ALTER TABLE `markets` AUTO_INCREMENT = 5;
How do I know that the MySQL is attempting to add the market with its Id as 0?
My application is powered by C# that is throwing an exception:
Duplicate entry '0' for key 'PRIMARY'

On your INSERT statement, leave the auto_increment field out of the statement. This will leave MySQL to increment it and add it automatically.

how can I add some value from the 5th Id
Just try:;--
INSERT INTO markets(Name) VALUES('E');
ie, dont use the auto_increment field while inserting the data. MySQL is smart enough to do that for you ;)

Already there are four values are there in the table, So you can just insert next row. it will automatically take 5 as a next value.
When we are using auto_increment no need to specify that column in the insert command.
INSERT INTO markets(Name) VALUES('E');
In case if you want to alter the auto_increment value you can use the following statement
ALTER TABLE market AUTO_INCREMENT = 5;

Related

SELECT(MAX) not going past 10 - mysql with phpmyadmin

I'm creating a PHP script to insert rows into a database called orders based on a shopping cart that is stored in an associative array using a sessional array $_SESSION['cart']. The database looks something like this:
orders
----------+--------------+-------------+-------------+-------------+
Id | Username | Item1Id | Item2Id | Item3Id |
----------+--------------+-------------+-------------+-------------+
1 | a#aa.com | 8000001 | 8000002 | 800003 |
----------+--------------+-------------+-------------+-------------+
5 | a#aa.com | 7000001 | 6000002 | 700003 |
----------+--------------+-------------+-------------+-------------+
7 | b#bb.com | 8000001 | 8000002 | NULL |
----------+--------------+-------------+-------------+-------------+
10 | a#aa.com | 3000001 | 1000002 | 800009 |
----------+--------------+-------------+-------------+-------------+
Id column type is CHAR(20) as I may choose to use letters later on.
As part of inserting the row, I need to assign an Id (Primary Key) to the order row which will be set to 1 higher than the current highest Id number found.
The whole script works perfectly; query finds highest Id in the table and I increment that by 1 and assign it to a variable to use as part of the insert query. The only problem is that "SELECT MAX(Id) FROM orders" can't seem to find anything higher than 9. Is there a condition which prevents the SELECT MAX(Id) from identifying anything in double digits?
I've got it written like:
$highestID = mysqli_query($conn, "SELECT MAX(Id) FROM orders");
$orderID = $highestID +1;
I've emptied the database except for Id numbers1 and 2. Running the PHP script inserts new rows with Id numbers 3, 4, 5 except when it gets to 10, the script is unable to as it produces an error of having duplicate primary key of '10' (from $orderID's value). Even when manually entering a row into the database with Id of '25', $orderID still only returns '10' when I echo out its result.
I have not set any specific limits to the amount of rows that can be entered or anything like that.
Id is char(20) so order by Id using string sort. You could use cast or convert function to sort numbers.
Like:
select max(cast(Id as unsigned)) from orders
You really do not need to go through ALL that trouble for an auto-incremental PK. Here's how you can go about it.
Step 1 : In your phpmyadmin, edit your table, and check the A_I checkbox for your PK column.
Step 2 : While inserting from PHP, leave the field blank. It will automatically assign a value of the current max + 1 to your PK.
Eg,
$query = "Insert into mytable (id, name) values ('', 'Name1'), ('', 'Name2')";
Edit : You really cannot have a CHAR(20) PK and then expect the increment to work btw.

Change values in new autoincrement field added to table from 0 to a meaningful number

After adding an autoincrement field to a table to act as a primary key, all records contain a 0 value in this field, so it is not much use for its intended purpose.
New records will get a good value, but what about the 3000+ entries with 0? Is there a way to alter those?
TIA!
It depends on how you created the column. Can you post your code? And what engine are you using: MyISAM, InnoDB, or something else?
For example, I did a test with a table:
alter table test1 add column i int auto_increment primary key;
select i from test1;
+---+
| i |
+---+
| 1 |
| 2 |
| 3 |
+---+
So in normal circumstances you get the values populated for existing records.

Query to Re-index Primary Key of MySQL Database

I've got a table in MySQL that has a Primary Key Column.
Lets say:
ID | Value
1 | One
2 | Two
6 | Three
8 | Four
9 | Five
How do I get it to be:
ID | Value
1 | One
2 | Two
3 | Three
4 | Four
5 | Five
There are no other tables. Just the one.
I just want the ID to be in a proper series.
Any suggestion??
A Query perhaps.. :)
There is even a simple way to accomplish the result by writing this query
SET #newid=0;
UPDATE tablename SET primary_key_id=(#newid:=#newid+1) ORDER BY primary_key_id;
This query will reindex the primary key starts from 1
Seems to me you have two options.
1) create a new table and copy the existing data over.
2) add another autoincrement field to the existing table, then delete the original column.
ALTER TABLE tableName ADD NewIdn INT NOT NULL AUTO_INCREMENT KEY
I did this in phpmyadmin by unchecking the A_I box (Auto Increment setting), clicking save, and then checking it again, and clicking save again.

Mysql auto_increment proceed with lowest value

My problem is: I have a table with an auto_increment column. When I insert some values, all is right.
Insert first row : ID 1
Insert second row : ID 2
Now I want to insert a row at ID 10.
My problem is, that after this there are only rows inserted after ID 10 (which is the normal behaviour ).
But I want that the database first fills up ID 3-9 before making that.
Any suggestions?
EDIT:
To clarify: this is for an URL shortener I want to build for myself.
I convert the id to a word(a-zA-z0-9) for searching, and for saving in the database I convert it to a number which is the ID of the table.
The Problem is now:
I shorten the first link (without a name) -> ID is 1 and the automatically name is 1 converted to a-zA-Z0-9 which is a
Next the same happenes -> ID is 2 and the name is b, which is 2 converted.
Next interesting, somebody want to name the link test -> ID is 4597691 which is the converted test
Now if somebody adds another link with no name -> ID is 4597692 which would be tesu because the number is converted.
I want that new rows will be automatically inserted at the last gap that was made (here 3)
You could have another integer column for URL IDs.
Your process then might look like this:
If a default name is generated for a link, then you simply insert a new row, fill the URL ID column with the auto-increment value, then convert the result to the corresponding name.
If a custom name is specified for a URL, then, after inserting a row, the URL ID column would be filled with the number obtained from converting the chosen name to an integer.
And so on. When looking up for integer IDs, you would then use the URL ID column, not the table auto-increment column.
If I'm missing something, please let me know.
You could do 6 dummy inserts and delete/update them later as you need. The concept of the auto increment, by design, is meant to limit the application's or user's control over the number to ensure a unique value for every single record entered into the table.
ALTER TABLE MY_TABLE AUTO_INCREMENT = 3;
You would have to find first unused id, store it as user variable, use as id for insert.
SELECT #id := t1.id +1
FROM sometable t1 LEFT JOIN sometable t2
ON t2.id = t1.id +1 WHERE t2.id IS NULL LIMIT 1;
INSERT INTO sometable(id, col1, col2, ... ) VALUES(#id, 'aaa', 'bbb', ... );
You will have to run both queries for every insert if you still have gaps, its up to you to decide whether it is worth doing it.
not 100% sure what you're trying to achieve but something like this might work:
drop table if exists foo;
create table foo
(
id int unsigned not null auto_increment primary key,
row_id tinyint unsigned unique not null default 0
)
engine=innodb;
insert into foo (row_id) values (1),(2),(10),(3),(7),(5);
select * from foo order by row_id;
+----+--------+
| id | row_id |
+----+--------+
| 1 | 1 |
| 2 | 2 |
| 4 | 3 |
| 6 | 5 |
| 5 | 7 |
| 3 | 10 |
+----+--------+
6 rows in set (0.00 sec)

MYSQL: how to "reorder" a table

I have a table like the following,
| id | name | color |
------+--------+---------
| 1 | pear | green |
| 2 | apple | red |
| 3 | banana | yellow |
| 4 | grape | purple |
I'd like to reorder alphabetically using the "name" column and reset the id (autoincrement) with this new order to end up with the following
| id | name | color |
------+--------+---------
| 1 | apple | red |
| 2 | banana | yellow |
| 3 | grape | purple |
| 4 | pear | green |
QUESTION: how can I do this with MYSQL?
The cleanest way to reset the auto increment is to create another table.
MySQL provides commands such as CREATE TABLE LIKE and RENAME TABLE that are useful.
CREATE TABLE table2 LIKE table1;
INSERT INTO table2
SELECT * FROM table1 ORDER BY name;
DROP TABLE table1;
RENAME TABLE table2 TO table1;
Can I ask why you would want to do this?
If anyone modifies any of the name values or inserts new rows it will mess up your ordering scheme. Trying to store some meaning in the ordering of the PK that is already available elsewhere in the table (the name column) seems redundant and consequently a bad idea.
A much better solution is not to worry about the value of the ID column and just sort on the name column when you use the data in your app.
PS: Sorry for the non-answer type response. Normally I'd assume you had a good reason and just give an answer that directly addresses what you are trying to do, but I noticed from your other questions that you are still in the early learning stages about database design, so I wanted to help point you in the right direction instead of helping further your progress towards an ill-advised approach.
You can SELECT INTO a new table from the old table, ordering your select into as desired. Have an auto-increment ID in the new table. If needed, drop the old table and rename the new table.
Why not adding "ORDER BY name ASC" at the end of your query? My guess would be that you need the ID for some reason.
If you have a table with an autoincrement primary key (named 'id' for example), and the key is not being depended on by other tables, the way to go about this is this.
Remove the column id entirely.
alter table order by column_x, column_y;
Add the primary key column 'id' again, with autoincrement.
I did this a few times, with success and quite fast, using phpmyadmin.
Reordering a table that has a primary key as an index, is impossible. That's why u need to remove it first.
If u need to keep the 'id' column, but need to re-sort, based on other columns, u need to omit the primary key & index status of the id column & re-sort. Then you need to add a new column as primary key / index.
SELECT
RANK() Over (ORDER BY Name) As NewID
, Name
, Color
FROM Fruits
could save to a temp table then truncate then truncate the fruit table and insert, but it's probably a crappy solutions.