Friday, September 22, 2023

Jump-start your SQL Development with new ACS SQL Generators

With the first day of Fall quickly approaching, it won’t be too long before us Minnesotans need to make sure we have jumper cables in our vehicles for the cold winter months. Hopefully, that’s later rather than sooner…

The new SQL generators for Db2 tables (& physical files) in IBM i Access Client Solutions (ACS) 1.1.9.3 provide a different type of jump-start. These recently released generators should help developers that are new to SQL by providing the option of generating Insert, Update, and Delete statements along with Stored Procedures that perform the same data change operations.

The following figure highlights the new Generate options available for a table with ACS 1.1.9.3. Prior to this latest round of enhancements, ACS only provided the ability to generate the table definition or a query to retrieve all the columns from a table.














Here's an example of the SQL produced by the Update and Delete statements generated for the Employee table in the Db2 sample database.










Notice that the generated statements include host variable placeholders to make it easier to embed the SQL statements in your high-level language programs. Also, notice how the ACS generator utilizes the IS DISTINCT predicate on the WHERE clause. The IS DISTINCT predicate is handy with null capable columns because it automatically accounts for the null values - either both values being compared must both be null or both of the non-null values must match.

Here's an example of the SQL generated by the Procedure->Delete option.


















You may be wondering what’s the point of generating a stored procedure that wrappers an Insert, Update or Delete statement. The usage of stored procedures to support CRUD (Create, Read, Update, Delete) operations on database tables is a pretty common coding pattern/architecture. Some DBMS products advocate this approach because their stored procedures offer better performance for Create, Read, Update, and Delete operations. While this performance difference doesn’t apply to Db2 for i, the CRUD stored procedure approach does offer security and application architecture advantages.

ACS 1.1.9.3 currently only generates stored procedures for create (ie, insert), update, and delete operations. Adding a stored procedure generator for the read operation is on IBM’s list of future possible enhancements.

You should now see how these new SQL generators in ACS can provide a nice boost to the coding productivity of developers who are new to using SQL and/or stored procedures on IBM i.  


Thursday, August 24, 2023

Share & Communicate your SQL with Style

The Run SQL Scripts tool provided by IBM i Access Client Solutions (ACS) does a great job of making an SQL statement more understandable with its color highlighting of SQL keywords and its formatting of the statement text.

I think you would agree that it would be great if that same highlighting and formatting could ride along with your SQL statement text to make it clearer to your peers when sharing your SQL via email, presentations, design docs, etc. This actually is possible - assuming that you have ACS 1.1.9.2 or later installed on your workstation.

The Run SQL Scripts auto-prompting support for host variables and parameter markers got all the fanfare when ACS 1.1.9.2 was released, but this version of ACS also delivered Rich Text Format copy capabilities. Without this new capability, the following figure shows how the SQL syntax highlighting disappears when an SQL statement text is copied from Run SQL Scripts to a word processing tool or an email.







Now that the Run SQL Scripts copy captures the rich text format (i.e., color highlighting) associated with your SQL statement, you’ll be able to choose the highlighted Paste Option on the left as shown below to preserve the source statement format when performing a paste operation.














Once you select the  highlighted Keep Source Formatting paste option in the prior figure, the SQL will be transformed back to the highlighted and formatted SQL statement  as shown below. It's the same stylish presentation as Run SQL Scripts, but available in a different medium.









Hopefully, it’s now clear to how newer versions of ACS enable you to communicate and share your SQL statement text in a more comprehensible format.

Wednesday, July 19, 2023

Pivoting with SQL

Just like last month’s entry, the roots for this entry were formed from a recent discussion on an IBM TechXChange Community - the Db2 for i SQL Community. If you’re not yet part of this online community, it’s a good resource for getting your Db2 for i & SQL-related questions answered.

The discussion in this community was regarding two tables like the following which contained employee data and deductions data for employees.


An IBM i developer was looking for SQL support which would allow the deduction details to be returned alongside the employee data in the same row. Essentially, their goal was to take the data in these two tables above and produce the following result set. In their situation, an employee could have a maximum of four deductions. 

This transformation of the data that moves values from a single column into multiple columns is often referred to as a pivot operation. While Db2 for i SQL support doesn’t include a pivot operator, it is possible to perform this type of transformation using a combination of rich Db2 for i SQL syntax.

The first step is associating a unique identifier with each employee’s deduction using the ROW_NUMBER specification as shown in this query.

