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 |
| 5 | BEGIN; |
| 6 | |
| 7 | -- First update the count to include tools and news |
| 8 | UPDATE categories c |
| 9 | SET 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 |
| 20 | SELECT |
| 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 |
| 26 | FROM |
| 27 | categories c |
| 28 | ORDER BY |
| 29 | c.tool_count DESC |
| 30 | LIMIT 10; |
| 31 | |
| 32 | -- Now rename the column to better reflect its purpose |
| 33 | ALTER TABLE categories |
| 34 | RENAME COLUMN tool_count TO instance_count; |
| 35 | |
| 36 | -- Verify the rename worked |
| 37 | SELECT column_name, data_type, is_nullable |
| 38 | FROM information_schema.columns |
| 39 | WHERE table_schema = 'public' |
| 40 | AND table_name = 'categories' |
| 41 | AND column_name = 'instance_count'; |
| 42 | |
| 43 | -- Show current table structure |
| 44 | SELECT column_name, data_type, is_nullable |
| 45 | FROM information_schema.columns |
| 46 | WHERE table_schema = 'public' |
| 47 | AND table_name = 'categories' |
| 48 | ORDER BY ordinal_position; |
| 49 | |
| 50 | -- Commit transaction |
| 51 | COMMIT; |