Mysql – How to find unused columns in MariaDB tables

mariadbmariadb-10.2mariadb-10.3MySQL

I have a lot of tables in my DB that have a number of columns which might not be getting used as they slowly lost their relevance with time, I need to find such columns and delete those from the tables, Is there a definitive way to check if a column is getting used or not?

MariaDB 10.3.8

Best Answer

If your table has columns that are defined to have NULL values, run this:

SELECT COUNT(given_column) FROM mytable;

This gives you the numbers of rows in mytable whose given_column is not NULL. If the result comes back as zero(0), that column is not populated with anything. You could drop that column with ALTER TABLE mytable DROP COLUMN given_column;

If your table has columns define as DEFAULT <some-value>, run this

SELECT COUNT(DISTINCT given_column) DistinctCount FROM mytable;

If this comes back as 1, you could most likely drop this column as well.

If the DistinctCount > 1 and you want to see that breakdown, run this

SELECT IFNULL(given_column,'Total Rows') ColumnsValues,COUNT(1) rowcount
FROM mytable GROUP BY given_column WITH ROLLUP;

These queries should give you a good idea which can be dropped.

CAVEAT : Please make sure your given_column is never referenced in your source code before dropping the column