Visualizing SQL Statements
Join the DZone community and get the full member experience.Join For Free
Usually if I concentrate I am able to understand most SQL statements. There are times though such as:
- When a set of tables is not familiar
- When I did not write the SQL statement
- When the SQL statement is long and involves many tables and joins
- When I want to discuss a statement with a colleague
- All of the above
Having a visual representation of a SQL statement can be helpful in deciphering the statement. My visualisation tool of choice for SQL is an Open Source application called Reverse Snowflake Joins (REVJ). As the name implies, this tool shines when it comes to showing you how your tables are related.
I have installed the tool on my workstation but when I am on the move I use the online version of the tool. Using the tool is straight forward, simply paste your SQL statement in the text area and generate the diagram, the online version generates an SVG image. I have at times found that the tool struggles with complex CASE statements. In such cases I remove the CASE statement and just include the fields used in the case statement. Below is a sample statement to show REVJ at work.
SELECT a.prod_cat_name ,b.prod_name ,c.prod_owner_name ,p.promo_id ,pt.promo_type ,sum(s.units) as total_units ,sum(s.sale_price) as total_sale_price ,sum(prev_s.units) as prev_yr_total_units FROM product_category a JOIN product b ON a.product_cat_id = b.product_cat_id LEFT OUTER JOIN product_owner c ON a.product_cat_id = c.product_cat_id JOIN sales s ON b.product_id = s.product_id JOIN sales prev_s ON s.sale_year = prev_s.sale_year-1 LEFT OUTER JOIN promotion p ON s.promo_id = p.promo_id RIGHT OUTER JOIN promo_type pt ON p.promo_type_id = pt.promo_type_id WHERE pt.promo_type IN ('Email', 'TV') AND a.prod_cat_name = 'Electronics' AND s.sale_year >=2013 GROUP BY a.prod_cat_name ,b.prod_name ,c.prod_owner_name ,p.promo_id ,pt.promo_type HAVING sum(s.units)>100
The generated image shown below. Notice how the filters applied to each table are also shown, further simplifying the task of understanding the SQL statement.big samples page.
Published at DZone with permission of Mpumelelo Msimanga, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.