MySQL query to get table name with numerically highest number - mysql

I have a WordPress multisite database, which has a lot of orphan tables I need to get rid of. The names are structured like this. The number in the table name is the site ID.
wp_9892_wc_booking_relationships
wp_10001_wc_booking_relationships
wp_18992_wc_deposits_payment_plans
wp_20003_followup_coupons
wp_245633_followup_coupon_logs
I want to make a query to find out the highest site ID from the table names.
I've tried queries like this
SELECT table_name FROM information_schema.tables
WHERE table_type = 'base table'
AND table_name REGEXP '^wp_[0-9]+_[a-z0-9]+'
ORDER BY table_name DESC
LIMIT 1;
But that sorts the results in an unexpected way: I get
wp_9_woocommerce_log
When with LIMIT 10 I see there are names with higher numbers:
wp_99_woocommerce_log
wp_999_woocommerce_log
wp_999_wc_webhooks
wp_999_wc_download_log
wp_999_wcpv_per_product_shipping_rules
wp_999_wcpv_commissions
wp_9999_wcpv_per_product_shipping_rules
wp_9999_wcpv_commissions
wp_9998_wc_points_rewards_user_points_log
Is this something that's doable with a SQL query?

Consider the following data example.
CREATE TABLE test(
table_name varchar(255) );
insert into test values
('wp_99_woocommerce_log'),
('wp_999_woocommerce_log'),
('wp_999_wc_webhooks'),
('wp_999_wc_download_log'),
('wp_999_wcpv_per_product_shipping_rules'),
('wp_999_wcpv_commissions'),
('wp_9999_wcpv_per_product_shipping_rules'),
('wp_9999_wcpv_commissions'),
('wp_9998_wc_points_rewards_user_points_log');
Using,
SELECT table_name
FROM test
order by (substring_index(substring_index(table_name, 'wp_', -1), '_', 1) * 1 ) desc ;
Will give the following result:
table_name
wp_9999_wcpv_per_product_shipping_rules
wp_9999_wcpv_commissions
wp_9998_wc_points_rewards_user_points_log
wp_999_woocommerce_log
wp_999_wc_webhooks
wp_999_wc_download_log
wp_999_wcpv_per_product_shipping_rules
wp_999_wcpv_commissions
wp_99_woocommerce_log
https://dbfiddle.uk/590L44Xr
Using substring_index twice we get the number between wp_ and the second _.
* 1 is a shortcut to cast the varchar to int.
In your case it will be something like
SELECT table_name
FROM information_schema.tables
WHERE table_type = 'base table'
AND table_name REGEXP '^wp_[0-9]+_[a-z0-9]+'
ORDER BY (substring_index(substring_index(table_name, 'wp_', -1), '_', 1) * 1 ) DESC
LIMIT 1;

One way is to extryct the numbers and sort it
Example
CREATE TABLE table1
(`tb` varchar(34))
;
INSERT INTO table1
(`tb`)
VALUES
('wp_9892_wc_booking_relationships'),
('wp_10001_wc_booking_relationships'),
('wp_18992_wc_deposits_payment_plans'),
('wp_20003_followup_coupons'),
('wp_245633_followup_coupon_logs')
;
Records: 5 Duplicates: 0 Warnings: 0
SELECT tb FROM table1 ORDER BY REGEXP_SUBSTR(tb,"[0-9]+") + 0 DESC LIMIT 1
tb
wp_245633_followup_coupon_logs
fiddle
So your query will look like
SELECT table_name FROM information_schema.tables
WHERE table_type = 'base table'
AND table_name REGEXP '^wp_[0-9]+_[a-z0-9]+'
ORDER BY REGEXP_SUBSTR(table_name,"[0-9]+") + 0 DESC
LIMIT 1;

Related

select Query from a table and plus table name as a column

I am trying to make a select query where i select all the columns from a table and add the table name as another column.but i don't know how to proceed with this.
SELECT t.name , t.table_name FROM `glassfilms` as t WHERE `name` LIKE '%007%'
here t.table_name is not a column. I need the columns name and table_name
From my concern, it is not a good idea to get a table name with the select statement because you have to add your database name and tables name which has confidential data for your project.
By the way, I solved your problem with the below query.
SELECT t.name,
(select table_name from information_schema.tables where TABLE_SCHEMA = '{{your_database_name}}' and table_name = 'glassfilms') as tbl_name
FROM glassfilms t
WHERE t.name like "%007%";

How to get last column name from mysql table?

