Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases Reporting with SQL Aggregate and Numeric Functions Counting Results

How to remember where to put what part of a SQL query?

This question isn't really about any specific Challenge Task. I keep getting stuck because I put "AS" or "WHERE" or some other keyword or function in wrong spot in my query. Is there a good place to reference to find what order everything should go in? Is there a more general rule of thumb that I can remember? This is getting pretty frustrating.

3 Answers

Hi Jack!

Generally, SQL order of operations is as follows:

SELECT DISTINCT <column_name> AS <new_column_name>
FROM <left_table> AS <new_table_name_A>
<join_type> JOIN <right_table> AS <new_table_name_B>
ON <join_condition> (<new_table_name_A>.<column_name> = <new_table_name_B>.<column_name>)
WHERE <where_condition>  
GROUP BY <group_by_list>
HAVING <having_condition>
ORDER BY <order_by_list>
LIMIT <limit_condition>;

Keep in mind, this is the customary way to write the query, but actual execution happens in a different order (see second link below).

And I recommend, if you don't generally do it already, to stack your queries like above for easier readability (it makes editing and debugging the query much easier).

More info:

https://learnsql.com/blog/sql-order-of-operations/

https://stackoverflow.com/questions/4596467/order-of-execution-of-the-sql-query

I also recommend checking these out, if you haven't already:

https://teamtreehouse.com/library/sql-basics/getting-data-from-a-database/review-practice-with-sql-playgrounds

To practice writing/running queries:

https://sqlpad.io/playground/

https://www.w3schools.com/sql/trysql.asp?filename=trysql_asc

https://sql-playground.wizardzines.com/

I hope this all helps.

Stay safe and happy coding!

BTW, this passes task 1:

SELECT COUNT(*) AS scifi_book_count
FROM books
WHERE genre = "Science Fiction";

This passes task 2:

SELECT COUNT(*) AS jk_book_count
FROM books
WHERE author = "J.K Rowling"

Again, I hope that helps.

Stay safe and happy coding!

Thanks a million for that comprehensive answer!

Follow up question for you Peter Vann : If I were doing a set operation with a second query, that would go between WHERE and GROUP BY, correct?