If you need to optimize all your MySQL tables, it's not easy to do via SQL manually.
Instead, use the SQL below to create all the optimize SQLs that you need:
SET SESSION group_concat_max_len = 99999999;
SELECT GROUP_CONCAT(CONCAT('OPTIMIZE TABLE `', table_name, '`;') SEPARATOR '') AS O
FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_TYPE = 'BASE TABLE'
AND table_name!='dual'
AND TABLE_SCHEMA = 'XXX'