Demystifying PROC SQL Join Algorithms

Similar documents
Exploring DATA Step Merge and PROC SQL Join Techniques Kirk Paul Lafler, Software Intelligence Corporation, Spring Valley, California

PROC SQL for New Users Kirk Paul Lafler, Software Intelligence Corporation

Simple Rules to Remember When Working with Indexes

Conditional Processing Using the Case Expression in PROC SQL

Conditional Processing in the SAS Software by Example

JMP Coders 101 Insights

Exploring DICTIONARY Tables and SASHELP Views

One-to-One, One-to-Many, and Many-to-Many Joins Using PROC SQL

Connect with SAS Professionals Around the World with LinkedIn and sascommunity.org

An Introduction to SAS Hash Programming Techniques Kirk Paul Lafler, Software Intelligence Corporation, Spring Valley, California

A Hands-on Tour Inside the World of PROC SQL

An Introduction to PROC REPORT

Undocumented and Hard-to-find PROC SQL Features

A Visual Step-by-step Approach to Converting an RTF File to an Excel File

Using SAS Enterprise Guide to Coax Your Excel Data In To SAS

A Hands-on Introduction to SAS DATA Step Hash Programming Techniques

Undocumented and Hard-to-find PROC SQL Features

Introduction / Overview

Introduction to ODS Statistical Graphics

SAS Macro Programming Tips and Techniques

Ten Great Reasons to Learn SAS Software's SQL Procedure

Quick Results with SAS Enterprise Guide

A Hands-on Tour Inside the World of PROC SQL Kirk Paul Lafler, Software Intelligence Corporation, Spring Valley, California

What's Hot, What's Not - Skills for SAS Professionals Kirk Paul Lafler, Software Intelligence Corporation Charles Edwin Shipp, Shipp Consulting

Ready To Become Really Productive Using PROC SQL? Sunil K. Gupta, Gupta Programming, Simi Valley, CA

PharmaSUG Paper TT03. Kirk Paul Lafler, Software Intelligence Corporation, Spring Valley, California

If You Need These OBS and These VARS, Then Drop IF, and Keep WHERE Jay Iyengar, Data Systems Consultants LLC

KEYWORDS Metadata, macro language, CALL EXECUTE, %NRSTR, %TSLIT

SAS Performance Tuning Strategies and Techniques

Can you decipher the code? If you can, maybe you can break it. Jay Iyengar, Data Systems Consultants LLC, Oak Brook, IL

Arthur L. Carpenter California Occidental Consultants, Oceanside, California

SAS Programming Tips, Tricks and Techniques

INTRODUCTION TO PROC SQL JEFF SIMPSON SYSTEMS ENGINEER

Dynamic Dashboards Using Base-SAS Software

Output Delivery System (ODS) Simply the Basics

PROC SQL vs. DATA Step Processing. T Winand, Customer Success Technical Team

Using Data Set Options in PROC SQL Kenneth W. Borowiak Howard M. Proskin & Associates, Inc., Rochester, NY

Quality Control of Clinical Data Listings with Proc Compare

Oracle Compare Two Database Tables Sql Query Join

Advanced PROC REPORT: Getting Your Tables Connected Using Links

Guide Users along Information Pathways and Surf through the Data

Getting Up to Speed with PROC REPORT Kimberly LeBouton, K.J.L. Computing, Rossmoor, CA

Importing CSV Data to All Character Variables Arthur L. Carpenter California Occidental Consultants, Anchorage, AK

Table Lookups: From IF-THEN to Key-Indexing

Test Bank for Database Processing Fundamentals Design and Implementation 13th Edition by Kroenke

$99.95 per user. Writing Queries for SQL Server (2005/2008 Edition) CourseId: 160 Skill level: Run Time: 42+ hours (209 videos)

Output Delivery System (ODS) Tips and Techniques

Using the SQL Editor. Overview CHAPTER 11

Google Search Tips and Techniques for SAS and JMP Users!

Tackling Unique Problems Using TWO SET Statements in ONE DATA Step. Ben Cochran, The Bedford Group, Raleigh, NC

Programming Beyond the Basics. Find() the power of Hash - How, Why and When to use the SAS Hash Object John Blackwell

