Home > Enterprise >  What is SQL's Keyword order? (Postgresql)
What is SQL's Keyword order? (Postgresql)

Time:07-07

Depending on where you put SELECT, FROM, WHERE, etc, I have run into syntax errors. What is the proper order to write queries and code? An example below:

//No error
SELECT count(*)
FROM us_counties_pop_est_2019
WHERE births_2019 - deaths_2019 <=0;

vs

//Syntax error
SELECT count(*) 
WHERE births_2019 - deaths_2019 <=0
FROM us_counties_pop_est_2019;

CodePudding user response:

The main clauses of a SELECT statement in PostgreSQL are written in the following order:

  • [WITH]
  • SELECT
  • FROM
  • JOIN
  • WHERE
  • GROUP BY
  • HAVING
  • WINDOW
  • ORDER BY
  • OFFSET
  • LIMIT

If the query includes CTEs, then the WITH clause comes before the other ones.

  • Related