AlanJ :
I'm a beginner in SQL and I've been given this command which returns the size of all tables in a given database.
SELECT
table_schema AS 'Database',
table_name AS 'Table',
ROUND(((data_length + index_length) / 1024 / 1024), 2) 'Size (MB)'
FROM
information_schema.TABLES
WHERE
table_schema = DATABASE-NAME
ORDER BY (data_length + index_length) DESC;
However, I'm trying to modify it so that the size of the largest and smallest tables in MB are returned.
In my last attempt to get the largest size I have tried this:
SELECT
table_schema AS 'Database', table_name AS 'Table', MAX(Size)
FROM
(SELECT
(ROUND(((data_length + index_length) / 1024 / 1024), 2)) AS Size
FROM
information_schema.TABLES) AS subquery
WHERE
table_schema = DATABASE-NAME;
But I got an error (error code 1054) saying that 'table_schema' in 'field list' does not exist.
I know how to use aggregate functions to get the min and max values from a regular column, but I don't see how to do it with an alias column.
Sebastian Brosch :
You can use the following:
SELECT tInfo.table_schema, tInfo.table_name, ROUND(((tInfo.data_length + tInfo.index_length) / 1024 / 1024), 2) AS `Size (MB)`
FROM information_schema.TABLES tInfo INNER JOIN (
SELECT
table_schema,
MAX(data_length + index_length) AS `max_size`,
MIN(data_length + index_length) AS `min_size`
FROM information_schema.TABLES
GROUP BY table_schema
) tSizes ON tInfo.table_schema = tSizes.table_schema AND (tInfo.data_length + tInfo.index_length) IN (tSizes.`max_size`, tSizes.`min_size`)
WHERE tInfo.table_schema LIKE 'DATABASE-NAME'