SELECT EmpID, Deductions,
ROW_NUMBER() OVER (PARTITION BY EmpID) AS seqnum FROM deduction

This query converts the data in the Deduction table into the following output.  The Partition By keyword on the Row_Number specification is what causes the seqnum column (i.e., the unique identifier) value to reset to 1 when it encounters the deductions for a different employee.




Now that each employee’s deduction has a unique identifier associated with it, the next step is getting those individual deduction column values into a single row for each employee. The Group By EmpID clause in the following query is used to consolidate all of the deduction entries for an employee into a single result row.


SELECT EmpID,
       MAX(CASE WHEN seqnum = 1 THEN Deductions END) AS Deduct1,
       MAX(CASE WHEN seqnum = 2 THEN Deductions END) AS Deduct2,
       MAX(CASE WHEN seqnum = 3 THEN Deductions END) AS Deduct3,
       MAX(CASE WHEN seqnum = 4 THEN Deductions END) AS Deduct4
   FROM (SELECT EmpID, Deductions,
ROW_NUMBER() OVER (PARTITION BY EmpID) AS seqnum FROM deduction) GROUP BY EmpID)

 As the group of deductions for an individual employee is processed, a Case expression is used to perform the pivot of the employee’s deductions values into separate output columns. The unique identifier (seqnum) for a deduction is checked to see which output column (Deduct1, Deduct2, Deduct3, Deduct4) will be assigned the value of one of the employee’s deduction values. The MAX function is used only as a trick to get the deduction output columns into the result set - the result set can only contain grouping columns and aggregate functions because the outer Select statement is using a grouping clause.  This grouping query produces the following result set.




As you can see in the complete query solution that follows, this grouping query is encapsulated within a common table expression (CTE) named pivot_deductions. The last step remaining step is to join the pivoted deductions with the employee table, so the employee name can be part of the the final pivoted result set. 


WITH pivot_deductions AS
  SELECT EmpID,
       MAX(CASE WHEN seqnum = 1 THEN Deductions END) AS Deduct1,
       MAX(CASE WHEN seqnum = 2 THEN Deductions END) AS Deduct2,
       MAX(CASE WHEN seqnum = 3 THEN Deductions END) AS Deduct3,
       MAX(CASE WHEN seqnum = 4 THEN Deductions END) AS Deduct4
   FROM (SELECT EmpID, Deductions,
ROW_NUMBER() OVER (PARTITION BY EmpID) AS seqnum FROM deduction) GROUP BY EmpID) SELECT e.EmpID, Name, Deduct1, Deduct2, Deduct3, Deduct4 FROM employee e INNER JOIN pivot_deductions p ON e.EmpID = p.EmpID

Hopefully, this article will give you confidence to leverage some of the SQL functionality highlighted here to more easily perform your own data transformations whether they involve pivoting or not.  

Thursday, June 22, 2023

The Amazing & Disappearing Plan Cache

This month I decided to continue with a Plan Cache-related topic as a result of a recent discussion thread on IPL frequency on the IBM i Global TechXchange Community.  System IPLs are relevant to the Db2 for i Plan Cache used by the SQL Query Engine (SQE) because it’s a temporary object that gets recreated each time the system is restarted. Before diving into IPL considerations for the Plan Cache, let’s first focus on how SQE uses the Plan Cache and the benefits it provides. 

As I highlighted in my January entry, the Plan Cache is used by SQE to store the access plans (or query plans) created by the query optimizer. An access plan must be in place before a query can be run since it contains the details on what methods (e.g., table scan, index probe, etc.) and objects (e.g., index) will be used by Db2 during the runtime execution of a query. SQE’s usage of the Plan Cache as a single repository for all access plans on the system benefits IBM i clients in several different ways.

First, a centralized repository reduces the amount of system resources used to build query plans. If you had the same SQL request run by different programs, the Classic Query Engine (CQE) had to create and store a separate access plan for each program. With SQE, one copy of the access plan can be created and shared across multiple programs. 

Second, the Plan Cache enables a tremendous Db2 performance toolset with no overhead. Usage of plans from the Plan Cache is part of the normal SQE query execution process, so there’s no additional tool that must be run to collect data for detailed performance analysis with Visual Explain. The IBM i Access Client Solutions (ACS) SQL Performance Center interface shown below makes it fast and simple to perform analysis on a query plan. Just hit the highlighted “Show Statements” button and find the query that needs performance analysis.