I want to retrieve the last column name from a mysql table.
For example the schema would look like this:
TABLE example {surname,firstname,birthdate}
In this example I want to get the column name "birthdate" from table "example".
How do I achieve this in MySQL?
Please try this:
SELECT
COLUMN_NAME,
ORDINAL_POSITION
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'YOUR_DATABASE_NAME'
AND TABLE_NAME ='YOUR_TABLE_NAME'
ORDER BY ORDINAL_POSITION DESC
LIMIT 1;
Information_schema.columns stores column specific information.
Also try this one, The Solution from command line mysql
Learn about Information Schema
mysql>USE information_schema;
mysql>SELECT COLUMN_NAME,ORDINAL_POSITION FROM COLUMNS WHERE TABLE_SCHEMA = '<--DATABASE_NAME-->' AND TABLE_NAME='<--TABLENAME-->' ORDER BY ORDINAL_POSITION desc limit 1

SELECT * FROM MULTIPLE+DYNAMIC table_name

A Case in point is getting data from tables which is generated every day with new name like below:
select table_name from INFORMATION_SCHEMA.TABLES where table_name like 'ifhcraw%';
ifhcraw_2016_03_31_24
ifhcraw_2016_04_01_8
ifhcraw_2016_04_02_14
ifhcraw_2016_04_03_20
ifhcraw_2016_04_05_8
ifhcraw_2016_04_06_14
As you can see, there is a name convention based on rule - "ifhcraw+year+month+day+hour". But the hour of generation is not known.
Is there any way to create some SQL script which can get all data from the tables "where table_name like 'ifhcraw%'"
You can use GROUP_CONCAT to combine all the table names in a single string.
SELECT #queries := GROUP_CONCAT(CONCAT('SELECT * FROM ', table_name) SEPARATOR ' UNION ')
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name LIKE 'ifhcraw%';
PREPARE stmt FROM #queries;
EXECUTE stmt;
The first query finds all the matching table names, and creates a query like SELECT * FROM <tablename>. Then it uses GROUP_CONCAT to connect them all with UNION, so the resulting query looks like:
SELECT * FROM table1
UNION
SELECT * FROM table2
UNION
SELECT * FROM table3
...
Note that by default GROUP_CONCAT is limited to returning 1024 characters. If you have lots of these tables, you'll need to increase group_concat_max_len to get everything.

Just started working with Magento and I wanted to get the number of fields in each table

I'm astounded by the number of tables in Magento Enterprise 1.13 (over 200). I'm trying to get a handle on the way things are organized and I think it would be helpful to know the number of columns in each of the tables. The following query will get me a breakdown of columns and their data_types for each table:
SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = `<database_name>`
ORDER BY TABLE_NAME;
But I would also like to know the number of columns in each table.
SELECT COUNT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '<database_name>'
AND TABLE_NAME IN (
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '<database_name>'
);
Unfortunately, the above query returns a count of the total number of columns in the database. I realize that my approach is too simplistic and a LOOP or a FOREACH statement is closer to the solution I'm looking for but I don't know how to make the leap to that point.
SELECT TABLE_NAME, COUNT(COLUMN_NAME) AS NoCOLUMNS
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '<database_name>'
AND TABLE_NAME IN (SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '<database_name>')
GROUP BY TABLE_NAME;
Basic GROUP BY DEMO

Find Table with maximum number of rows in a database in mysql

As the question title suggests, I want to find the table having maximum number of rows (entries) in a particular database. I have been able to extract the names of all the tables in a particular database using the query below.
SELECT TABLE_NAME
FROM information_schema.tables
WHERE TABLE_SCHEMA="Some_Database";
How do I proceed beyond this?? I have been trying to formulate a nested query for the above purpose but couldn't come up with something (I am not very comfortable with them). Please Help.
EDIT: As given in this link the table_rows field does not give an accurate result. That is why I need to do something like a MAX (Count(*)) for each table.
Try this one......
SELECT TABLE_NAME,MAX(TABLE_ROWS)
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "DB_Name";
OR
please try the following two queries for actual result.
query 1:
SELECT CONCAT('SELECT COUNT(*) as cnt FROM ', table_name, ' union all')
FROM information_schema.tables WHERE table_schema = 'your_db_name';
query 2:
select max(cnt) from (paste the result of first query and remove
last union all keyword) as tmptable;
What about this:
SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "Some_Database"
ORDER BY TABLE_ROWS DESC
LIMIT 1;
information_schema.tables has a column named table_rows, so:
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'Some_Database'
ORDER BY table_rows DESC
LIMIT 1;
We can obtain the table name having max number of rows in MySQL using the this query
SELECT
TABLE_NAME,MAX(TABLE_ROWS)
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'DB_Name'
GROUP BY TABLE_NAME ORDER BY MAX(TABLE_ROWS) DESC LIMIT 1;