KEYWORDS ARRAY statement, DO loop, temporary arrays, MERGE statement, Hash Objects, Big Data, Brute force Techniques, PROC PHREG

T-SQL Training: T-SQL for SQL Server for Developers

Anatomy of a Merge Gone Wrong James Lew, Compu-Stat Consulting, Scarborough, ON, Canada Joshua Horstman, Nested Loop Consulting, Indianapolis, IN, USA

Quick Results with the Output Delivery System

Database Optimization

Full file at

Different Methods for Accessing Non-SAS Data to Build and Incrementally Update That Data Warehouse

Reading and Writing RTF Documents as Data: Automatic Completion of CONSORT Flow Diagrams

SECTION 1 DBMS LAB 1.0 INTRODUCTION 1.1 OBJECTIVES 1.2 INTRODUCTION TO MS-ACCESS. Structure Page No.

Visual Storytelling The Art of Communicating Information with Graphics

Relational Database Model. III. Introduction to the Relational Database Model. Relational Database Model. Relational Terminology.

Hash Objects for Everyone

Slicing and Dicing Data in CF and SQL: Part 2

MariaDB Crash Course. A Addison-Wesley. Ben Forta. Upper Saddle River, NJ Boston. Indianapolis. Singapore Mexico City. Cape Town Sydney.

A Guided Tour Through the SAS Windowing Environment Casey Cantrell, Clarion Consulting, Los Angeles, CA

Statistical Discovery

USING SAS HASH OBJECTS TO CUT DOWN PROCESSING TIME Girish Narayandas, Optum, Eden Prairie, MN

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

Testing ANSI SQL Hierarchical Data Modeling and Structure Processing

Using Different Methods for Accessing Non-SAS Data to Build and Incrementally Update That Data Warehouse

Introductory SQL SQL Joins: Viewing Relationships Pg 1

Lecture 06. Fall 2018 Borough of Manhattan Community College

DBLOAD Procedure Reference

Locking SAS Data Objects

Querying Data with Transact SQL

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

Files Arriving at an Inconvenient Time? Let SAS Process Your Files with FILEEXIST While You Sleep

Creating Zillions of Labels (and Other Documents) the Easy Way with ODS and Microsoft Word

Oracle Syllabus Course code-r10605 SQL

APPENDIX 4 Migrating from QMF to SAS/ ASSIST Software. Each of these steps can be executed independently.

The DATA Statement: Efficiency Techniques

Now That You Have Your Data in Hadoop, How Are You Staging Your Analytical Base Tables?

Best Practice for Creation and Maintenance of a SAS Infrastructure

Are Your SAS Programs Running You? Marje Fecht, Prowerk Consulting, Cape Coral, FL Larry Stewart, SAS Institute Inc., Cary, NC

Countdown of the Top 10 Ways to Merge Data David Franklin, Independent Consultant, Litchfield, NH

Using PROC SQL to Calculate FIRSTOBS David C. Tabano, Kaiser Permanente, Denver, CO

Beginning Transact-SQL with SQL Server 2000 and Paul Turley with Dan Wood

Join (SQL) - Wikipedia, the free encyclopedia

Course Outline and Objectives: Database Programming with SQL

Why choose between SAS Data Step and PROC SQL when you can have both?

INTRODUCTION TO THE QUALIFIED COURSE PROFESSIONAL GUIDELINES

How to Implement the One-Time Methodology Mark Tabladillo, Ph.D., MarkTab Consulting, Atlanta, GA Associate Faculty, University of Phoenix

Advancement Application

capabilities and their overheads are therefore different.

Using the Force of Python and SAS Viya on Star Wars Fan Posts

Chapter 7 File Access. Chapter Table of Contents

Is Your Data Viable? Preparing Your Data for SAS Visual Analytics 8.2

Introduction to Data-driven Programming Using SAS

Oracle Database 11g: SQL and PL/SQL Fundamentals

Transcription:

