-- SQL to properly update instance_count to reflect actual usage -- This assumes the column has already been renamed from tool_count to instance_count -- Begin transaction BEGIN; -- First, check if the column exists with new name DO $$ DECLARE column_exists BOOLEAN; BEGIN SELECT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'categories' AND column_name = 'instance_count' ) INTO column_exists; IF column_exists THEN RAISE NOTICE 'Using column instance_count'; ELSE RAISE NOTICE 'Column instance_count not found, using tool_count instead'; END IF; END $$; -- Update the instance_count in the categories table to reflect current usage UPDATE categories c SET -- Use the appropriate column name based on what exists in your database instance_count = ( -- Count tools with this category SELECT COUNT(*) FROM tools WHERE category_id = c.id ) + ( -- Count news with this category SELECT COUNT(*) FROM news WHERE category_id = c.id ); -- Show current counts for verification SELECT c.id, c.name, c.instance_count AS current_count, (SELECT COUNT(*) FROM tools WHERE category_id = c.id) AS tools_count, (SELECT COUNT(*) FROM news WHERE category_id = c.id) AS news_count, ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + (SELECT COUNT(*) FROM news WHERE category_id = c.id)) AS total_calculated FROM categories c ORDER BY c.instance_count DESC LIMIT 20; -- Check for any discrepancies SELECT c.id, c.name, c.instance_count AS stored_count, ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + (SELECT COUNT(*) FROM news WHERE category_id = c.id)) AS calculated_count, ABS(c.instance_count - ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + (SELECT COUNT(*) FROM news WHERE category_id = c.id))) AS difference FROM categories c WHERE c.instance_count != ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) + (SELECT COUNT(*) FROM news WHERE category_id = c.id)) ORDER BY difference DESC; -- Commit the transaction COMMIT;