ALTER TABLE expenses ADD COLUMN IF NOT EXISTS expense_name VARCHAR(255) NOT NULL DEFAULT '';

UPDATE expenses e
SET expense_name = first_item.item
FROM (
    SELECT DISTINCT ON (expense_id) expense_id, item
    FROM expense_items
    WHERE COALESCE(item, '') != ''
    ORDER BY expense_id, created_at ASC
) first_item
WHERE e.id = first_item.expense_id
  AND COALESCE(e.expense_name, '') = '';

CREATE INDEX IF NOT EXISTS idx_expenses_expense_name ON expenses(expense_name);
DROP INDEX IF EXISTS idx_expense_items_item;
ALTER TABLE expense_items DROP COLUMN IF EXISTS item;