Demystifying PROC SQL Join Algorithms Kirk Paul Lafler, Software Intelligence Corporation, Spring Valley, California ABSTRACT When it comes to performing PROC SQL joins, users supply the names of the tables for joining along with the join conditions, and the PROC SQL optimizer determines which of the available join algorithms to use for performing the join operation. Attendees learn about the different types of join algorithms and explore nested loop (brute-force), sortmerge, index, and hash join methods along with selected options to control processing. INTRODUCTION The SQL procedure is a simple and flexible tool for joining tables of data together. Certainly many of the join techniques can be accomplished using other methods, but the simplicity and flexibility found in the SQL procedure makes it especially interesting, if not indispensable, as a tool for the information practitioner. This paper presents the importance of joins, the join algorithms, how joins are performed without a WHERE clause, with a WHERE clause, using table aliases, and with three tables of data. WHY JOIN ANYWAY? As relational database systems continue to grow in popularity, the need to access normalized data stored in separate tables becomes increasingly important. By relating matching values in key columns in one table with key columns in two or more tables, information can be retrieved as if the data were stored in one huge file. Consequently, the process of joining data from two or more tables can provide new and exciting insights into data relationships. SQL JOINS A join of two or more tables provides a means of gathering and manipulating data in a single SELECT statement. Joins are specified on a minimum of two tables at a time, where a column from each table is used for the purpose of connecting the two tables using a WHERE clause. Typically, the tables connecting columns have "like" values and the same datatype attributes since the join's success is often dependent on these values. EXAMPLE TABLES A relational database is simply a collection of tables. Each table contains one or more columns and one or more rows of data. The examples presented in this paper apply an example database consisting of three tables:,, and. Each table appears below. CUST_NO NAME CITY STATE 11321 John Smith Miami FL 44555 Alice Jones Baltimore MD 21713 Ryan Adams Atlanta GA CUST_NO MOVIE_NO RATING CATEGORY 44555 1011 PG-13 Adventure 21713 3090 G Comedy 44555 2198 G Comedy 37753 4456 PG Suspense MOVIE_NO LEAD_ACTOR 1011 Mel Gibson 2198 Clint Eastwood 3090 Sylvester Stallone 1

PROC SQL JOIN ALGORITHMS When it comes to performing PROC SQL joins, users supply the names of the tables for joining along with the join conditions, and the PROC SQL optimizer determines which of the available join algorithms to use for performing the join operation. There are three algorithms used in the process of performing a join: Nested Loop Join When an equality condition is not specified, a read of the complete contents of the right table is processed for each row in the left table. Merge Join When the tables specified are already in the desired sort order, resources will not need to be extended to rearranging the tables. Hash Join When an equality relationship exists, the smaller of the tables is able to fit in memory, no sort operations are required, and each table is read only once. JOINING TWO TABLES WITH A WHERE CLAUSE Joining two tables together is a relatively easy process in SQL. To illustrate how a join works, a two-table join is linked in the following diagram. Cust_no Name City State Cust_no Movie_no The following SQL code references a join on two tables with CUST_NO specified as the connecting column. SELECT * FROM, WHERE.CUST_NO =.CUST_NO; In this example, tables and are used. Each table has a common column, CUST_NO which is used to connect rows together from each when the value of CUST_NO is equal, as specified in the WHERE clause. A WHERE clause restricts what rows of data will be included in the resulting join. CREATING A CARTESIAN PRODUCT When a WHERE clause is omitted, all possible combinations of rows from each table is produced. This form of join is known as the Cartesian Product. Say for example you join two tables with the first table consisting of 10 rows and the second table with 5 rows. The result of these two tables would consist of 50 rows. Very rarely is there a need to perform a join operation in SQL where a WHERE clause is not specified. The primary importance of being aware of this form of join is to illustrate a base for all joins. Visually, the two tables would be combined without a corresponding WHERE clause as illustrated in the following diagram. Consequently, no connection between common columns exists. Cust_no Name City State Cust_no Movie_no 2