Prior to the Plan Cache, Visual Explain analysis could only be performed if you had first collected database monitor data. This requirement was problematic because of the noticeable overhead caused by the database monitor collection process. This overhead meant that you couldn’t just keep a database monitor always running on your production system. When a query performance problem arose on your production system, Visual Explain could not be used to analyze the query because the required performance data wasn’t available. Then, when you went to collect the requisite database monitor data, you ran the risk of negatively impacting the performance of other workloads on your system. The Plan Cache automatically contains the data required to perform detailed analysis with Visual Explain without adding extra overhead to your system.

Lastly, the Plan Cache’s centralized plan repository provides a foundation for self-learning query optimization techniques. One of those self-learning query optimization techniques is Adaptive Query Processing or AQP for short. The ACS SQL Performance Center displays a Plan Cache property, Number of Plans Rebuilt due to AQP, where you can see how often this self-learning technology automatically has tuned the performance of queries on your system. 

Now that you know about the amazing benefits the Plan Cache provides, hopefully it’s also clearer how these great benefits are somewhat negated by frequent system IPLs.

The biggest issue is slower performance on Monday morning after a weekend featuring a system IPL. An empty Plan Cache has the potential to add to the Monday blues for your end users since all the query plans that we’re being reused by your applications and reports on Friday have to be rebuilt by the Db2 query optimizer on Monday morning when users start running your applications and reports. Building access plans takes time and system resources which can lead to sluggish system performance. 

This performance slowdown can be further compounded if some of your queries had been auto-tuned by SQE with the creation of maintained temporary indexes (MTIs). These temporary indexes obviously also pull a disappearing act when an IPL is performed. A query which previously relied on a temporary index will run slower post IPL until SQE makes the decision to auto-tune the query again. In addition, the recreation of these temporary indexes can cause additional overhead on your production system.

So, what actions can you take to minimize the performance impact of an IPL causing your Plan Cache to disappear?

If your system is frequently IPLed, then start by determining if frequent IPLs are truly required. If  the answer is we’ve always done it that way - that’s a good indicator you should keep investigating. When the AS/400 was first launched, weekly IPLs were common because it was possible for the system to run out of temporary addresses. However, that launch was 35 years ago! Even though IBM has delivered enhancements over the years including the switch to 64-bit RISC processors in 1995 which significantly expanded the temporary address support, our IBM Technology Expert Labs team encounters a significant number of clients still employing weekly IPLs when we’re helping them with SQL performance analysis and tuning. If your company is hesitant to change this old practice, make a small change in IPL frequency and evaluate the impact - for instance, move from weekly IPLs to biweekly or monthly IPLs. 

Regardless of the IPL frequency, proactively replacing the MTIs on your system can minimize the post IPL query performance blues. In 2022, the Db2 for i development team delivered the MTI_INFO service that makes it really easy to identify the temporary indexes currently on your system and  to replace them with permanent indexes. I’d recommend modifying your IPL preparation procedure to include using the MTI_INFO service to replace the temporary indexes with permanent indexes before they disappear at IPL time. The MTI_INFO service is supported back to the IBM i 7.3 release.

The final action you can take is to alter your post IPL procedures to include a warmup of key applications and reports. After an IPL on the weekend, set up a process to run some of your key applications and reports prior to Monday morning. This warmup action will pre-populate some of the Plan Cache to lessen the performance pain when end users ramp up system activity on Monday morning.

Hopefully, one of these actions or a combination of them will help you maximize the performance benefits that the Plan Cache can provide to your application and reports. Please reach out, if you need assistance learning how to leverage Visual Explain and the SQL Performance Center to manage and tune query performance on your systems.

Wednesday, May 17, 2023

A Followup on Snapshot Scheduling

 

A colleague recently pointed out that while my Snapshot Scheduling blog entry was on target, it was missing a few details for a portion of the IBM i install base. Specifically, those IBM i clients that are using Independent Disk Pools  - also known as Independent Auxiliary Storage Pools (ASPs) or IASPs for short. IASP usage is on the rise by IBM i customers since they provide the foundation for IBM PowerHA.

In the prior blog entry, I advocated the use of the DUMP_PLAN_CACHE service for creating Plan Cache snapshots on your production system on a regular basis. The detail that I did not include regarding this service and IASPs is this - by default, the DUMP_PLAN_CACHE service only copies Plan Cache entries for those queries referencing tables in the System ASP.  That means if you had a critical query like the following and DBLIB resided in an IASP, then the Plan Cache snapshot would contain no record of this query. 

