Rana Maninder Singh
Lesson 4 of 12Distributed AI Engineering

Hive & Distributed SQL

Lesson opener

In one line: Use Apache Hive to put tables, partitions and SQL over files in distributed storage, write HiveQL that filters, joins and aggregates safely, validate every result, and know when Spark SQL or a managed warehouse is the better engine for a new build.

Why it matters: Hive made distributed data usable by people who know SQL, and its table and partition model (and its metastore) underpins many platforms, including Spark and lakehouse tools. A large share of enterprise reporting still runs on HiveQL. Writing it well means understanding what a query will read: a filter on the wrong column turns a seconds-long query into a full scan of years of data, and a join that silently drops rows produces a plausible but wrong number.

Before this lesson: Warehouses, Lakes & Lakehouse covered layers and formats; Hadoop Core Commands & Data Movement covered landing files. You also need SQL basics and the pipeline vocabulary from What Data Engineers Do, the Python used in the worked example from Python Advanced and the model context from ML Fundamentals. Hive is treated here as foundational and often legacy; for managed Spark see Databricks & Spark.

Northline Financial Services (illustrative) stores card transactions and a merchant reference table on a Hadoop cluster. The risk team wants a repeatable analysis pack: daily approved spend by merchant category and a list of merchants with a high decline rate, each with validation queries that prove the numbers can be trusted. A previous query pack scanned seven years of data for a one-day question and quietly dropped transactions whose merchant was missing from the reference table. The analyst must build a HiveQL pack that is fast, correct and verified, and say what would change on a modern engine.

What you will be able to do

Deliverable: a HiveQL analysis pack with validation queries for a named analysis: table definitions, analysis queries, validation queries with pass criteria, a partition-pruning check, performance notes, limits and a note on the modern alternative; HiveQL marked illustrative against Hive 3.x documentation.

Prerequisites

PrerequisiteWhy it matters
Warehouses, Lakes & LakehouseBronze, silver and gold layers, Parquet and ORC, partitioning concepts.
Hadoop Core Commands & Data MovementDirectory layout and landed files that external tables point to.
Big Data & Hadoop: Distributed FoundationsYARN, MapReduce and why Hive is a layer on top.
What Data Engineers DoTables, joins and aggregations in pipeline context.
Data Quality ChecksThe checks reused as validation queries.
Python AdvancedThe worked example runs SQL from Python.
ML FundamentalsWhy merchant risk features feed later models.
Databricks & SparkSpark SQL on a managed platform, the usual modern alternative.

Plain English

What Hive is. Apache Hive is a data warehouse layer over distributed storage. Its main parts are the Metastore (a database of table names, columns, types, formats, partitions and file locations), HiveServer2 (the service that accepts queries from clients such as Beeline or BI tools) and an execution engine that turns HiveQL into distributed jobs. Hive 3 runs on Apache Tez (MapReduce as an engine is deprecated in the Hive documentation). Hive does not store data itself; it reads and writes files, for example on HDFS. The Hive metastore is also used by other engines, which is why Spark can query tables defined in Hive.

Tables: managed and external. A managed table is owned by Hive: it chooses the storage location and dropping the table deletes the data. In Hive 3, managed tables are generally transactional (ACID) tables stored as ORC, although exact defaults depend on configuration and distribution. An external table points at files you control (LOCATION '...'); dropping it removes only the definition, not the files. Use external tables for landed or shared data and managed tables for derived data that Hive should own.

Partitions. A partitioned table stores each partition value in its own directory, such as txn_date=2025-03-02/. The partition column is not stored inside the files; it comes from the directory name. A query that filters on the partition column lets Hive prune, meaning read only matching directories. Choose a low-cardinality column that queries filter by (date is typical). Avoid partitioning by an id: millions of partitions overload the metastore and create tiny files. After adding directories outside Hive, register them with MSCK REPAIR TABLE or ALTER TABLE ... ADD PARTITION.

Types. Common types are STRING, INT, BIGINT, DOUBLE, DECIMAL(p,s), BOOLEAN, DATE, TIMESTAMP and complex types (ARRAY, MAP, STRUCT). Use DECIMAL for money, not floating point, because binary floating-point values cannot represent many decimal amounts exactly and totals drift. Cast text columns to proper types early; a bad cast produces NULL, not an error, so check null counts afterwards.

