KatInterview

Report SQL Clauses in Conceptual Evaluation Order

StringsAuto-graded · 17 test cases
EasyAuto-gradedStringsstringsregexsql

Last updated

Detect which of six SQL clauses appear in a query string and return them in SQL-92 logical evaluation order, using case-insensitive whole-word matching.

Report SQL Clauses in Conceptual Evaluation Order

A SQL query is written starting with SELECT, but a database conceptually evaluates its clauses in a different sequence. Under the SQL-92 model, the logical evaluation order of the six clauses is:

  1. FROM
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT
  6. ORDER BY

Given the text of a query, determine which of these six clauses are present and return their names in the logical evaluation order above.

Task

Implement a function that takes a query string and returns a list of clause names, containing only the clauses found in the text, arranged in the logical order listed above.

Rules

  • Matching is case-insensitive: select, Select, and SELECT all count as SELECT.
  • A keyword only counts as a whole word. Identifiers that merely contain a keyword, such as FROMAGE, my_from, or SELECTED, do not count. Letters, digits, and underscore are word characters.
  • GROUP BY and ORDER BY each count as one clause. The two words may be separated by any amount of whitespace (spaces, tabs, newlines), but at least one whitespace character is required.
  • The output order depends only on the fixed logical order, not on where the keywords appear in the text. A clause appears at most once in the result, no matter how many times it occurs.
  • This is a keyword detector, not a SQL parser. Keywords inside string literals, comments, or subqueries are counted like any other occurrence.
  • Output names must be exactly: "FROM", "WHERE", "GROUP BY", "HAVING", "SELECT", "ORDER BY" (uppercase, with a single space in the two-word names).
  • If no clause is found (including for an empty string), return an empty list.

Constraints

  • query is a string; its length may be zero.
  • Only the six clauses above need to be detected.
  • Return a list of strings.

Examples

Example 1

Input: clauses_in_logical_order('SELECT foo, COUNT(foo) FROM pokes WHERE foo > 10 GROUP BY foo HAVING COUNT(foo) > 1 ORDER BY foo;')

Output: ['FROM', 'WHERE', 'GROUP BY', 'HAVING', 'SELECT', 'ORDER BY']

Hints

Hint 1

Write the six clause names once, in logical order, and decide for each whether it occurs in the query. Filtering that fixed list keeps the right order automatically.

Hint 2

Normalize case first (for example by uppercasing), then use a regular expression with word boundaries so that identifiers like FROMAGE or my_from are not matched.

Hint 3

For GROUP BY and ORDER BY, allow one or more whitespace characters between the two words so tabs, newlines, and repeated spaces still match.