Can I find out the next auto_increment to be used? - mysql

Is it possible to find out what the next auto increment will be for my primary key without executing an INSERT INTO query? Some rows are deleted meaning that it's not as easy as just adding one to a SELECT MAX query on the PK. Many thanks.

If you really want to know next auto_increment value try SHOW TABLE STATUS returns next Auto_increment field, e.g.:
SHOW TABLE STATUS WHERE name = your_table_name;
or
SELECT Auto_increment
FROM information_schema.tables
WHERE table_schema = DATABASE() AND table_name = your_table_name

You can get the value by executing
SHOW TABLE STATUS WHERE Name = nameOfTableHere
and then retrieving the column 'Auto_Increment' from the result

Try the following:
SELECT Auto_increment
FROM information_schema.tables
WHERE table_name= 'tableName'
AND table_schema = DATABASE();

This is also possible:
(SELECT (SELECT your_primary_key FROM Your_Table ORDER BY your_primary_key DESC LIMIT 1)+1);

Related

how to get only name of columns in mysql table?

i saw this post MySQL query to get column names?
i try to use this code `table name` or DESCRIBE `table name` or SHOW COLUMNS FROM `table name`
but return me also a datatype and more in this mode
id int NO auto_increment
i want only a name id is possible have it ?? thanks
somtime is possible bypass qualitystandard ?? please
use the tables from information_schema to get the meta data of your table:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
For more information see https://docs.oracle.com/cd/E19078-01/mysql/mysql-refman-5.0/information-schema.html#columns-table
If you don't like the default output of the SHOW commands, you can get anything you want from the INFORMATION_SCHEMA tables (which is where the SHOW commands get their data too).
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?;

How to auto-increment table-name during create-table, if table exists with same name

I'm trying to auto-increment table-name while creating a new table.
Below one, is the generic way to do it.
CREATE TABLE table_name (column_name column_type);
How can we add an auto-increment to table name like: table_name1, table_name2, etc?
There is no "auto incrementing" functionality with table names, you should handle it yourself. You can, for example, count the tables in your database with specific names and in specific schema:
SELECT count(*) FROM information_schema.tables WHERE table_schema = 'YOUR_SCHEMA' AND table_name LIKE '%YOUR_TABLE_NAME%';
Increase the number you got in result and create a new table.
Thanks to #errata, I have solved this problem. If I have tables with names: table_name1, table_name2, table_name_100, table_name_120.
I wanted to add an increment to a new table. So in the first part, I fetched the max count of the alpha-numeric table name.
SELECT MAX(CAST(SUBSTR(TRIM(table_name),12) AS UNSIGNED)) FROM information_schema.tables WHERE table_schema = '${userSchema}' AND table_name LIKE '%table_name%';
It returns, for example, 120 in the above case.
Use this and increment with 1 to new table_name.

Retrieve MAX Primary Key values of all tables in a database at once

What I need to do is retrieve the maximum primary key of all tables in my database at once? That is, my result will be like if I executed the below 2 queries:
SHOW TABLES FROM DATABASE_NAME
SELECT MAX(PRIMARY_KEY) AS maxId FROM TABLE
That is
(first column = TableName , second column = MAX(PK) Of that table)
Pardon if I am doing something wrong. I just do not want to write 80 queries because my database has 80 tables.
If (and only if) your primary keys are AUTO INCREMENT variables you can do this:
SELECT TABLE_NAME, AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'mydb'
Please pay attention to the situation below when choosing the method of retrieving that info and what you are going to do with it:
AUTO_INCREMENT value is stored in memory, so after a server restart, AUTO_INCREMENT value is reset to:
SELECT MAX(ai_col) FROM table_name FOR UPDATE;
This can break things if the database has missing FKs and, for example, you delete some rows that refer to other tables. You would end up by reusing the same id.
Refer to: https://dev.mysql.com/doc/refman/5.7/en/innodb-auto-increment-handling.html#innodb-auto-increment-initialization
SELECT table_schema, table_name, column_name, data_type, extra
FROM `columns`
WHERE table_schema = 'mydb'
AND extra LIKE '%auto_increment%'
Optionally JOIN this with Alnitak's Answer.

