-- SQL to update the categories table by first updating counts and then renaming the column -- This script first ensures the counts are correct, then renames the column to instance_count -- Begin transaction BEGIN; -- First update the count to include tools and news UPDATE categories c SET tool_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 counts before rename SELECT c.id, c.name, c.tool_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 FROM categories c ORDER BY c.tool_count DESC LIMIT 10; -- Now rename the column to better reflect its purpose ALTER TABLE categories RENAME COLUMN tool_count TO instance_count; -- Verify the rename worked SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'categories' AND column_name = 'instance_count'; -- Show current table structure SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'categories' ORDER BY ordinal_position; -- Commit transaction COMMIT;