Why Does This Hive INSERT...SELECT Fail or Load Bad Data?
SQL & DataModel answerLast 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
- Explain why the statement fails, or worse, appears to succeed while writing bad data.
- 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.
- Write the corrected statement.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Hive INSERT problems fall into two groups, and I check both in a fixed order:
- Loud failures at compile or run time:
ParseException,SemanticException, ACID or transaction-manager errors, strict-mode complaints. - Silent failures that load wrong data: swapped columns, casts that return
NULL, bad partition values. These are more dangerous because the job reports success.
Diagnosis, in order
1. Reserved words and syntax. date is reserved, so the parser fails with cannot recognize input near 'date'. Quote it as `date`. Other risky names are timestamp, user, order, interval and function. Also check for trailing commas and a missing TABLE keyword.
2. Column count and position. Mapping is positional. The order must be: non-partition columns in DDL order, then dynamic partition columns in the order given in PARTITION (...). Static partition values are not selected. Here event_type and user_id are swapped, so 'click' cast to BIGINT becomes NULL with no error. A count mismatch gives SemanticException ... column number/types are different. Compare against DESCRIBE dw.user_events, or on newer versions use an explicit column list.
3. Types and casts.
tslooks like2024/05/01 13:45:00, butCAST(... AS TIMESTAMP)accepts onlyyyyy-MM-dd HH:mm:ss[.fff]. Every row would beNULL. Parse it explicitly withunix_timestamp(ts, 'yyyy/MM/dd HH:mm:ss')andfrom_unixtime.amountshould be cast toDECIMAL(10,2). Strip currency symbols and thousands separators first. Values exceeding the precision becomeNULL.user_idmust be cast toBIGINT. Blank strings becomeNULL, so decide whether to drop or keep such rows.- In text sources,
\Nmeans NULL but an empty string does not.
4. Partition columns. The source column is date, but the partition is dt. Derive dt explicitly in a fixed format so you do not create stray partitions like dt=05/01/2024. A NULL partition value lands in __HIVE_DEFAULT_PARTITION__, which almost always signals a parsing bug upstream.
5. Dynamic partition settings. With every partition column dynamic, strict mode raises requires at least one static partition column. Fix it with:
SET hive.exec.dynamic.partition = true;
SET hive.exec.dynamic.partition.mode = nonstrict;
SET hive.exec.max.dynamic.partitions = 5000; -- default 1000
SET hive.exec.max.dynamic.partitions.pernode = 1000; -- default 100
A better production option is to make the date static, such as PARTITION (dt='2024-05-01', region), and drop dt from the SELECT. That bounds how many partitions one run can touch.
6. File format and SerDe. INSERT ... SELECT rewrites data, so TEXTFILE to ORC is fine. LOAD DATA only moves files, so loading CSV into an ORC table appears to work and then fails on read. On the source side, the delimiter must match the files; quoted fields with embedded commas need OpenCSVSerde (which reads everything as STRING), and header rows need skip.header.line.count.
7. ACID requirements. A transactional=true table needs ORC (and before Hive 3, bucketing) plus:
SET hive.support.concurrency = true;
SET hive.txn.manager = org.apache.hadoop.hive.ql.lockmgr.DbTxnManager;
Without these you get an error saying the command is not allowed on an ACID table with a non-ACID transaction manager. If you never update or delete, a plain external ORC table avoids this overhead.
8. Re-run semantics. INSERT INTO appends, so a retry duplicates rows. INSERT OVERWRITE replaces only the partitions it writes, which makes daily loads idempotent.
Corrected statement
SET hive.exec.dynamic.partition = true;
SET hive.exec.dynamic.partition.mode = nonstrict;
SET hive.support.concurrency = true;
SET hive.txn.manager = org.apache.hadoop.hive.ql.lockmgr.DbTxnManager;
INSERT INTO TABLE dw.user_events PARTITION (dt, region)
SELECT
CAST(user_id AS BIGINT) AS user_id,
event_type,
CAST(from_unixtime(unix_timestamp(ts, 'yyyy/MM/dd HH:mm:ss')) AS TIMESTAMP) AS event_ts,
CAST(regexp_replace(amount, '[^0-9.\\-]', '') AS DECIMAL(10,2)) AS amount,
date_format(to_date(`date`), 'yyyy-MM-dd') AS dt,
region
FROM staging.raw_events
WHERE user_id IS NOT NULL AND user_id <> '';
Validation
- Run the SELECT alone with
LIMIT 20and inspect it. - Count rows where a cast returned
NULLalthough the source value was non-null, per column. - After loading, run
SHOW PARTITIONS dw.user_eventsand look for__HIVE_DEFAULT_PARTITION__or oddly formatted values. - Reconcile source and target row counts, accounting for deliberately filtered rows.
Optional automation
A small pre-flight script can take the target column list, the partition list and the SELECT output schema, then flag reserved names, count mismatches, name or type mismatches by position, and partition columns not at the end. Complexity is linear in the number of columns.
Trade-offs and common mistakes
- Relying on name matching: Hive does not do it, so swaps load silently.
- Trusting "job succeeded" without counting NULLs per column.
- Setting nonstrict mode and raising partition limits globally, which hides a bad
dtexpression that creates thousands of partitions. Prefer static partitions when the batch date is known. - Using
INSERT INTOin a retryable job and creating duplicates. - Using
LOAD DATAto convert formats. - Forgetting that ACID settings are session-level and must be present in the job's scripts, not just in an interactive shell.