How to get the next auto-increment id in mysql

How to get the next id in mysql to insert it in the table
INSERT INTO payments (date, item, method, payment_code)
VALUES (NOW(), '1 Month', 'paypal', CONCAT("sahf4d2fdd45", id))
You can use
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'table_name'
AND table_schema = DATABASE( ) ;
or if you do not wish to use information_schema you can use this
SHOW TABLE STATUS LIKE 'table_name'
You can get the next auto-increment value by doing:
SHOW TABLE STATUS FROM tablename LIKE Auto_increment
/*or*/
SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = 'tablename'
Note that you should not use this to alter the table, use an auto_increment column to do that automatically instead.
The problem is that last_insert_id() is retrospective and can thus be guaranteed within the current connection.
This baby is prospective and is therefore not unique per connection and cannot be relied upon.
Only in a single connection database would it work, but single connection databases today have a habit of becoming multiple connection databases tomorrow.
See: SHOW TABLE STATUS
This will return auto increment value for the MySQL database and I didn't check with other databases. Please note that if you are using any other database, the query syntax may be different.
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'your_table_name'
and table_schema = 'your_database_name';
SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'your_table_name'
and table_schema = database();
The top answer uses PHP MySQL_ for a solution, thought I would share an updated PHP MySQLi_ solution for achieving this. There is no error output in this exmaple!
$db = new mysqli('localhost', 'user', 'pass', 'database');
$sql = "SHOW TABLE STATUS LIKE 'table'";
$result=$db->query($sql);
$row = $result->fetch_assoc();
echo $row['Auto_increment'];
Kicks out the next Auto increment coming up in a table.
In PHP you can try this:
$query = mysql_query("SELECT MAX(id) FROM `your_table_name`");
$results = mysql_fetch_array($query);
$cur_auto_id = $results['MAX(id)'] + 1;
OR
$result = mysql_query("SHOW TABLE STATUS WHERE `Name` = 'your_table_name'");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
Use LAST_INSERT_ID() from your SQL query.
Or
You can also use mysql_insert_id() to get it using PHP.
Solution:
CREATE TRIGGER `IdTrigger` BEFORE INSERT ON `payments`
FOR EACH ROW
BEGIN
SELECT AUTO_INCREMENT Into #xId
FROM information_schema.tables
WHERE
Table_SCHEMA ="DataBaseName" AND
table_name = "payments";
SET NEW.`payment_code` = CONCAT("sahf4d2fdd45",#xId);
END;
"DataBaseName" is the name of our Data Base
Simple query would do
SHOW TABLE STATUS LIKE 'table_name'
For MySQL 8 use SHOW CREATE TABLE to retrieve the next autoincrement insert id:
SHOW CREATE TABLE mysql.time_zone
Result:
CREATE TABLE `time_zone` (
`Time_zone_id` int unsigned NOT NULL AUTO_INCREMENT,
`Use_leap_seconds` enum('Y','N') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'N',
PRIMARY KEY (`Time_zone_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1784 DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 ROW_FORMAT=DYNAMIC COMMENT='Time zones'
See the AUTO_INCREMENT=1784 at the last line of returned query.
Compare with the last value inserted:
select max(Time_zone_id) from mysql.time_zone
Result:
+-------------------+
| max(Time_zone_id) |
+-------------------+
| 1783 |
+-------------------+
Tested on MySQL v8.0.20.
SELECT id FROM `table` ORDER BY id DESC LIMIT 1
Although I doubt in its productiveness but it's 100% reliable
You have to connect to MySQL and select a database before you can do this
$table_name = "myTable";
$query = mysql_query("SHOW TABLE STATUS WHERE name='$table_name'");
$row = mysql_fetch_array($query);
$next_inc_value = $row["AUTO_INCREMENT"];
I suggest to rethink what you are doing. I never experienced one single use case where that special knowledge is required. The next id is a very special implementation detail and I wouldn't count on getting it is ACID safe.
Make one simple transaction which updates your inserted row with the last id:
BEGIN;
INSERT INTO payments (date, item, method)
VALUES (NOW(), '1 Month', 'paypal');
UPDATE payments SET payment_code = CONCAT("sahf4d2fdd45", LAST_INSERT_ID())
WHERE id = LAST_INSERT_ID();
COMMIT;
You can't use the ID while inserting, neither do you need it. MySQL does not even know the ID when you are inserting that record. You could just save "sahf4d2fdd45" in the payment_code table and use id and payment_code later on.
If you really need your payment_code to have the ID in it then UPDATE the row after the insert to add the ID.
What do you need the next incremental ID for?
MySQL only allows one auto-increment field per table and it must also be the primary key to guarantee uniqueness.
Note that when you get the next insert ID it may not be available when you use it since the value you have is only within the scope of that transaction. Therefore depending on the load on your database, that value may be already used by the time the next request comes in.
I would suggest that you review your design to ensure that you do not need to know which auto-increment value to assign next
use "mysql_insert_id()". mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.
Below are the example of use:
<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable VALUES('','value')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
I hope above example is useful.
If return no correct AUTO_INCREMENT, try it:
ANALYZE TABLE `my_table`;
SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE (TABLE_NAME = 'my_table');
This clear cache for table, in BD
using the answer of ravi404:
CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
RETURNS BIGINT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE Value BIGINT;
SELECT
AUTO_INCREMENT INTO Value
FROM
information_schema.tables
WHERE
table_name = TableName AND
table_schema = DATABASE();
RETURN Value;
END
using in your insert query, to create a SHA1 Hash. ex.:
INSERT INTO
document (Code, Title, Body)
VALUES (
sha1( getAutoincrementalNextval ('document') ),
'Title',
'Body'
);
Improvement of #ravi404, in case your autoincrement offset IS NOT 1 :
SELECT (`auto_increment`-1) + IFNULL(##auto_increment_offset,1)
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = your_table_name
AND table_schema = DATABASE( );
(auto_increment-1) : db engine seems to alwaus consider an offset of 1. So you need to ditch this assumption, then add the optional value of ##auto_increment_offset, or default to 1 : IFNULL(##auto_increment_offset,1)
For me it works, and looks simple:
$auto_inc_db = mysql_query("SELECT * FROM my_table_name ORDER BY id ASC ");
while($auto_inc_result = mysql_fetch_array($auto_inc_db))
{
$last_id = $auto_inc_result['id'];
}
$next_id = ($last_id+1);
echo $next_id;//this is the new id, if auto increment is on
SELECT AUTO_INCREMENT AS next_id FROM information_schema.tables WHERE table_name = 'table name' AND table_schema = 'database name of table name'
mysql_insert_id();
That's it :)

INSERT INTO othertbl SELECT * tbl

Current situation:
INSERT INTO othertbl
SELECT *
FROM tbl
WHERE id = '1'
So i want to copy a record from tbl to othertbl. Both tables have an autoincremented unique index. Now the new record should have a new index, rather then the value of the index of the originating record else copying results in a index not unique error.
A solution would be to not use the * but since these tables have quite some columns i really think it's getting ugly.
So,.. is there a better way to copy a record which results in a new record in othertbl which has a new autoincremented index without having to write out all columns in the query and using a NULL value for the index.
-hope it makes sense....-
Think you're gonna have to drop the * and specify the columns fella
If you're using SQL Server you could get a list of columns using
SELECT column_name+', ' from INFORMATION_SCHEMA.COLUMNS where table_name = 'tbl'
Building an insert statement using the result from the above should be easy.
You can dump the list of non-auto-increment columns for your table with this query, and then use it in the insert and select statements:
SELECT group_concat(column_name)
from INFORMATION_SCHEMA.COLUMNS
where table_schema = 'myschema'
and table_name = 'tbl'
and extra != 'auto_increment';
Try:
INSERT ...
SELECT *
FROM tbl
ON DUPLICATE KEY UPDATE `id`=NULL
http://dev.mysql.com/doc/refman/5.1/en/insert-select.html