0

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;
1

1 Answer 1

4

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.

2
  • you seem really knowledgeable on sql and postgress. I'm a student, any recommendations on consolidated resources for my understanding of both SQL language || Database design & functionality ? Commented Jul 12, 2022 at 20:10
  • 1
    @MarkThomas PostgreSQL is one of the most standard database engines in the market, and it's also free. If you want to learn SQL I would recommend learning using PosgreSQL and focus on constraints. For database design, you probably need to start with theory, and focus on normalization (1NF, 2NF, 3NF). Finally, you can tackle database design, properly; there are a number of web sites that teach that. Commented Jul 13, 2022 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.