Book Image

SQL Query Design Patterns and Best Practices

By : Steve Hughes, Dennis Neer, Dr. Ram Babu Singh, Shabbir H. Mala, Leslie Andrews, Chi Zhang
5 (1)
Book Image

SQL Query Design Patterns and Best Practices

5 (1)
By: Steve Hughes, Dennis Neer, Dr. Ram Babu Singh, Shabbir H. Mala, Leslie Andrews, Chi Zhang

Overview of this book

SQL has been the de facto standard when interacting with databases for decades and shows no signs of going away. Through the years, report developers or data wranglers have had to learn SQL on the fly to meet the business needs, so if you are someone who needs to write queries, SQL Query Design and Pattern Best Practices is for you. This book will guide you through making efficient SQL queries by reducing set sizes for effective results. You’ll learn how to format your results to make them easier to consume at their destination. From there, the book will take you through solving complex business problems using more advanced techniques, such as common table expressions and window functions, and advance to uncovering issues resulting from security in the underlying dataset. Armed with this knowledge, you’ll have a foundation for building queries and be ready to shift focus to using tools, such as query plans and indexes, to optimize those queries. The book will go over the modern data estate, which includes data lakes and JSON data, and wrap up with a brief on how to use Jupyter notebooks in your SQL journey. By the end of this SQL book, you’ll be able to make efficient SQL queries that will improve your report writing and the overall SQL experience.
Table of Contents (21 chapters)
1
Part 1: Refining Your Queries to Get the Results You Need
6
Part 2: Solving Complex Business and Data Problems in Your Queries
11
Part 3: Optimizing Your Queries to Improve Performance
14
Part 4: Working with Your Data on the Modern Data Platform

Understanding window functions

A window function operates over a set of rows called a window and returns a column that is included with the other selected columns. The window becomes a partition on the table and allows the rows to retain their details while providing an aggregate. That is what makes the window function different from aggregates, even though, in some cases, it is evaluating an aggregate.

Here is a partial list of the window functions:

  • Ranking:
    • ROW_NUMBER
    • RANK
    • DENSE_RANK
    • NTILE
    • PERCENT_RANK
    • CUME_DISTLEAD
    • FIRST_VALUE
    • LAST_VALUE
    • COUNT
    • PERCENTILE_CONT
    • PERCENTILE_DIST
  • Value:
    • LAG
  • Aggregate:
    • AVG
    • SUM
    • MAX/MIN

Next, we will look at the structure of the window functions and the required clauses to create them.

Using a window function in a query

To use a window function in a query, you just include it as a column in the query definition. Every window function requires an OVER clause and optionally can include a PARTITION BY clause and an ORDER BY clause, which is...