HiveQL essentials. HiveQL is SQL-like: SELECT, WHERE, GROUP BY, HAVING, ORDER BY, joins (INNER, LEFT, RIGHT, FULL), aggregates, CASE, window functions such as ROW_NUMBER() and common table expressions. Typical aggregation work is GROUP BY with COUNT, SUM and AVG. An inner join drops rows with no match, which is correct only if that is what you want; prefer a LEFT JOIN followed by an orphan check. Small tables can be broadcast in a map-side join, which Hive may choose automatically (settings are environment-dependent).

Formats and performance. Plain text (CSV) is simple but slow and untyped. ORC and Parquet are columnar and compressed with statistics that let the engine skip data, so use them for anything queried repeatedly. Keep files reasonably large, partition on the common filter, collect table and column statistics (ANALYZE TABLE ... COMPUTE STATISTICS) so the optimiser can choose join strategies, filter early, select only needed columns and check the plan with EXPLAIN. Settings and plan formats are environment-dependent.

Limits. Hive is built for batch and interactive analytics over large data, not for millisecond row lookups or high-frequency single-row updates. Row-level UPDATE and DELETE need transactional tables and compaction. Query start-up cost is noticeable on small data. The metastore can become a bottleneck with huge partition counts. SQL features and behaviour differ between Hive versions and distributions, and between Hive and other engines (functions, null handling, case sensitivity, date formats), which matters for migration.

Modern distributed SQL. Spark SQL runs SQL on Spark, can read Hive tables through the metastore and is commonly used for new builds on lakehouse platforms. Google BigQuery and Snowflake are managed cloud warehouses where storage, compute and operations are provider-managed; they use their own SQL dialects and storage. All three can replace Hive for many workloads; choose by data location, governance needs, skills, latency and total cost, and obtain current pricing from the providers rather than from a course. Hive remains reasonable where an existing cluster, residency rules and sunk skills favour it.

Safe guidance. Run HiveQL first on a small partition range or a test database. Treat all queries in this lesson as illustrative against the Apache Hive 3.x documentation: check syntax and settings on your own version.

Teacher walkthrough

Plan the merchant risk analysis pack. All figures are illustrative.

  1. Business objective. Give the risk team a daily view of approved spend by merchant category and a weekly list of merchants whose decline rate suggests card testing or poor data, with numbers that reconcile to the source.
  2. Scale assumptions. 25 million transactions a day, seven years of history, daily queries over one or a few days, weekly queries over a week. Merchant reference data is a few hundred thousand rows.
  3. Data sources. Landed CSV settlement files (external raw table), the cleaned transactions table and the merchant master from the reference-data team.
  4. Volume and velocity. Daily batch load into raw, cleaned into a partitioned ORC table before 06:00; no real-time requirement in this pack.
  5. Storage. External raw table on landed files; managed ORC txn_clean partitioned by txn_date; merchant table unpartitioned and small.
  6. Processing. HiveQL on Tez: dedupe and type in the load query, then analysis queries that always filter on txn_date.
  7. Model workload. The merchant risk list feeds a fraud-model feature (merchant_decline_rate_7d) in a later lesson; the pack's definitions must match what the model team uses.
  8. Security. Role-based access to databases and tables, account tokens instead of card numbers, no personal data in the merchant table, audit of query access by the platform team.
  9. Monitoring. Query duration, partitions read per query, load row counts against control, validation pass or fail per day and queue wait time.
  10. Failure handling. A failed load leaves the previous day's partitions intact (insert overwrite per partition), validation failures block publication and the raw files remain the replay source.
  11. Cost. Drivers: cluster time per query, bytes scanned (driven by partition pruning and columnar formats), storage, metastore and operations effort and analyst time. No prices appear here; use current quotes from your platform owner or vendor.
  12. Validation. Row count and amount sum against a control record, duplicate txn_id, null amount and orphan merchant_id checks, an EXPLAIN partition check and a reconciliation of analysis totals with the cleaned table.

Worked example

The HiveQL below is illustrative against Hive 3.x documentation. Table, column, path and database names are fictional, and the file paths and settings are environment-dependent. These blocks are not executed by the course test harness.

