Search code examples
mysqlgoogle-bigquerysql-deletewith-statement

Using `With` then `Delete` in BigQuery


Using BigQuery I want to delete rows that has id in Common Table Expression or with

so this is my query :

WITH
  redundant AS (
  SELECT
    id,
    MAX(updated_at) AS updated_at,
    COUNT(*) AS counter
  FROM
    t1
  GROUP BY
    id
  HAVING
    counter >= 2)
DELETE
FROM
  t1
WHERE
  id IN (redundant.id)
  AND updated_at NOT IN (redundant.updated_at )

I expected the rows will be deleted but I got this error message :
Syntax error: Expected "(" or keyword SELECT but got keyword DELETE at [13:1]


Solution

  • Below is for BigQuery Standard SQL

    #standardSQL
    DELETE FROM `project.dataset.table` d
    WHERE EXISTS (
      WITH redundant AS (
        SELECT id,
          MAX(updated_at) AS updated_at,
          COUNT(*) AS counter
        FROM `project.dataset.table`
        GROUP BY id
        HAVING counter > 2
      )
      SELECT 1 FROM redundant 
      WHERE d.id = id AND d.updated_at != updated_at
    )