Branchwell

AI Resource Pro / website / scripts / remove-duplicate-news.sql

1-- SQL script to identify and remove duplicate news stories
2-- Run this in your Supabase SQL editor
3
4-- Create a function to normalize URLs for comparison
5CREATE OR REPLACE FUNCTION normalize_url(url TEXT) RETURNS TEXT AS $$
6BEGIN
7 RETURN REGEXP_REPLACE(
8 REGEXP_REPLACE(
9 REGEXP_REPLACE(
10 LOWER(TRIM(url)),
11 '^https?://(www\.)?', ''
12 ),
13 '/+$', ''
14 ),
15 '\?.*$', ''
16 );
17END;
18$$ LANGUAGE plpgsql;
19
20-- First, let's identify duplicates
21-- We consider news duplicates if they have the same normalized URL or same title+source
22CREATE TEMP TABLE news_duplicates AS (
23 WITH news_with_normalized_url AS (
24 SELECT
25 id,
26 title,
27 url,
28 normalize_url(url) AS normalized_url,
29 content,
30 source,
31 article_date,
32 created_at
33 FROM
34 public.news
35 ),
36 duplicates AS (
37 SELECT
38 id,
39 title,
40 url,
41 normalized_url,
42 content,
43 source,
44 article_date,
45 created_at,
46 ROW_NUMBER() OVER (
47 PARTITION BY normalized_url
48 ORDER BY article_date DESC, created_at DESC
49 ) AS url_rank,
50 ROW_NUMBER() OVER (
51 PARTITION BY title, source
52 ORDER BY article_date DESC, created_at DESC
53 ) AS title_source_rank
54 FROM
55 news_with_normalized_url
56 )
57 SELECT
58 id,
59 title,
60 url,
61 normalized_url,
62 source,
63 article_date,
64 CASE
65 WHEN url_rank > 1 THEN 'Duplicate URL'
66 WHEN title_source_rank > 1 THEN 'Duplicate Title+Source'
67 ELSE NULL
68 END AS duplicate_reason
69 FROM
70 duplicates
71 WHERE
72 url_rank > 1 OR title_source_rank > 1
73);
74
75-- Preview duplicates (for information only)
76SELECT * FROM news_duplicates ORDER BY normalized_url, title;
77
78-- Count how many duplicates were found
79SELECT COUNT(*) AS duplicate_count FROM news_duplicates;
80
81-- Delete the duplicates
82-- This keeps one version of each duplicate (the newest one, based on article_date and created_at)
83DO $$
84DECLARE
85 deleted_count INTEGER;
86BEGIN
87 -- Delete duplicates that we've identified
88 DELETE FROM public.news
89 WHERE id IN (SELECT id FROM news_duplicates);
90
91 -- Also delete any news_categories entries for the deleted news items
92 DELETE FROM public.news_categories
93 WHERE news_id IN (SELECT id FROM news_duplicates);
94
95 GET DIAGNOSTICS deleted_count = ROW_COUNT;
96 RAISE NOTICE 'Deleted % duplicate news stories', deleted_count;
97END $$;
98
99-- Clean up
100DROP FUNCTION IF EXISTS normalize_url;
101DROP TABLE IF EXISTS news_duplicates;
102
103-- Update any statistics
104ANALYZE public.news;
105ANALYZE public.news_categories;
106
107-- Final count of remaining news stories
108SELECT COUNT(*) AS remaining_news_count FROM public.news;