-- ILLUSTRATIVE HiveQL (Apache Hive 3.x). Check syntax and settings on your own version.
CREATE DATABASE IF NOT EXISTS nfs_risk;
USE nfs_risk;

-- External raw table over landed CSV files; dropping it never deletes the files.
CREATE EXTERNAL TABLE IF NOT EXISTS txn_raw (
  txn_id STRING, account_id STRING, merchant_id STRING, amount DECIMAL(12,2), status STRING)
PARTITIONED BY (txn_date STRING)
ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
STORED AS TEXTFILE
LOCATION '/data/nfs/raw/txn'
TBLPROPERTIES ('skip.header.line.count'='1');
MSCK REPAIR TABLE txn_raw;
SHOW PARTITIONS txn_raw;

-- Hive-owned, columnar, partitioned table for analysis (managed; transactional behaviour is configuration-dependent).
CREATE TABLE IF NOT EXISTS txn_clean (
  txn_id STRING, account_id STRING, merchant_id STRING, amount DECIMAL(12,2), status STRING)
PARTITIONED BY (txn_date STRING)
STORED AS ORC;

CREATE TABLE IF NOT EXISTS merchants (
  merchant_id STRING, merchant_name STRING, category STRING, risk_tier STRING)
STORED AS ORC;

SET hive.exec.dynamic.partition=true;
SET hive.exec.dynamic.partition.mode=nonstrict;
INSERT OVERWRITE TABLE txn_clean PARTITION (txn_date)
SELECT txn_id, account_id, merchant_id, amount, status, txn_date
FROM (SELECT r.*, ROW_NUMBER() OVER (PARTITION BY txn_id ORDER BY txn_date) AS rn
      FROM txn_raw r WHERE txn_date BETWEEN '2025-03-01' AND '2025-03-03') d
WHERE rn = 1 AND amount IS NOT NULL;

ANALYZE TABLE txn_clean PARTITION (txn_date) COMPUTE STATISTICS;

-- Analysis 1: approved spend by day and category (partition filter first).
SELECT t.txn_date, m.category, COUNT(*) AS txns, SUM(t.amount) AS total
FROM txn_clean t JOIN merchants m ON t.merchant_id = m.merchant_id
WHERE t.txn_date BETWEEN '2025-03-01' AND '2025-03-03' AND t.status = 'approved'
GROUP BY t.txn_date, m.category;

-- Analysis 2: merchants with a high decline rate.
SELECT m.merchant_id, m.merchant_name, m.risk_tier, COUNT(*) AS txns,
       SUM(CASE WHEN t.status = 'declined' THEN 1 ELSE 0 END) / COUNT(*) AS decline_rate
FROM txn_clean t JOIN merchants m ON t.merchant_id = m.merchant_id
WHERE t.txn_date BETWEEN '2025-03-01' AND '2025-03-03'
GROUP BY m.merchant_id, m.merchant_name, m.risk_tier
HAVING COUNT(*) >= 3 AND SUM(CASE WHEN t.status = 'declined' THEN 1 ELSE 0 END) / COUNT(*) >= 0.5;

-- Validation: orphan merchants, duplicates and nulls (each should return 0), then check pruning.
SELECT COUNT(*) FROM txn_raw t LEFT JOIN merchants m ON t.merchant_id = m.merchant_id
WHERE t.txn_date = '2025-03-03' AND m.merchant_id IS NULL;
SELECT COUNT(*) FROM (SELECT txn_id FROM txn_raw WHERE txn_date = '2025-03-03'
                      GROUP BY txn_id HAVING COUNT(*) > 1) x;
SELECT COUNT(*) FROM txn_raw WHERE txn_date = '2025-03-03' AND amount IS NULL;
EXPLAIN SELECT COUNT(*) FROM txn_clean WHERE txn_date = '2025-03-02';

The runnable script mirrors the same logic with Python's built-in sqlite3 so you can see the results and the validation behaviour: it loads 15 synthetic transactions (one duplicate id, one null amount, one merchant missing from the reference table), checks them against a control record, builds a cleaned table with ROW_NUMBER(), runs the two analyses and simulates partition pruning by counting the partitions scanned. SQLite is a stand-in for logic, not for Hive performance or syntax. It needs Python 3.11+ with a bundled SQLite that supports window functions.

