Branchwell

AI Resource Pro / website / scripts / fix-instance-count.sql

1-- SQL to properly update instance_count values
2-- This script assumes the column has been renamed from tool_count to instance_count
3
4-- Begin transaction
5BEGIN;
6
7-- Update the instance_count in the categories table to reflect correct usage
8UPDATE categories c
9SET
10 instance_count = (
11 -- Count tools with this category
12 SELECT COUNT(*) FROM tools
13 WHERE category_id = c.id
14 ) + (
15 -- Count news with this category
16 SELECT COUNT(*) FROM news
17 WHERE category_id = c.id
18 );
19
20-- Show current counts for verification
21SELECT
22 c.id,
23 c.name,
24 c.instance_count AS current_count,
25 (SELECT COUNT(*) FROM tools WHERE category_id = c.id) AS tools_count,
26 (SELECT COUNT(*) FROM news WHERE category_id = c.id) AS news_count,
27 ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) +
28 (SELECT COUNT(*) FROM news WHERE category_id = c.id)) AS total_calculated
29FROM
30 categories c
31ORDER BY
32 c.instance_count DESC
33LIMIT 20;
34
35-- Check for any discrepancies
36SELECT
37 c.id,
38 c.name,
39 c.instance_count AS stored_count,
40 ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) +
41 (SELECT COUNT(*) FROM news WHERE category_id = c.id)) AS calculated_count,
42 ABS(c.instance_count - ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) +
43 (SELECT COUNT(*) FROM news WHERE category_id = c.id))) AS difference
44FROM
45 categories c
46WHERE
47 c.instance_count != ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) +
48 (SELECT COUNT(*) FROM news WHERE category_id = c.id))
49ORDER BY
50 difference DESC;
51
52-- Commit the transaction
53COMMIT;