CMuscroft / intro-data-capstone-musclehub

0 stars 0 forks source link

Try to format the SQL statement so that it is more readable #3

Open jmcrey opened 5 years ago

jmcrey commented 5 years ago

https://github.com/CMuscroft/intro-data-capstone-musclehub/blob/d36da442eb09324c20911f19dab001dc04612fcc/Capstone%20Project%20-%20Charlotte%20Muscroft/musclehub.py.html#L117-L120

Really nice job creating this SQL query! It works exactly how we desire and pulls all the data required for this project. The only thing is that it is quite difficult to read. In fact, since the entire query is on one line, it is very difficult to decipher exactly what data it is pulling.

To combat this, we can use spacing and indentation to help the reader digest our query and more easily grasp what our query is doing. Specifically, if we follow the rules in our SQL Style Guide, we will better be able to read and understand each query. Here is an example of this query formatted following these rules:

df = sql_query('''
SELECT visits.first_name, 
       visits.last_name, 
       visits.gender, 
       visits.email, 
       visits.visit_date, 
       fitness_tests.fitness_test_date, 
       applications.application_date, 
       purchases.purchase_date 
FROM visits 
LEFT JOIN fitness_tests 
     ON visits.first_name = fitness_tests.first_name 
     AND visits.last_name = fitness_tests.last_name 
     AND visits.email = fitness_tests.email 
LEFT JOIN applications 
     ON visits.first_name = applications.first_name 
     AND visits.last_name = applications.last_name 
     AND visits.email = applications.email 
LEFT JOIN purchases 
     ON visits.first_name = purchases.first_name 
     AND visits.last_name = purchases.last_name 
     AND visits.email = purchases.email 
WHERE visit_date >= "7-1-17"
''')

Notice that each selected column is on its own line and they are left-aligned for easier visual-digestion. Further, the sections of each JOIN are in their own mini-sections such that we know exactly where a JOIN begins and ends based on the indentation.

Again, the query was excellent in terms of content, it was just quite hard to understand. So, I highly recommend taking a look at the above SQL Style Guide for a reference on how to format SQL queries for easier reading.