import sqlite3

MERCHANTS = [
    ("M1", "Fresh Mart", "grocery", "low"),
    ("M2", "QuickFuel", "fuel", "medium"),
    ("M3", "TravelNow", "travel", "high"),
    ("M4", "GadgetHub", "electronics", "high"),
]
TXNS = [
    ("T1", "A1", "M1", 40.00, "approved", "2025-03-01"),
    ("T2", "A2", "M1", 25.50, "approved", "2025-03-01"),
    ("T3", "A3", "M3", 900.00, "declined", "2025-03-01"),
    ("T4", "A3", "M3", 850.00, "declined", "2025-03-01"),
    ("T5", "A4", "M3", 700.00, "approved", "2025-03-01"),
    ("T6", "A1", "M2", 30.00, "approved", "2025-03-02"),
    ("T7", "A5", "M4", 1200.00, "declined", "2025-03-02"),
    ("T8", "A5", "M4", 1100.00, "declined", "2025-03-02"),
    ("T9", "A5", "M4", 1000.00, "approved", "2025-03-02"),
    ("T10", "A2", "M1", 15.00, "approved", "2025-03-02"),
    ("T11", "A6", "M9", 50.00, "approved", "2025-03-03"),
    ("T12", "A1", "M2", 35.00, "approved", "2025-03-03"),
    ("T12", "A1", "M2", 35.00, "approved", "2025-03-03"),
    ("T13", "A7", "M3", None, "approved", "2025-03-03"),
    ("T15", "A2", "M1", 22.00, "approved", "2025-03-03"),
]
CONTROL = {"row_count": 15, "amount_sum": 6002.50}

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE merchants (merchant_id TEXT, merchant_name TEXT, category TEXT, risk_tier TEXT)")
db.execute("CREATE TABLE txn_raw (txn_id TEXT, account_id TEXT, merchant_id TEXT, amount REAL, status TEXT, txn_date TEXT)")
db.executemany("INSERT INTO merchants VALUES (?,?,?,?)", MERCHANTS)
db.executemany("INSERT INTO txn_raw VALUES (?,?,?,?,?,?)", TXNS)


def q(sql):
    return db.execute(sql).fetchall()


checks = {
    "row count equals control": (q("SELECT COUNT(*) FROM txn_raw")[0][0], CONTROL["row_count"]),
    "amount sum equals control": (round(q("SELECT SUM(amount) FROM txn_raw")[0][0], 2), CONTROL["amount_sum"]),
}
for name, (got, want) in checks.items():
    print(f"{'PASS' if got == want else 'FAIL'} {name}: got={got} want={want}")

validation = {
    "null amounts": "SELECT COUNT(*) FROM txn_raw WHERE amount IS NULL",
    "duplicate txn_id values": "SELECT COUNT(*) FROM (SELECT txn_id FROM txn_raw GROUP BY txn_id HAVING COUNT(*) > 1)",
    "orphan merchant_id rows": ("SELECT COUNT(*) FROM txn_raw t LEFT JOIN merchants m ON t.merchant_id = m.merchant_id "
                                "WHERE m.merchant_id IS NULL"),
}
for name, sql in validation.items():
    n = q(sql)[0][0]
    print(f"{'PASS' if n == 0 else 'FAIL'} {name}: {n}")

db.execute("""CREATE TABLE txn AS
SELECT txn_id, account_id, merchant_id, amount, status, txn_date FROM (
  SELECT t.*, ROW_NUMBER() OVER (PARTITION BY txn_id ORDER BY txn_date) AS rn FROM txn_raw t
) WHERE rn = 1 AND amount IS NOT NULL""")
print("clean rows:", q("SELECT COUNT(*) FROM txn")[0][0])

print("daily approved by category:")
for row in q("""SELECT t.txn_date, m.category, COUNT(*) AS txns, ROUND(SUM(t.amount), 2) AS total
                FROM txn t JOIN merchants m ON t.merchant_id = m.merchant_id
                WHERE t.status = 'approved'
                GROUP BY t.txn_date, m.category ORDER BY t.txn_date, m.category"""):
    print(" ", row)

