My first fix? Filter the data before it hits the window function: WITH clean_data AS (SELECT * FROM orders LEFT JOIN customers ON orders.customer_id = customers.id WHERE customers.id IS NOT NULL -- ...