Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

database

mysql

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.

like image 861
Fawad Ghafoor Avatar asked Mar 01 '13 13:03

Fawad Ghafoor


People also ask

How do I get all the max values in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).

How many maximum possible primary key we can create in a table?

A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).

Which command in SQL is used to find maximum value of all data present in table?

SQL MIN() and MAX() Functions The MAX() function returns the largest value of the selected column.

Which query can be used to extract the maximum value of the column?

To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.


1 Answers

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'
like image 155
Alnitak Avatar answered Nov 10 '22 04:11

Alnitak