資料操作語言(DML)陳述式

BigQuery 入門

Matt Forrest

Field CTO

BigQuery 中的資料操作概觀

  • INSERT:新增資料列。
  • UPDATE:修改列中的既有值。
  • DELETE:從資料表移除不需要的資料。
  • MERGE:將 INSERTUPDATEDELETE 合併成一個陳述式。
  • CREATE TABLE AS:由查詢結果建立新資料表。
BigQuery 入門

注意事項與效能

  • 能合併的 DML 盡量一起執行,不要逐一執行。
  • 執行 UPDATE 時必須使用 WHERE 條件。
  • 可考慮使用資料表分割與叢集。
1 https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language
BigQuery 入門

INSERT

  • 新增資料到資料表
-- Define the columns in the parentheses 
INSERT INTO customers (customer_id, name, email)

-- Each value is a row to be inserted
VALUES (1, "John Doe", "[email protected]"),
(2, "Jane Doe", "[email protected]"),
(3, "Alice Smith", "[email protected]");
BigQuery 入門

UPDATE

  • 依條件變更資料
UPDATE customers
-- Set one column for each SET statement
SET email = "[email protected]"
-- Make sure to include where otherwise all
-- rows will be updated
WHERE customer_id = 1;
  • UPDATE 可搭配子查詢或聯結
    UPDATE customers c
    SET c.email = e.email
    FROM emails e
    WHERE c.customer_id = 1;
    
BigQuery 入門

DELETE

  • DELETE 會「永久」刪除紀錄,且「無法還原」
DELETE FROM customers

-- Include WHERE to ensure only specific rows are deleted
WHERE customer_id = 3;
DELETE FROM customers c
JOIN emails e USING (customer_id)
WHERE email = '[email protected]'
BigQuery 入門

MERGE

  • 在單一作業中結合 INSERTUPDATEDELETE
-- Sets the customers table as the target
MERGE customers AS target

-- The source is set to new_customers USING new_customers AS source
-- Matching condition ON target.customer_id = source.customer_id
-- If the emails do not match, update the email WHEN MATCHED AND target.email != source.email THEN UPDATE SET email = source.email
-- If the match is not met, insert the record WHEN NOT MATCHED THEN INSERT (customer_id, name, email) VALUES (source.customer_id, source.name, source.email);
BigQuery 入門

CREATE TABLE

  • 由查詢建立新資料表
CREATE TABLE active_customers AS
SELECT customer_id, name, email 
FROM customers
WHERE last_active_date > DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY);
BigQuery 入門

一起來練習吧!

BigQuery 入門

Preparing Video For Download...