To inspect the results of a Cartesian Product, you could submit the same code as before but without the WHERE clause. SELECT * FROM, ; TABLE ALIASES Table aliases provide a "short-cut" way to reference one or more tables within a join operation. One or more aliases are specified so columns can be selected with a minimal number of keystrokes. To illustrate how table aliases in a join works, a two-table join is linked in the following diagram. M Cust_no Movie_no A Movie_no Lead_actor The following SQL code illustrates a join on two tables with MOVIE_NO specified as the connecting column. The table aliases are specified in the SELECT statement as qualified names, the FROM clause, and the WHERE clause. SELECT M.MOVIE_NO, M.RATING, A.LEADING_ACTOR FROM M, A WHERE M.MOVIE_NO = A.MOVIE_NO; JOINING THREE TABLES In an earlier example, you saw where customer information was combined with the movies they rented. You may also want to display the leading actor of each movie along with the other information. To do this, you will need to extract information from three different tables:,, and. A join with three tables follows the same rules as in a two-table join. Each table will need to be listed in the FROM clause with appropriate restrictions specified in the WHERE clause. To illustrate how a three table join works, the following diagram should be visualized. Cust_no Name City State Cust_no Movie_no Movie_no Lead_actor 3

The following SQL code references a join on three tables with CUST_NO specified as the connecting column for the and tables, and MOVIE_NO as the connecting column for the and tables. SELECT C.CUST_NO, M.MOVIE_NO, M.RATING, M.CATEGORY, A.LEADING_ACTOR FROM C, M, A WHERE C.CUST_NO = M.CUST_NO AND M.MOVIE_NO = A.MOVIE_NO; OUTER JOINS Generally a join is a process of relating rows in one table with rows in another. But occasionally, you may want to include rows from one or both tables that have no related rows. This concept is referred to as row preservation and is a significant feature offered by the outer join construct. There are operational and syntax differences between inner (natural) and outer joins. First, the maximum number of tables that can be specified in an outer join is two (the maximum number of tables that can be specified in an inner join is 32). Like an inner join, an outer join relates rows in both tables. But this is where the similarities end because the result table also includes rows with no related rows from one or both of the tables. This special handling of matched and unmatched rows of data is what differentiates an outer join from an inner join. An outer join can accomplish a variety of tasks that would require a great deal of effort using other methods. This is not to say that a process similar to an outer join can not be programmed it would probably just require more work. Let s take a look at a few tasks that are possible with outer joins: List all customer accounts with rentals during the month, including customer accounts with no purchase activity. Compute the number of rentals placed by each customer, including customers who have not rented. Identify movie renters who rented a movie last month, and those who did not. Another obvious difference between an outer and inner join is the way the syntax is constructed. Outer joins use keywords such as LEFT JOIN, RIGHT JOIN, and FULL JOIN, and has the WHERE clause replaced with an ON clause. These distinctions help identify outer joins from inner joins. Finally, specifying a left or right outer join is a matter of choice. Simply put, the only difference between a left and right join is the order of the tables they use to relate rows of data. As such, you can use the two types of outer joins interchangeably and is one based on convenience. EXPLORING OUTER JOINS Outer joins process data relationships from two tables differently than inner joins. In this section a different type of join, known as an outer join, will be illustrated. The following code example illustrates a left outer join to identify and match movie numbers from the and tables. The resulting output would contain all rows for which the SQL expression, referenced in the ON clause, matches both tables and retaining all rows from the left table () that did not match any row in the right () table. Essentially the rows from the left table are preserved and captured exactly as they are stored in the table itself, regardless if a match exists. 4

SQL Code SELECT movies.movie_no, leading_actor, rating FROM LEFT JOIN ON movies.movie_no = actors.movie_no; The result of a Left Outer join is illustrated by the shaded area (A and AB) in the following diagram. A AB B The next example illustrates the result of using a right outer join to identify and match movie titles from the and tables. The resulting output would contain all rows for which the SQL expression, referenced in the ON clause, matches in both tables (is true) and all rows from the right table () that did not match any row in the left () table. SQL Code SELECT movies.movie_no, actor_leading, rating FROM RIGHT JOIN ON movies.movie_no = actors.movie_no; The result of a Right Outer join is illustrated by the shaded area (AB and B) in the following diagram. A AB B CONCLUSION The SQL procedure provides a powerful way to join two or more tables of data. It's easy to learn and use. More importantly, since the SQL procedure follows the ANSI (American National Standards Institute) guidelines, your knowledge is portable to other platforms and vendor implementations. The simplicity and flexibility of performing joins with the SQL procedure makes it an especially interesting, if not indispensable, tool for the information practitioner. 5

