KatInterview

Why Does This Hive INSERT...SELECT Fail or Load Bad Data?

SQL & DataModel answer
MediumModel answerSQL & Datahiveinsert-selectdynamic-partitions

Last updated

Diagnose a failing Hive INSERT...SELECT into a partitioned ACID ORC table and explain, in order, the fixes for syntax, alignment, casts, partitions, settings and format.

You are handed a Hive load job that does not work. Here are the tables and the statement.

-- Destination: partitioned, transactional ORC table
CREATE TABLE dw.user_events (
  user_id    BIGINT,
  event_type STRING,
  event_ts   TIMESTAMP,
  amount     DECIMAL(10,2)
)
PARTITIONED BY (dt STRING, region STRING)
STORED AS ORC
TBLPROPERTIES ('transactional'='true');

-- Source: raw CSV landing table
CREATE TABLE staging.raw_events (
  event_type STRING, user_id STRING, ts STRING,   -- e.g. '2024/05/01 13:45:00'
  amount STRING, `date` STRING, region STRING
)
ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
STORED AS TEXTFILE;

-- The load
INSERT INTO TABLE dw.user_events PARTITION (dt, region)
SELECT event_type, user_id, ts, amount, date, region
FROM staging.raw_events;

What to do

  1. Explain why the statement fails, or worse, appears to succeed while writing bad data.
  2. Walk through the problems in a sensible order and give a concrete fix for each. Cover syntax and reserved words, column count and position, data types and casts, partition columns and values, dynamic partition settings, file format and SerDe, and ACID requirements.
  3. Write the corrected statement.
  4. Describe how you would check the load before and after running it.

Be explicit about which problems raise an error and which silently produce NULL or misplaced values.

Hints

Hint 1

Hive matches SELECT columns to the target by position, not by name. Compare the SELECT list against DESCRIBE output one column at a time, remembering that dynamic partition columns go last, in PARTITION order.

Hint 2

Several failures are silent: a string that cannot be cast becomes NULL, and a NULL partition value goes into __HIVE_DEFAULT_PARTITION__. Look at the timestamp format and at what happens when 'click' is cast to BIGINT.

Hint 3

Separate compile-time errors (reserved word, strict dynamic partition mode, non-ACID transaction manager) from data-quality problems, and finish with checks such as NULL counts per cast, SHOW PARTITIONS and row-count reconciliation.