9.1. Migrating From Hive

Presto uses ANSI SQL syntax and semantics, whereas Hive uses a SQL-like language called HiveQL which is loosely modeled after MySQL (which itself has many differences from ANSI SQL).

Use subscript for accessing a dynamic index of an array instead of a udf

The subscript operator in SQL supports full expressions, unlike Hive (which only supports constants). Therefore you can write queries like:

  1. SELECT my_array[CARDINALITY(my_array)] as last_element
  2. FROM ...

Avoid out of bounds access of arrays

Accessing out of bounds elements of an array will result in an exception. You can avoid this with an if as follows:

  1. SELECT IF(CARDINALITY(my_array) >= 3, my_array[3], NULL)
  2. FROM ...

Use ANSI SQL syntax for arrays

Arrays are indexed starting from 1, not from 0:

  1. SELECT my_array[1] AS first_element
  2. FROM ...

Construct arrays with ANSI syntax:

  1. SELECT ARRAY[1, 2, 3] AS my_array

Use ANSI SQL syntax for identifiers and strings

Strings are delimited with single quotes and identifiers are quoted with double quotes, not backquotes:

  1. SELECT name AS "User Name"
  2. FROM "7day_active"
  3. WHERE name = 'foo'

Quote identifiers that start with numbers

Identifiers that start with numbers are not legal in ANSI SQL and must be quoted using double quotes:

  1. SELECT *
  2. FROM "7day_active"

Use the standard string concatenation operator

Use the ANSI SQL string concatenation operator:

  1. SELECT a || b || c
  2. FROM ...

Use standard types for CAST targets

The following standard types are supported for CAST targets:

  1. SELECT
  2. CAST(x AS varchar)
  3. , CAST(x AS bigint)
  4. , CAST(x AS double)
  5. , CAST(x AS boolean)
  6. FROM ...

In particular, use VARCHAR instead of STRING.

Use CAST when dividing integers

Presto follows the standard behavior of performing integer division when dividing two integers. For example, dividing 7 by 2 will result in 3, not 3.5.To perform floating point division on two integers, cast one of them to a double:

  1. SELECT CAST(5 AS DOUBLE) / 2

Use WITH for complex expressions or queries

When you want to re-use a complex output expression as a filter, use either an inline subquery or factor it out using the WITH clause:

  1. WITH a AS (
  2. SELECT substr(name, 1, 3) x
  3. FROM ...
  4. )
  5. SELECT *
  6. FROM a
  7. WHERE x = 'foo'

Use UNNEST to expand arrays and maps

Presto supports UNNEST for expanding arrays and maps.Use UNNEST instead of LATERAL VIEW explode().

Hive query:

  1. SELECT student, score
  2. FROM tests
  3. LATERAL VIEW explode(scores) t AS score;

Presto query:

  1. SELECT student, score
  2. FROM tests
  3. CROSS JOIN UNNEST(scores) AS t (score);