REFERENCES Lafler, Kirk Paul (2012), Powerful, But Sometimes Hard-to-find PROC SQL Features, Iowa SAS Users Conference, Software Intelligence Corporation, Spring Valley, CA, USA. Lafler, Kirk Paul (2011), Powerful and Sometimes Hard-to-find PROC SQL Features, PharmaSUG 2011 Conference, Software Intelligence Corporation, Spring Valley, CA, USA. Lafler, Kirk Paul (2010), Exploring Powerful Features in PROC SQL, SAS Global Forum (SGF) Conference, Software Intelligence Corporation, Spring Valley, CA, USA. Lafler, Kirk Paul (2008), Kirk s Top Ten Best PROC SQL Tips and Techniques, Wisconsin Illinois SAS Users Conference (June 26 th, 2008), Software Intelligence Corporation, Spring Valley, CA, USA. Lafler, Kirk Paul (2008), Exploring the Undocumented PROC SQL _METHOD Option, Proceedings of the SAS Global Forum (SGF) 2008 Conference, Software Intelligence Corporation, Spring Valley, CA, USA. Lafler, Kirk Paul (2007), Undocumented and Hard-to-find PROC SQL Features, Proceedings of the PharmaSUG 2007 Conference, Software Intelligence Corporation, Spring Valley, CA, USA. Lafler, Kirk Paul and Ben Cochran (2007), A Hands-on Tour Inside the World of PROC SQL Features, Proceedings of the SAS Global Forum (SGF) 2007 Conference, Software Intelligence Corporation, Spring Valley, CA, and The Bedford Group, USA. Lafler, Kirk Paul (2006), A Hands-on Tour Inside the World of PROC SQL, Proceedings of the 31 st Annual SAS Users Group International Conference, Software Intelligence Corporation, Spring Valley, CA, USA. Lafler, Kirk Paul (2005), Manipulating Data with PROC SQL, Proceedings of the 30 th Annual SAS Users Group International Conference, Software Intelligence Corporation, Spring Valley, CA, USA. Lafler, Kirk Paul (2004). PROC SQL: Beyond the Basics Using SAS, SAS Institute Inc., Cary, NC, USA. Lafler, Kirk Paul (2003), Undocumented and Hard-to-find PROC SQL Features, Proceedings of the Eleventh Annual Western Users of SAS Software Conference. Lafler, Kirk Paul (1992-2006). PROC SQL for Beginners; Software Intelligence Corporation, Spring Valley, CA, USA. Lafler, Kirk Paul (1998-2006). Intermediate Software Intelligence Corporation, Spring Valley, CA, USA. ACKNOWLEDGMENTS I want to thank Katie Martin and Dennis Fisher, Tutorials Section Chairs, for accepting my abstract and paper. I also want to thank Scott Leslie, WUSS 2012 Academic Chair, Sally Carson, WUSS 2012 Operations Chair, the WUSS Executive Committee, SAS Institute, and Conference Leaders for organizing a great conference! TRADEMARK CITATIONS SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. indicates USA registration. Other brand and product names are trademarks of their respective companies. ABOUT THE AUTHOR Kirk Paul Lafler is consultant and founder of Software Intelligence Corporation and has been using SAS since 1979. He is a SAS Certified Professional, provider of IT consulting services, trainer to SAS users around the world, and sascommunity.org emeritus Advisory Board member. As the author of four books including PROC SQL: Beyond the Basics Using SAS, Kirk has written more than five hundred peer-reviewed papers, been an Invited speaker and trainer at three hundred-plus SAS International, regional, local, and special-interest user group conferences and meetings, and is the recipient of 19 Best contributed paper, hands-on workshop (HOW), and poster awards. His popular SAS Tips column, Kirk s Korner of Quick and Simple Tips, appears regularly in several SAS User Group newsletters and websites, and his fun-filled SASword Puzzles is featured in SAScommunity.org. Comments and suggestions can be sent to: Kirk Paul Lafler Senior Consultant, Application Developer, Data Magicianist, Trainer and Author Software Intelligence Corporation E-mail: KirkLafler@cs.com LinkedIn: http://www.linkedin.com/in/kirkpaullafler Twitter: @sasnerd 6