SELECT COUNT(*) FROM dblib.orders WHERE custid = 123

The snapshot would only contain queries that reference objects that reside in libraries and schemas that are housed in the System ASP. This default behavior of the DUMP_PLAN_CACHE service exactly matches the default behavior when you view the live Plan Cache entries with the IBM i Access Client Solutions (ACS) SQL Performance Center. 

The SQL Performance Center Database pull-down menu highlighted in the following figure defaults to the System ASP. Thus, clicking on the Show Statements button to analyze Plan Cache entries will result in a list of those queries that only reference objects that reside in libraries that are stored in the System ASP. If you want to view Plan Cache entries for queries referencing tables that reside in an IASP, then you’ll first need to select the IASP name from the highlighted Database pull-down menu.







On a side note, the Plan Cache Properties shown in this figure are summary metrics that include all queries regardless of which ASP the queried objects resides in.

Obviously, there’s no graphical interface for the DUMP_PLAN_CACHE service, so you’re probably wondering how that service can be used to capture all of the entries in the Plan Cache. One way to ensure that all Plan Cache entries are written to the snapshot is to use the Set ASP Group (SETASPGRP) CL command featured in the following CL script. 

RUNSQL SQL('CALL QSYS2.DUMP_PLAN_CACHE(''SOMELIB'',''SNAP1'')')

SETASPGRP ASPGRP(IASPNN)

RUNSQL SQL('CALL QSYS2.DUMP_PLAN_CACHE (''SOMELIB'',''SNAP1'')')

The first call to the DUMP_PLAN_CACHE service will dump the plan cache entries related to System ASP queries. After that dump has completed, the SETASPGRP command is run to reset the job to the independent ASP named IASPNN.  This ASP group reset causes the second DUMP_PLAN_CACHE service invocation to dump the plan cache entries related to the specified IASP. 

Take note in this CL script that the second DUMP_PLAN_CACHE request also uses the same snapshot name to ensure that all of the plan cache entries end up in a single Plan Cache Snapshot object. 

Now, you have all the details needed to guarantee that even environments utilizing IASPs can have scheduled Plan Cache snapshots that capture ALL of your queries.

Wednesday, April 12, 2023

Spring Forward with New Db2 for i Features

Spring Forward is a phrase that is often used in the United States to remind people which direction to move their clocks when Daylight Savings Time begins. I’m not going to debate Daylight Savings Time here since it’s a highly charged issue for many people. However, there is no disputing that many of us associate springtime with an adjustment to our clocks. 

Many in the IBM i world are also accustomed to IBM announcing new refreshes or releases for their favorite system around this time of the year. Spring 2023 follows that pattern with the recent announcement of Technology Refreshes (TRs) for the IBM i 7.4 and IBM i 7.5 releases. Like usual, these refreshes include new Db2 for i functionality to help you move your applications and databases forward.

Here are some of my favorite new Db2 capabilities in the recently announced TRs:

Those of you that have already upgraded to IBM i 7.5 will benefit from the extension of the RESTRICT ON DROP support. The RESTRICT ON DROP support initially could be used to prevent the accidental deletion of Db2 tables and physical files. Tables or physical files created with this option cannot be deleted with the SQL DROP statement or the DLTF CL command until the RESTRICT ON DROP setting is removed. Now, the RESTRICT ON DROP support can be used to prevent the accidental deletion of stored procedures and user-defined functions. This new support can be used with both the SQL and external flavor of stored procedures & functions.

Geospatial Analytics was a big addition to Db2 for i in 2022 and that support was also enhanced with a new scalar function - ST_GEOHASHVALUE.  The use of geohash values is a great way to speed up the performance of many solutions which integrates the Geospatial Analytics support.

As you’ve come to expect, new and enhanced IBM i Services are often found in IBM i TRs and that holds true for the 7.4 and 7.5 TRs announced this week. The new RDB_ENTRY_INFO view is a great addition from a Db2 perspective. Now, SQL can be used to easily retrieve your database directory entry details instead of having to run the Display Relational Database Directory Entries (DSPRDBDIRE) CL command.

IBM i Access Client Solutions (ACS) is a key tool for the support and management of your Db2 for i databases. Not surprisingly, it also includes several new enhancements that make working with SQL and Db2 for i easier. The biggest enhancement is the prompting support for Run SQL Scripts. Frequently, the SQL statements run by applications reference host variable or parameter markers like the following statements:

