-- SQL to update the tool_count field in the categories table -- Based on confirmed column names and with error handling -- First, check if blog_posts table has primary_category_id column DO $$ DECLARE blog_has_primary_category_id BOOLEAN; BEGIN -- Check if blog_posts.primary_category_id exists SELECT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'blog_posts' AND column_name = 'primary_category_id' ) INTO blog_has_primary_category_id; RAISE NOTICE 'blog_posts.primary_category_id exists: %', blog_has_primary_category_id; -- Update the tool_count based on what columns exist IF blog_has_primary_category_id THEN -- If blog_posts has primary_category_id, include blog posts in the count 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 ) + ( -- Count blog posts with this category SELECT COUNT(*) FROM blog_posts WHERE primary_category_id = c.id ); RAISE NOTICE 'Updated category counts including blog posts'; ELSE -- If blog_posts does not have primary_category_id, only count 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 ); RAISE NOTICE 'Updated category counts without blog posts (column not found)'; END IF; END $$; -- Output the results for verification 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, CASE WHEN EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'blog_posts' AND column_name = 'primary_category_id' ) THEN (SELECT COUNT(*) FROM blog_posts WHERE primary_category_id = c.id) ELSE 0 END AS blog_posts_count FROM categories c ORDER BY c.tool_count DESC;