print("merchant risk flags:")
for row in q("""SELECT m.merchant_id, m.merchant_name, m.risk_tier, COUNT(*) AS txns,
                       ROUND(1.0 * SUM(CASE WHEN t.status = 'declined' THEN 1 ELSE 0 END) / COUNT(*), 2) AS decline_rate
                FROM txn t JOIN merchants m ON t.merchant_id = m.merchant_id
                GROUP BY m.merchant_id, m.merchant_name, m.risk_tier
                HAVING COUNT(*) >= 3 AND 1.0 * SUM(CASE WHEN t.status = 'declined' THEN 1 ELSE 0 END) / COUNT(*) >= 0.5
                ORDER BY decline_rate DESC"""):
    print(" ", row)

partitions = {}
for r in TXNS:
    partitions.setdefault(r[5], []).append(r)


def scan(dates):
    scanned = [d for d in sorted(partitions) if d in dates]
    return len(scanned), sum(len(partitions[d]) for d in scanned)


print("filter txn_date = 2025-03-02 -> partitions, rows scanned:", scan({"2025-03-02"}))
print("no partition filter           -> partitions, rows scanned:", scan(set(partitions)))

Expected result: the two control checks pass (15 rows, 6002.5 total), then the three validation checks report FAIL with a count of 1 each: one null amount, one duplicate txn_id (T12) and one orphan merchant (M9). Cleaning leaves 13 rows. Daily approved spend by category lists seven rows (for example grocery 65.5 and travel 700.0 on 2025-03-01); note that the inner join silently drops the M9 transaction of 50.00, which is exactly why the orphan check exists. The risk list returns TravelNow (M3) and GadgetHub (M4), each with three transactions and a 0.67 decline rate. Filtering on one date scans 1 partition and 5 rows; with no partition filter all 3 partitions and 15 rows are scanned, the same effect that on seven years of data separates a short query from a full scan.

A second workplace case

Northline Consumer Goods (illustrative) has about 300 HiveQL reporting scripts on an ageing cluster that business users find slow, and the infrastructure team wants to retire it. This is different from the risk pack: the task is migration, not authoring. The team inventories the scripts by usage and criticality, converts the high-value ones to Spark SQL on a managed platform (reading the same files and, where sensible, the same metastore), and runs old and new in parallel for a month, diffing row counts and totals. They keep a list of dialect differences to test: function names, date format strings, null and empty-string handling, integer division, case sensitivity, and how undefined partitions behave. Scripts nobody ran in the last year are retired rather than migrated. Where a business unit needs interactive dashboards, a managed warehouse such as BigQuery or Snowflake is evaluated with the same parallel-run acceptance tests; selection depends on data location, governance, skills and a priced proof of concept using current provider quotes.

Failure example

Symptom: A one-day merchant query that normally returns in seconds runs for forty minutes, fills the cluster queue and delays the morning risk report.

Diagnosis: The analyst filtered on the timestamp column (txn_ts) instead of the partition column txn_date. Hive cannot prune partitions from a predicate on a non-partition column, so it read every partition of seven years of history. EXPLAIN showed all partitions selected, and the table also held many small files per partition, multiplying the task count.

Correction: Add a predicate on txn_date (for example txn_date = '2025-03-02') while keeping the timestamp predicate for precision. Re-run and compare EXPLAIN. Ask the platform team to compact the small files in the affected partitions.

Validation: EXPLAIN lists only the intended partition, the result is identical to the slow query's result on a one-day sample, runtime meets the agreed target and the queue clears.

Prevention: Publish views that require a date predicate, enable the partition-filter strictness settings your Hive version provides (names are environment-dependent), review queries before they join the scheduled pack and teach EXPLAIN as a habit.

Guided practice

Scenario: The risk team also wants accounts with two or more declined transactions on the same day (a possible card-testing pattern) for 1 to 3 March 2025, plus a validation that proves the list is complete.

Hints:

  1. Which table and which columns do you need?
  2. Which clause filters partitions, and which clause keeps only groups with two or more declines?
  3. How do you check that you have not lost rows?
  4. What answer do you expect from the sample data?

Complete solution:

-- ILLUSTRATIVE HiveQL (Apache Hive 3.x).
SELECT txn_date, account_id, COUNT(*) AS declines, SUM(amount) AS declined_amount
FROM txn_clean
WHERE txn_date BETWEEN '2025-03-01' AND '2025-03-03' AND status = 'declined'
GROUP BY txn_date, account_id
HAVING COUNT(*) >= 2;

-- Validation: declines counted by the list must equal declines in the table for flagged accounts.
SELECT SUM(declines) FROM (
  SELECT COUNT(*) AS declines FROM txn_clean
  WHERE txn_date BETWEEN '2025-03-01' AND '2025-03-03' AND status = 'declined'
  GROUP BY txn_date, account_id HAVING COUNT(*) >= 2) f;

Independent practice

Build a HiveQL analysis pack with validation queries for an analysis you know, or for Northline's merchant risk analysis, and run the equivalent logic on your own synthetic data in sqlite3.

Acceptance criteria

Common mistakes

  1. Filtering on a non-partition column and scanning the whole table.
  2. Using an inner join that silently drops unmatched rows and never checking for orphans.
  3. Storing money as DOUBLE instead of DECIMAL.
  4. Partitioning by a high-cardinality key such as account_id.
  5. Leaving large tables as CSV text rather than ORC or Parquet.
  6. Forgetting MSCK REPAIR TABLE after adding directories, so new partitions are invisible.
  7. Treating a failed cast (which gives NULL) as success.
  8. Dropping an external table and assuming the files are gone, or dropping a managed table and not realising the data is deleted.
  9. Expecting Hive to serve millisecond lookups or frequent single-row updates.
  10. Migrating HiveQL to another engine without testing dialect differences and parallel-running results.

Quick check

  1. What does the Hive metastore store, and does Hive store the table data itself?
  2. What happens to the data when you drop an external table, and when you drop a managed table?
  3. Why does filtering on the partition column make a query faster?
  4. Why check for orphan keys before trusting an inner join total?
  5. Name one reason to choose Spark SQL or a managed warehouse over Hive for a new build, and one reason to keep Hive.

Answers:

  1. Table definitions, column types, formats, partitions and file locations. Hive reads and writes files in storage (for example HDFS); it does not hold the data itself.
  2. Dropping an external table removes only the definition and the files remain; dropping a managed table deletes the data as well.
  3. Hive reads only the directories that match the filter (partition pruning), so far less data is scanned.
  4. An inner join drops rows without a match, so the total can be wrong without any error; an orphan check shows how many rows were lost.
  5. For example: storage and compute scale independently, operations are managed and engines are faster for interactive and multi-step work. To keep Hive: an existing estate, residency or sunk-cost reasons, and migration risk that exceeds the benefit.

Quiz alignment

The quiz (QUIZ_DAI4) covers Hive's purpose and components, managed versus external tables, partitions and pruning, data types, HiveQL filtering, joins and aggregation, formats and performance, validation queries, Hive limits and modern distributed SQL options, using the merchant risk, card-testing and HiveQL migration cases.

Lesson summary

Hive gives SQL access to files in distributed storage through a metastore and a distributed engine. Use external tables for landed data and managed ORC tables for derived data, partition on the column queries filter by, use DECIMAL for money and always filter on the partition column. Write HiveQL with explicit joins and verify results with control totals and duplicate, null and orphan checks, because inner joins and failed casts hide errors. Hive is batch-oriented and version-dependent; Spark SQL, BigQuery and Snowflake are the usual modern options, chosen by data location, governance, skills and a proof of concept with current pricing. Treat the HiveQL in this course as illustrative and test it on your own version.

Bridge to the next lesson

The next lesson, Spark Fundamentals & Distributed Data Processing, moves from SQL over files to the Spark engine itself: how it distributes work, how it reads the same tables and files and how to build transformations and model-feature pipelines that scale beyond a single query.

Sources

Northline Consumer Goods and Northline Financial Services, their tables, volumes and findings are illustrative and synthetic. HiveQL is illustrative against Apache Hive 3.x documentation; syntax, defaults, settings and managed-table behaviour differ by version and distribution. No prices are stated for any product; use the providers' current published pricing.