SELECT COUNT(*) FROM qsys2.systables WHERE table_schema = :H 

SELECT orderkey, quantity  FROM orders 
  WHERE shipdate BETWEEN ? AND ?

While this is a great SQL coding practice, it does make life difficult for anyone that wants to run these SQL requests from ACS Run SQL Scripts in order to analyze performance or debug an issue. Before these types of SQL statements can be run, all the host variables and parameter markers needed to be manually replaced with literal values. 

This cumbersome, manual replacement process has been eliminated with the new Run SQL Scripts prompting support. All you need to do is copy and paste the SQL statement text into Run SQL Scripts. When you go to run the SQL statement, ACS will automatically detect that there are host variables or parameter markers that need to be replaced and will prompt you for the replacement values as shown below.







You just enter the appropriate values into the input field(s) and hit the “OK” button. ACS will then run the SQL request with your input values.  Notice that the right-hand side of these two input windows include the data type definition of the column being compared (or assigned) which make its easier for you to supply a compatible replacement value.

Again, these are just a few of the highlights from the latest IBM i TRs, so make sure you take the time to review the complete list to see if there are other new features that can make your life easier and move your IBM i applications forward!



Friday, March 17, 2023

Shared CTEs - They're Here...

They’re Here is a famous quote from Poltergeist, a horror movie from the 1980s. In this movie, spirits visit a family’s home and appear playful at first. These spirits, however, do not remain cordial and end up wreaking havoc on the family. This turn of events shouldn’t be too much of a surprise given that this film is a horror movie.   

Last June, I had given everyone a heads up about a pending Db2 for i change for Shared Common Table Expressions (CTEs) that would be coming soon to visit your systems. Well, to borrow the quote from Poltergeist… They’re Here. The implementation changes to make the Db2 for i Shared CTE support compliant with the SQL Standard are now part of the IBM i 7.4 & 7.5 releases. This implementation change is required to eliminate inconsistent results which were a possibility with the prior non-compliant implementation. These changes were part of the IBM i 7.5 GA code delivered in May 2022. For the IBM i 7.4 release, the changes were introduced with the 7.4 Database Group PTF level #23 which was delivered in December 2022.

While these Shared CTE implementation changes are not to be feared like the evil spirits in the movie, they should not be ignored. The reason that they should not be ignored is that these changes could make some of your queries with Shared CTEs run faster or could make some of your queries using Shared CTEs run slower. Unfortunately, recent client interactions have made it clear to the IBM team that some clients have been ignoring this pending implementation change despite the warnings raised in this blog and the IBM i Memo to Users. 

Before delivering the Shared CTE implementation change, the IBM i development team did a great job delivering flagging support for the IBM i 7.3 and 7.4 releases which makes it easy to use an SQL Plan Cache Snapshot or SQL Monitor to identify your SQL requests that might be impacted by this change. Regrettably, it appears few clients have used this flagging support to proactively identify and evaluate queries using a Shared CTE.

A query with a Shared CTE running slower doesn’t sound like that big of a threat. However, if that same query is run frequently and processes a large amount of data, there is the potential for your overall system performance being negatively impacted. In fact, IBM has seen clients experience system performance issues due to queries affected by the Shared CTE implementation change. In these cases, some rewriting and tuning of the queries was necessary.

Instead of ignoring this pending performance behavior change in your queries, the following proactive actions are recommended:

  • Before updating your 7.4 Database Group PTF level or upgrading to IBM i 7.4 or 7.5, use the flagging support to identify which SQL statements on your system use a Shared CTE.
  • Before updating your 7.4 Database Group PTF level or upgrading to IBM i 7.4 or 7.5, simulate the Shared CTE coding change by adding the following predicate, AND RAND() IS NOT NULL, to your Shared CTE definition.  Rerun the query after making this change and measure the performance.
  • If performance is not acceptable, try to improve your query performance by rewriting it or tuning it with new indexes. The Db2 team in IBM Technology Expert Labs can help with this!
  •  When your systems get updated with new IBM i 7.4 or 7.5 code, make sure the following PTFs, MF70861 (7.4) & MF70868 (7.5), are applied to ensure you have the latest version of the Shared CTE code. As you hopefully gather from this update, this implementation change is significant - so it would be advantageous to stay current with the latest PTFs for Shared CTEs.

·        As the old saying goes, an ounce of prevention is worth a pound of cure.  Please reach out if you need help with your prevention plan.