SQL Zone is brought to you in partnership with:

I currently manage the BI platform for the second largest health insurance company in South Africa. In my previous life I was a BI lecturer and consultant. I have implemented data warehouses and BI solutions using both Open Source and proprietary software. I live by the saying, "keep it simple stupid." Mpumelelo is a DZone MVB and is not an employee of DZone and has posted 7 posts at DZone. You can read more from them at their website. View Full User Profile

Visualizing SQL Statements

  • submit to reddit

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.

    ,sum(s.units) as total_units
    ,sum(s.sale_price) as total_sale_price
    ,sum(prev_s.units) as prev_yr_total_units
    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
    pt.promo_type IN ('Email', 'TV')
    AND a.prod_cat_name = 'Electronics'
    AND s.sale_year >=2013

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.

For more complex examples have a look at big samples page.
Published at DZone with permission of Mpumelelo Msimanga, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)