Criteria to SQL Converter

Difficulty: Hard · Topics: Recursion, SQL, Parsing, Tree · Acceptance: 100.0% of 1 submissions

Difficulty: Hard  |  Tags: SQL, Parsing, Tree, Recursion

Description

Given a criteria object (similar to Zoho CRM API criteria), convert it to a SQL WHERE clause.

A criteria object has the structure:

{
  "group_operator": "and",
  "group": [
    {"field": "name", "comparator": "equals", "value": "Alice"},
    {"field": "age", "comparator": "greater_than", "value": 25},
    {
      "group_operator": "or",
      "group": [
        {"field": "city", "comparator": "equals", "value": "NYC"},
        {"field": "city", "comparator": "equals", "value": "LA"}
      ]
    }
  ]
}

Implement:

criteriaToSQL(criteria) → String

Examples

Example 1:

Input:
  {"field": "name", "comparator": "equals", "value": "Alice"}

Output: "name = 'Alice'"

Example 2:

Input:
  {
    "group_operator": "and",
    "group": [
      {"field": "age", "comparator": "greater_than", "value": 25},
      {"field": "status", "comparator": "equals", "value": "active"}
    ]
  }

Output: "(age > 25 AND status = 'active')"

Example 3 — Nested:

Input: (the full example above)

Output: "(name = 'Alice' AND age > 25 AND (city = 'NYC' OR city = 'LA'))"

Supported Comparators

ComparatorSQL
equals=
not_equals!=
greater_than>
less_than<
greater_equal>=
less_equal<=
containsLIKE '%value%'
starts_withLIKE 'value%'
ends_withLIKE '%value'
is_nullIS NULL
is_not_nullIS NOT NULL
inIN (...)

Constraints

Hints

Hint 1

Recursively process: if the node has a group field, recurse into each item and join with the operator. Otherwise, it's a leaf — convert the single condition.

Practice this problem

Related problems