-- SQL script to identify and remove duplicate news stories -- Run this in your Supabase SQL editor -- Create a function to normalize URLs for comparison CREATE OR REPLACE FUNCTION normalize_url(url TEXT) RETURNS TEXT AS $$ BEGIN RETURN REGEXP_REPLACE( REGEXP_REPLACE( REGEXP_REPLACE( LOWER(TRIM(url)), '^https?://(www\.)?', '' ), '/+$', '' ), '\?.*$', '' ); END; $$ LANGUAGE plpgsql; -- First, let's identify duplicates -- We consider news duplicates if they have the same normalized URL or same title+source CREATE TEMP TABLE news_duplicates AS ( WITH news_with_normalized_url AS ( SELECT id, title, url, normalize_url(url) AS normalized_url, content, source, article_date, created_at FROM public.news ), duplicates AS ( SELECT id, title, url, normalized_url, content, source, article_date, created_at, ROW_NUMBER() OVER ( PARTITION BY normalized_url ORDER BY article_date DESC, created_at DESC ) AS url_rank, ROW_NUMBER() OVER ( PARTITION BY title, source ORDER BY article_date DESC, created_at DESC ) AS title_source_rank FROM news_with_normalized_url ) SELECT id, title, url, normalized_url, source, article_date, CASE WHEN url_rank > 1 THEN 'Duplicate URL' WHEN title_source_rank > 1 THEN 'Duplicate Title+Source' ELSE NULL END AS duplicate_reason FROM duplicates WHERE url_rank > 1 OR title_source_rank > 1 ); -- Preview duplicates (for information only) SELECT * FROM news_duplicates ORDER BY normalized_url, title; -- Count how many duplicates were found SELECT COUNT(*) AS duplicate_count FROM news_duplicates; -- Delete the duplicates -- This keeps one version of each duplicate (the newest one, based on article_date and created_at) DO $$ DECLARE deleted_count INTEGER; BEGIN -- Delete duplicates that we've identified DELETE FROM public.news WHERE id IN (SELECT id FROM news_duplicates); -- Also delete any news_categories entries for the deleted news items DELETE FROM public.news_categories WHERE news_id IN (SELECT id FROM news_duplicates); GET DIAGNOSTICS deleted_count = ROW_COUNT; RAISE NOTICE 'Deleted % duplicate news stories', deleted_count; END $$; -- Clean up DROP FUNCTION IF EXISTS normalize_url; DROP TABLE IF EXISTS news_duplicates; -- Update any statistics ANALYZE public.news; ANALYZE public.news_categories; -- Final count of remaining news stories SELECT COUNT(*) AS remaining_news_count FROM public.news;