Branchwell

AI Resource Pro / website / scripts / update-column-and-rename.sql

1-- SQL to update the categories table by first updating counts and then renaming the column
2-- This script first ensures the counts are correct, then renames the column to instance_count
3
4-- Begin transaction
5BEGIN;
6
7-- First update the count to include tools and news
8UPDATE categories c
9SET tool_count = (
10 -- Count tools with this category
11 SELECT COUNT(*) FROM tools
12 WHERE category_id = c.id
13) + (
14 -- Count news with this category
15 SELECT COUNT(*) FROM news
16 WHERE category_id = c.id
17);
18
19-- Show counts before rename
20SELECT
21 c.id,
22 c.name,
23 c.tool_count,
24 (SELECT COUNT(*) FROM tools WHERE category_id = c.id) AS tools_count,
25 (SELECT COUNT(*) FROM news WHERE category_id = c.id) AS news_count
26FROM
27 categories c
28ORDER BY
29 c.tool_count DESC
30LIMIT 10;
31
32-- Now rename the column to better reflect its purpose
33ALTER TABLE categories
34RENAME COLUMN tool_count TO instance_count;
35
36-- Verify the rename worked
37SELECT column_name, data_type, is_nullable
38FROM information_schema.columns
39WHERE table_schema = 'public'
40AND table_name = 'categories'
41AND column_name = 'instance_count';
42
43-- Show current table structure
44SELECT column_name, data_type, is_nullable
45FROM information_schema.columns
46WHERE table_schema = 'public'
47AND table_name = 'categories'
48ORDER BY ordinal_position;
49
50-- Commit transaction
51COMMIT;