Tuesday, January 17, 2023

Manage Data Over Time with SQL Server MERGE Statement

This article is part of Greg Larsen's continuing series on Learning T-SQL. To see all 8 items in the series, click here.

The basic MERGE statement

The MERGE statement was introduced with SQL Server 2008. It provides a single statement to perform UPDATE, INSERT and/or DELETE operations against a target table. The syntax for the basic MERGE statement that will be discussed, in this article, can be found in Figure 1:

MERGE
[ INTO ] <target_table>

USING <table_source> [ [ AS ] table_alias ]
   ON <merge_search_condition>

[ WHEN MATCHED [ AND <clause_search_condition> ]
  THEN <merge_matched> ] [ ...n ]

[ WHEN NOT MATCHED [ BY TARGET ] [ AND <clause_search_condition> ]
  THEN <merge_not_matched> ]

[ WHEN NOT MATCHED BY SOURCE [ AND <clause_search_condition> ]
  THEN <merge_matched> ] [ ...n ];

Figure 1: Basic Merge Statement

Where:

  • target_table – identifies the table or view from which rows will be matched, so the appropriate update, insert, or delete actions can be performed based on the matching criteria.
  • table_source –identifies the data source rows for which target_table rows are matched.
  • merge_search_condition – identifies the join criteria for matching target_table rows, with the source_table rows.
  • merge_matched – identifies either an UPDATE or DELETE statement to issue based on matching criteria.
  • merged_no_matched – identifies the INSERT statement to issue for each row not matched.
  • clause_search_condition – identifies any valid search condition.

For the complete syntax of the MERGE statement refer to the Microsoft documentation that can be found here.

To better understand how the MERGE statement maintains a target table, a few merge examples will be provided, in the sections below. But first some test data needs to be created.

Creating Initial Test Data

To show how the MERGE statement works a new database will be created. The new database will contain tables that I will use as a target and source for the examples, which will be populated with the initial test data. The examples in this article will show how a fictious manufacturing company named Widget Magic keeps this data synchronized using different MERGE examples.

The code in Listing 1 is used to create a database, the target and source table, and populates these tables with some initial rows of data. Note if you don’t want to create a new database the source and target tables can be created in the tempdb database.

-- Create repository for products
CREATE DATABASE MergeDB
GO

USE MergeDB;

SET NOCOUNT ON;

CREATE TABLE dbo.ProductInventory (
   ID int identity, 
   ProductName varchar(20),
   Qty int);

CREATE TABLE dbo.ProductRun(
   RunNum int,
   ProductName varchar(20), 
   Qty int);
-- Product Run #1

USE MergeDB;
GO

INSERT INTO dbo.ProductRun (RunNum, ProductName, Qty) VALUES
   (1,'Widget Basic',5), 
   (1,'Widget Pro',5);
GO

INSERT INTO dbo.ProductInventory (ProductName, Qty) VALUES
   ('Widget Basic',5),
   ('Widget Pro', 5);
GO

Listing 1: Create repository for products

In Listing 1 two tables are created: dbo.ProductInventory and dbo.ProductRun. The dbo.ProductInventory table tracks the inventory of products created by Widget Magic company. Whereas, the dbo.ProductRun table will be used to keep track of the products produced from each product run cycle. The rows of data inserted into these two tables represents the products produced from the first product run of widget products. During that first product run 5 Widget Basic and 5 Widget Pro items were produced.

For the purpose of this article the dbo.ProductInventory table will be used as the target table of the MERGE examples. Whereas, records from the dbo.ProductRun table will be used as the source table records.

Merge Example #1 – Inserting/Updating Using MERGE Statement

In order to show how the MERGE statement works to maintain the dbo.ProductInventory table, the Widget Magic company first needs to have a second product run cycle. The second run produced 5 more Widget Pro items and introduced a new product called Widget Super Pro, of which 5 are produced

The code in Listing 2 inserts two new rows into the dbo.ProductRun table to represent the new products produced by this second product run.

-- Product Run #2
USE MergeDB;
GO

INSERT INTO dbo.ProductRun (RunNum, ProductName, Qty) VALUES
   (2, 'Widget Pro',5),
   (2, 'Widget Super Pro',5);
GO

Listing 2: Inserting Production Run #2 Rows

To update the dbo.ProductInventory table, based on the products manufactured during the second product run, the MERGE statement in Listing 3 will be run.

-- Merge Example #1 
USE MergeDB;
GO

MERGE dbo.ProductInventory AS T  
USING (SELECT * FROM dbo.ProductRun WHERE RunNum = 2) AS S 
ON T.ProductName = S.ProductName 
-- Perform UPDATE when rows are matched 
-- between source and target
WHEN MATCHED THEN 
   UPDATE SET T.Qty = T.Qty + S.Qty
-- Perform INSERT when rows are not matched 
--between source and target
WHEN NOT MATCHED BY TARGET THEN 
   INSERT (ProductName,Qty) VALUES (S.ProductName, S.Qty);

-- Review Inventory
SELECT * FROM dbo.ProductInventory;
GO

Listing 3: Merge Example #2 – Inserting/Updating ProductInventory table

Report 1 shows the rows in the dbo.ProductInventory table after the MERGE statement was executed.

Report 2: Output of SELECT statement in Listing 5

The MERGE statement in Listing 3 compares the dbo.ProductInventory records, with the widgets products produced during the second product run. The dbo.ProductInventory table is the target table, and the rows returned from the subquery “SELECT * FROM dbo.ProductRun WHERE ProductRun = 2” identifies the source rows. The target and source rows are joined based on the merge_search_condition specified with the “ON” clause, which in this case was “T.ProductName = S.ProductName”.

A word of caution here, target table columns should only be compared with source columns. Do not use any target table columns to filter out rows as part of the “ON” clause. Doing so could produce unexpected or incorrect results.

When rows are matched between target and source rows, SQL Server assigns a matching condition for each row, based on the merge_search_condition. When this condition equates to true, the source row is known as a MATCHED with a target row. When the merge search condition is false the source table row is considered “NOT MATCHED”. NOT MATCHED then is be broken into two different conditions “NOT MATCHED BY TARGET” and “NOT MATCHED BY SOURCE”.

The “NOT MATCHED BY TARGET” in this example means a row exists in the source table that did not match a row in table based on the join criteria. Whereas the “NOT MATCHED BY SOURCE” condition means that a row exists in the target table that has no matching rows in the source table (look at Example 2 for to see a “NOT MATCHED BY SOURCE” example). Additionally, when both source and target table comparison columns contain NULL values, the matching value is considered “NOT MATCHED” for both target and source tables.

For each row in source table from second product run, that got a MATCHED condition an UPDATE operation against the target table was performed. The UPDATE operation increases the inventory value of the Qty column, on the matched target row, based on the Qty column value, of the matching row in the source table.

An INSERT operation was performed for each source row, from the second product run that got a NOT MATCHED BY TARGET condition. The INSERT operation uses the source table’s ProductName and Qty values to insert a new rows into the target table for each new product produced.

Report 2 shows that 5 more Widget Pro and Widget Super Pro items were added to the dbo.ProductInventory table. This MERGE statement showed how to insert and update rows into the target table, based on a matching condition with the source table. The MERGE statement can also perform DELETE statements.

Merge Example #2 – Inserting/Updating/Deleting using MERGE Statement

The Widget Magic company so far has had two different product runs of their widget products. The Widget Basic product has not been well received, as the product has been demonstrated to potential customers. Therefore management has decided that this product should be removed from the inventory, once the next product run has completed.

For the third product run, only the Widget Pro, and Widget Super Pro items are produced. The code in Listing 6 inserts these products from product run #3 into the dbo.ProductRun table.

-- Product Run #3
USE MergeDB;
GO

INSERT INTO dbo.ProductRun (RunNum, ProductName, Qty) VALUES
   (3, 'Widget Pro',100),
   (3, 'Widget Super Pro',50);
GO

Listing 4: Inserting Product Run #3 Rows

To show how the MERGE statement can insert, update, and delete rows from a target table, the code in Listing 5 merges will be run.

-- Merge Example #2 
USE MergeDB;
GO

MERGE dbo.ProductInventory AS T  
USING (SELECT * FROM dbo.ProductRun WHERE RunNum = 3) AS S 
ON T.ProductName = S.ProductName 
AND S.RunNum = 3
-- Perform UPDATE when both target and source MATCHED 
WHEN MATCHED THEN 
   UPDATE SET T.Qty = T.Qty + S.Qty
-- Perform INSERT when NOT MATCHED BY SOURCE
WHEN NOT MATCHED BY TARGET THEN 
   INSERT (ProductName,Qty) VALUES (S.ProductName, S.Qty)
-- Perform DELETE when NOT MATCHED BY SOURCE
WHEN NOT MATCHED BY SOURCE THEN
   DELETE;

-- Review Inventory
SELECT * FROM dbo.ProductInventory;
GO

Listing 5: Inserting/Updating/Deleting ProductionInventory table

The code in Listing 5 now contains a third WHEN condition, “NOT MATCHED BY SOURCE”. This WHEN condition is followed when there is a row in the target table that does not exist in the source table. This is the opposite of the insert where there were rows that existed in the source table that did not exist in the target. When no matching rows are found a DELETE statement is executed. Or in this case, the discontinued product name “Widget Basic” will be deleted from the target table.

Additionally, when target and source rows are MATCHED the inventory Qty column of the target table is updated, based on the number of widgets produced during the third product run. The NOT MATCHED BY TARGET condition is not fired because no new products were introduced during the third product run. The resulting rows in the dbo.ProductInventory after Listing 5 is executed, can be seen in Report 3.

Report 3: Output from SELECT statement in Listing 5.

The MERGE example in Listing 5 had single MATCHED, NOT MATCHED BY TARGET and NOT MATCHED BY SOURCE clauses. The MERGE statement can support multiple MATCH and NOT MATCHED conditions, as well be shown in the next example.

MERGE Example 3 – Multiple MATCH and NOT MATCH conditions

To show how multiple MATCH and NOT MATCH conditions can be used on a MERGE statement, some new data management requirements are needed.

The first new requirement is a soft delete. To implement the soft delete the dbo.ProductInventory table needs to be modified to contain a soft delete flag.. Plus the Widget Basic inventory row that was deleted in the last MERGE example, will need to be re-inserted into the changed dbo.ProductInventory table. The code in Listing 6 will implement these two different changes to the target table.

-- Implement Soft Delete Requirements
USE MergeDB
GO

-- Add Soft Delete column
ALTER TABLE dbo.ProductInventory ADD
        ToBeDeleted char(1) NULL
GO

-- Re-introduce Widget Basic product
INSERT INTO dbo.ProductInventory (ProductName, Qty, ToBeDeleted) VALUES
   ('Widget Basic',5,'Y')
GO

Listing 6: Changes needed to implement new soft delete requirements

The second requirement is to perform a hard delete of a dbo.ProductInventory record, if a dbo.ProductRun record is found to have a Qty value of zero (0).

For the fourth product run only the Widget Pro items is produced. Additional a Widget Super Pro record with a Qty value of 0 will be added to the dbo.ProductRun table. This record was added so a hard delete of the dbo.ProductInventory record could be performed. Listing 7 contains the INSERT statements for these two products, for the 4th product run.

-- Product Run #4
USE MergeDB;
GO

INSERT INTO dbo.ProductRun (RunNum, ProductName, Qty) VALUES
   (4, 'Widget Pro',100),
   (4, 'Widget Super Pro',0);
GO

Listing 7: Product Run #4

To implement the two new data processing requirements the MERGE statement in Listing 8 will be used. This statement contains multiple MATCHED and NOT MATCHED BY merge options.

USE MergeDB;
GO

MERGE dbo.ProductInventory AS T  
USING (SELECT * FROM dbo.ProductRun  WHERE RunNum = 4) AS S 
ON T.ProductName = S.ProductName 
WHEN MATCHED and S.Qty = 0 THEN 
   DELETE
WHEN MATCHED THEN
   UPDATE SET T.Qty = T.Qty + S.Qty
WHEN NOT MATCHED BY TARGET AND S.QTY <> 0 THEN 
   INSERT (ProductName,Qty) VALUES (S.ProductName, S.Qty)
WHEN NOT MATCHED BY SOURCE and T.ToBeDeleted = 'Y' THEN
   DELETE
WHEN NOT MATCHED BY SOURCE THEN
   UPDATE SET T.ToBeDeleted = 'Y';

-- Review Inventory
SELECT * FROM dbo.ProductInventory;
GO

Listing 8: Merge data with multiple MATCH and NOT MATCHED conditions

The SELECT statement at the bottom of Listing 8 created the output in Report 4.

Report 4: Output from final SELECT statement in Listing 8.

When there are 2 MATCHED BY clauses the first match clause requires an AND condition. The second MATCHED BY condition is only applied if the first MATCHED BY condition is not met. Additionally, when there are 2 MATCHED BY clauses one must perform an UPDATE and the other a DELETE.

Gotcha’s

Here are a few things that you might run into while using the MERGE statement. The first two were already mentioned, but are worth repeating.

  • Unexpected results can occur if the ON clause tries to filter rows based on target columns.
  • If no rows are returned from the source table when joining the target and source then the UPDATE or DELETE cannot reference a source column because there are no matching rows between target and source.
  • Therefore, care needs to be taken when joining target and source rows, so multiple source rows are not matched with a single target row. This usually means that the join between the target and source data sets needs to be one of equality.

    If more than return more than one source rows is matched then SQL Server will throw the following error:

    Msg 8672, Level 16, State 1, Line 110
    The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.

  • There are limitations to the clauses you can include. For example, when there are two different NOT MATCHED BY SOURCE conditions. When there are two NOT MATCHED BY SOURCE conditions the first one needs to have an AND condition, and the condition can only reference target columns. The second NOT MATCHED BY SOURCE condition is only applied if the first NOT MATCHED BY SOURCE is not met. Also one of the NOT MATCHED BY conditions needs to perform a DELETE action and the other an UPDATE action.

For a complete list of requirements and other considerations when using the MERGE statement please refer to the Microsoft Documentation referenced in The Basic MERGE Statement section above.

Cleanup

If you ran the example code in this article it created the MergeDB database on your test instance of SQL Server. The script in Listing 9 can be used to remove this database from your test instance

USE TempDB

DROP DATABASE MergeDB;
GO

Listing 9: Removing the MergeDB database

Manage Data Over Time Using the Basic MERGE Statement

If you are using SQL Server 2008 or above the MERGE statement is supported. A single MERGE statement can be used to replace individual INSERT, UPDATE, and/or DELETE statements. The MERGE statement is ideal for helping manage source and target tables for complex extract, transform, and load situations. Next time an INSERT, UPDATE and DELETE statements are required to maintain the data in a target table, consider using the MERGE statement, to support these requirements.

 

The post Manage Data Over Time with SQL Server MERGE Statement appeared first on Simple Talk.



from Simple Talk https://ift.tt/vGkbAVf
via

Monday, January 16, 2023

Synapse Serverless: CETAS requires DFS to work

CETAS is the acronym for Create External Table As Select. This allow us to export the result of a select to an external table in different formats, such as PARQUET or CSV.

We can also convert the format from one external table to another. The SELECT used on the CETAS can be an external table query. In this way we would be converting files in a data lake from one format to another. For example, we could convert CSV files to PARQUET.

The following query is an example of CETAS:

CREATE EXTERNAL TABLE csvsampletables
WITH (
      LOCATION = ‘filescsv/’,
      DATA_SOURCE = SynapseSQLwriteable,
      FILE_FORMAT = ParquetFF
)
AS
select *, tradedetail.filepath(1) as datetime,
        tradedetail.filepath(2) as ticks from
OPENROWSET(
        BULK ‘https://ift.tt/3OH76R0;,
        FORMAT=‘CSV’,
        HEADER_ROW=true,
        parser_version=‘2.0’
) AS [tradedetail]

This query has two blob addresses: The SELECT query uses one address, while the create table uses a different address hidden in the Data Source called SynapseSQLWritable.

While making some CETAS tests, I discovered an interesting new behaviour. The following error message was displayed and it was very strange:

Msg 16539, Level 16, State 1, Line 1
Operation failed since the external data source ‘https://ift.tt/8lXYTjS; has underlying storage account that is not in the list of Outbound Firewall Rules on the server. Please add this storage account to the list of Outbound Firewall Rules on your server and retry the operation.

The Solution For CETAS

The error message doesn’t make much sense, because the Synapse Serverless Pool doesn’t have exposed Outbound Firewall Rules. In fact, the root cause and solution for this message is completely different from the message itself: CETAS is not supported using the BLOB protocol, only with the data lake protocol (DFS).

Mind the query using the BLOB protocol: This IS NOT the problem. The query can use the blob protocol with absolutely no problem. The problem is hidden in the data source called SynapseSQLWritetable. We will need to drop this data source and create again using the DFS protocol:

drop external data source [SynapseSQLwriteable]

CREATE EXTERNAL DATA SOURCE [SynapseSQLwriteable] WITH (
         LOCATION = ‘https://ift.tt/nkh4caz;,
         CREDENTIAL = [WorkspaceIdentity]
);GO

Once the data source is replaced, executing the query again it will work.

More About Synapse Serverless

  1. How to query blob storage with SQL using Azure Synapse
  2. How to query private blob storage with SQL and Azure Synapse
  3. Performance of querying blob storage with SQL 

 

The post Synapse Serverless: CETAS requires DFS to work appeared first on Simple Talk.



from Simple Talk https://ift.tt/DbKJVoe
via

Tuesday, January 10, 2023

Index Types in PostgreSQL: Learning PostgreSQL with Grant

As with any other relational data management system (RDBMS), PostgreSQL uses indexes as a mechanism to improve data access. PostgreSQL has a number of different index types, supporting different behaviors and different types of data. In addition, again, similar to other RDBMS, there are properties and behaviors associated with these indexes.

In this article I’m going to go over the different types of indexes and some index behaviors. We’ll get into what the indexes are, how they work, and how best you can apply them within your databases. I’m hoping you’ll develop an understanding of which indexes are likely to work better in each situation.

However, I won’t be covering the indexes in detail. Further, I won’t be going very far into how these indexes affects performance. I’m not yet up on performance tuning within PostgreSQL. That article is quite a way down the track from here. When you know which index to use where, you can then drill down to better understand that index, and how best to measure the performance impacts.

It is important to keep in mind that both your types of data, and your actual queries, that drive the indexes that are going to be best for your databases. This is especially true of PostgreSQL as some of the index types are very focused on specific query patterns.

There are six types of indexes:

  • B-Tree
  • Hash
  • GIST
  • SP-GIST
  • GIN
  • BRIN

Let’s break each of these down and talk about them.

Before we get there though, I’m storing all the scripts I generate for these articles publicly on GitHub. The file to start with is CreateDatabase.sql. You can use the script in SampleData.sql to load in some data.

B-Tree

The name for the B-Tree index within PostgreSQL is a shorthand for a multi-way balanced tree index. Basically, similar to SQL Server, the values of an index are stored on pages in a doubly-linked list. The pages are laid out in a tree, with leaf pages storing the key column data. You define the key column, or columns, in the index definition:

CREATE INDEX radios_radioname ON radio.radios(radio_name);

This default behavior lets you ignore some syntax that you’d do well to start using now, since all the other indexes you create won’t work quite this way:

CREATE INDEX radios_radioname ON radio.radios USING BTREE(radio_name);

USING BTREE tells PostgreSQL what kind of index we want to build. You’ll see other commands in other types of indexes throughout the rest of the article.

This is in part because index names within a given PostgreSQL database are unique That’s a bit of a jump for this old SQL Server person who is used to having duplicate index names since they’re dependent on the table they’re indexing.

You can make a compound key by just adding more columns:

CREATE INDEX radios_radioname_radioid ON radios.radios 
                           USING BTREE(radio_name, radio_id);

The B-tree indexes are the only index type in PostgreSQL to support the UNIQUE definition:

CREATE UNIQUE INDEX radios_radioid_unique ON radio.radios 
                         USING BTREE(radio_id);

This index will ensure that no duplicate values are entered in the index key column or columns.

Another behavior unique to the B-tree index is the ability to store the data in a defined order. This also can help with returning the data in the correct order. Of course, generally speaking, this benefits queries with ORDER BY clauses, although there are also other conditions and circumstances where it helps. Like SQL Server, you can pick and choose whether the values in the key are ascending or descending. You also get to decide if NULL values are stored at the beginning or end of the index. For example, this index will sort the values of the radioname column in a descending order, but put all the NULL values first:

CREATE INDEX radios_radioname ON radio.radios 
                        USING BTREE(radio_name DESC NULLS FIRST);

One thing different from SQL Server is the fact that there is only one type of B-tree index. All tables in PostgreSQL are stored as a heap table. There are not clustered indexes defining data storage. All the B-tree indexes are secondary storage, meaning that the columns defined in the index are what get stored in the index itself. Without getting too deep into performance tuning (which, let’s remember, I’m still not ready to teach), this can lead to performance headaches since access into the heap can be random. So, you can use the INCLUDE command to create a covering index, an index that satisfies the column needs in a query, avoiding extra reads to the heap:

CREATE INDEX radios_radioid ON radio.radios 
                      USING BTREE(radio_id) INCLUDE(radio_name);

PostgreSQL also supports what it calls Partial Indexes which SQL Server calls a Filtered Index:

CREATE INDEX radios_radioname ON radio.radios USING BTREE(radio_name)
WHERE radio_name IS NOT NULL;

In this case, only the values in the radioname column that are not null will be added to the index. You can even use a partial index with the UNIQUE definition, which opens up some interesting possibilities for indexing.

Finally, you can create indexes like this:

CREATE INDEX ON radios (adioed);

However, I didn’t demo that at the start because I think it’s a poor practice. PostgreSQL will name the index for you, which is great. But you could run that script more than one time, getting duplicate indexes. At which point, PostgreSQL will name the index for you, and you’ll end up withing something that looks like this:

That’s the same index, five times. That means five times the storage, five times the maintenance, and five times the overhead. Not to mention a thoroughly confusing looking database. I would not recommend building your indexes in this fashion.

Another example would if you did something like this on one server:

CREATE INDEX ON radios (radioid);
CREATE INDEX ON radios (radio_name);

Followed by this on another server:

CREATE INDEX ON radios (radio_name);
CREATE INDEX ON radios (radioid);

You would end up with different indexes with matching names, causing all sorts of testing and development headaches. Therefore I started by naming my indexes myself. You want to avoid headaches by following simple, straightforward coding practices.

There are quite a few more details to the behavior of B-Tree indexes within PostgreSQL, but this covers the basics.

Hash Indexes

PostgreSQL supports a hash index on any data type. A hash is just the result of a calculation made against the data in the column that will always result in the same value for the same input. The hash stored is a 4-byte value, regardless of the size of the column being indexed. That makes the hash a great choice for larger amounts of data. Think long strings, like a web address. Creating a hash index is about the same as creating a B-Tree:

CREATE INDEX bands_band_name ON radio.bands USING HASH(band_name);

However, there are lot more limits to using a Hash index than there are the B-Tree. First of all, a Hash index can only be created with a single column, ever. Sure, any data type at all, but no compound keys and no INCLUDE for a covering Hash Index.

The biggest issue with Hash indexes is hash collision, when two, nearly, but not quite, identical values get the same hash value. This is exceedingly rare, but it can happen. This is why it’s strongly suggested that Hash indexes only be made for unique, or nearly unique data. The Hash index itself doesn’t support the UNIQUE operator, but it does largely function as if it was dealing with unique values. Depending on your data size and the data within, you may never experience hash collisions. When you do though, it can lead to serious performance issues.

The values of a Hash index are stored in what is called a hash bucket. The bucket has meta data that relates the high and low values stored in the bucket. This helps to make searching for a hash value a fast operation. When there are multiple copies of the hash value, additional checks are made to identify the appropriate value, slowing down access. This is a big part of why it’s suggested that you make Hash indexes only on unique or nearly unique data. A pointer to the heap table is stored along with the hash value itself.

Hash indexes can be partial, so to assist in making them unique, you could add a WHERE clause to the index creation:

CREATE INDEX logs_log_date ON logging.logs USING HASH(log_date)
WHERE log_date > '1/1/2020';

The assumption here being values greater than  ‘1/1/2020' will be more unique, making the index more efficient.

Another difference from the B-Tree index is that the Hash index doesn’t support index-only scans. However, that’s good because you wouldn’t want to see a hash scan, especially in places where collisions are possible because of the overhead that would create. Also, the output from the Hash index isn’t sorted which means the data is returned based on how it gets retrieved, meaning, no ORDER BY clauses. This lack of index scans is a big reason why equality, the = operator, is the only supported operator.

If you search for PostgreSQL Hash indexes online, you might find information suggesting that they shouldn’t be used because they are not written to the Write Ahead Log (WAL). However, that’s quite old information, from version 9 of PostgreSQL. It no longer applies, so if this kind of index can help, go ahead and use it.

GiST

The Generalized Search Tree (GiST) index isn’t really an index as such. Instead, it’s an access method that allows you to define different kinds of indexes in support of different data types and the search operations for those data types. GiST indexes are used for data types that aren’t dealing with ranges or equality like B-Tree or Hash indexes, like geometric data, documents or even images. Also, the GiST indexes are extensible, in fact, the documentation on the GiST index itself is much more focused on the extensibility of the indexes within the GiST access methods. Documentation of GiST behavior is actually scattered around within the various data types that it supports, making it a little difficult to learn how GiST indexes actually work. My advice, as someone just starting the process of learning GiST, would be to not worry about this until you move away from more basic data types like VARCHAR, DATE, etc.

Data within a GiST index is stored in a balanced tree, but the interesting bits are what is stored there. Instead of starting with key values or hash values like the previously discussed indexes, the storage in GiST indexes starts with a predicate. Then, a series of childtree rows that match that predicate are stored under the predicate.

There are already a number of extensions to the GiST indexes within PostgreSQL. So, for example, if you had geographic locations stored as points, you could add an index that will help you locate information in the geometric plane:

create index logs_location on logging.logs using gist(log_location);

The syntax is basically the same. The question is whether or not the data type in question already has functionality within the PostgreSQL indexes. If not, you would have to provide the behavior as well as define the index. That goes far beyond the goal of this article, so we’ll defer it to a later (much later) date.

SP-GIST

The Space Partitioned GiST, or SP-GIST is quite a lot like a GiST index in that it’s built to support a completely customizable set of data. In this case, the function is similar to a GiST index, but, the storage is partitioned so that data that lends itself to grouping through partitioning is going to benefit more from an SP-GIST index, as a SQL Server DBA, think, partition elimination. The data types supported out of the box are pretty similar to GiST, including geometric data like my example above. In fact, in this case, I’d probably pick that again for the syntax example:

create index logs_location on logging.logs using spgist(log_location);

The most interesting aspect of both GiST and SP-GIST is the extensibility. I’m not getting into that here. I’m still learning how to query these things. However, another interesting aspect is how GiST is focused first on operations, while SP-GIST is certainly focused on operations, but it’s the partitioning of the data that’s going to be the determining factor for this to be a superior choice when choosing indexes.

GIN

A Generalized Inverted Index (GIN) is effectively indexing for arrays. PostgreSQL has a number of different array data types. We can argue over whether or not arrays are an appropriate way to store data, the fact is, arrays within PostgreSQL work pretty well and offer up quite a bit of functionality. Plus, everyone is storing data in JSON or YAML. So you’re going to see array data types in use. Why not find a way to make your array faster?

The GIN index is effectively just a B-Tree index with a few wrinkles. The real interest is down at the page level. Instead of storing a key value and a tuple identifier (TID), the location on the heap where the data is stored, you get what is called a posting list. This is a list of all the values that match the key, and then a pointer to the TID. Although, that can get a little more complicated because as you get more and more duplicate values, you may get what is called a posting tree. This is, effectively, a way to extend a page into a set of pages, all of which have the TID value, a kind of B-Tree inside the B-Tree.

While arrays, especially JSON, is probably the primary purpose of the GIN index, you can also use it for full text searches. The same concepts apply as if you were looking through an array. After all, a big text document can be thought of as just a big array of text.

I currently don’t have a full text column in my sample database, so we’ll just index one of the arrays:

create index parksontheair_contacts on logging.parksontheair 
                                              using GIN(contacts);

You can’t use INCLUDE columns because nothing is getting stored at the page level except the PID or the posting list. You can have a multi-column GIN index through, which will make the index much more selective at the key level, while making it quite a bit bigger at the leaf level. In fact, the one big weakness that GIN indexes seem to have universally acknowledged is that they are slow when it comes to UPDATE statements. There are several workarounds, which I’m still not prepared to understand, let alone explain, that can help to mitigate this issue. For more information, check out this introduction.

BRIN

The Block Range Index (BRIN) is for storing ordered data range values, think dates. So when you have naturally grouped data that is likely to be returned as a set, postal codes come to mind, you have an index that is going to help you out. Further, when you’re trying to eliminate sets, say, give me dates less than a certain value, again, the BRIN index can help you out. Just remember, it is very much about ranges to data, not individual point lookup values which are better suited to a B-Tree index.

So, if you’re looking at range queries, BRIN is your friend. I know that a B-Tree can support them too, but, within limited types of queries, again, think ordered sets, BRIN not only outperforms the B-Tree, but usually takes up about 1% of the space. You read that correctly, a 99% space saving. Approximately. All the tests I’ve seen with large data sets bears this out.

The syntax is not going to shock you:

create index logs_log_date on logging.logs using BRIN(logs_log_date);

Since logs are always going to be, for the most part, entered in order, and accessed by date, this proves to be a useful index.

My editor, Louis Davidson, correctly pointed out, to a degree, the BRIN index is sort of like a clustered B-Tree index in SQL Server. The similarities are clear, the order of the data, and therefore where you start a seek or a scan, is determined by the index. The key difference is still the fact that this index doesn’t determine data storage. The data is still back in the heap.

Conclusion

To really see the benefits of indexes, you’re going to want to see examples. However, I’m still just scratching the surface on my learning of PostgreSQL. I’m just not ready to tell you what’s happening in an EXPLAIN plan yet. However, just talking about the types of data and queries supported does give you some indications as to how an index can benefit behaviors within PostgreSQL. As with other database systems, you can add more than one index to a given table to assist in performance. Just know that, as with other database systems, this can lead to additional overhead in terms of storage and processing as the data gets changed over time.

The post Index Types in PostgreSQL: Learning PostgreSQL with Grant appeared first on Simple Talk.



from Simple Talk https://ift.tt/DrFLTMg
via

Friday, January 6, 2023

Introducing the MySQL common table expression

This article is part of Robert Sheldon's continuing series on Learning MySQL. To see all 10 items in the series, click here.

As with many relational database management systems, MySQL provides a variety of methods for combining data in a data manipulation language (DML) statement. You can join multiple tables in a single query or add subqueries that pull data in from other tables. You can also access views and temporary tables from within a statement, often along with permanent tables.

MySQL also offers another valuable tool for working with data—the common table expression (CTE). A CTE is a named result set that you define in a WITH clause. The WITH clause is associated with a single DML statement but is created outside the statement. However, only that statement can access the result set.

In some cases, you can include a CTE with a SELECT statement that is embedded in another statement, as in the case of a subquery or a DELETE…SELECT statement. But even then, the WITH clause is defined outside of that SELECT statement, and only that SELECT statement can access the result set.

One way to think of a CTE is as a type of view with a very limited scope (one statement). Another way to think of a CTE is as a type of named subquery that is defined in a clause separate from the main query. However, a CTE is neither of these, and in this article, I explain how the CTE works and walk you through a number of examples that demonstrate the different ways you can use them to retrieve data.

Note: the examples use the tables and data that is created in the last section of the article titled: “Appendix: Preparing the demo objects and data”.

Getting started with common table expressions

A common table expression is defined inside a WITH clause. The clause precedes the main DML statement, which is sometimes referred to as the top-level statement. In addition, the clause can contain one or more CTE definitions, as shown in the following syntax:

WITH [RECURSIVE]
  cte_name [(col_name [, col_name] ...)] AS (select_query)
  [, cte_name [(col_name [, col_name] ...)] AS (select_query)] ...
top_level_statement;

If the WITH clause contains more than one CTE, you must separate them with commas, and you must assign a unique name to each CTE, although this applies only within the context of the WITH clause. For example, two SELECT statements can include CTEs with the same name because a CTE is limited to the scope of its associated top-level statement.

The CTE name is followed by one or more optional column names, then the AS keyword, and finally a SELECT query enclosed in parentheses. If you specify column names, their number must match the number of columns returned by the SELECT query. If you don’t specify column names, the column names returned by the SELECT query are used.

Common table expressions are typically used with SELECT statements. However, you can also use them with UPDATE and DELETE statements, following the same syntax as shown above. In addition, you can include CTEs with your subqueries when passing them into your outer statements. You can also use CTEs in statements that support the use of SELECT as part of the statement definition. For example, you can add a WITH clause to the SELECT query in an INSERT…SELECT statement or in a CREATE TABLE…SELECT statement.

For this article, I focus primarily on creating CTEs that use SELECT statements as their top-level statements because this is the most common way to use a CTE. This approach is also a good way to start learning about CTEs without putting any data at risk. You can then apply the fundamental principles you learn here to other types of statements as you become more comfortable with how CTEs work.

With that in mind, let’s start with a simple example. The following SELECT statement includes a WITH clause that defines a CTE named planes:

WITH planes AS
  (SELECT plane, engine_count, max_weight
  FROM airplanes WHERE engine_type = 'jet');

SELECT plane, max_weight FROM planes
ORDER BY max_weight DESC;

The SELECT query in the CTE retrieves all the planes in the airplanes table that have jet as the engine_type. The CTE’s result set is made up of the data returned by the SELECT query and can be accessed by the top-level SELECT statement.

The top-level statement retrieves the data directly from the CTE, similar to how a statement might retrieve data from a view. The main difference is that the view definition is persisted to the database and can be used by anyone with adequate privileges. The CTE, on the other hand, has a very limited scope and can be accessed only within the context of the top-level statement.

In this case, the top-level SELECT statement retrieves only the plane and max_weight columns from the CTE and orders the results by the max_weight column, in descending order. The following figure shows the results returned by the statement.

Of course, you can easily achieve the same results without the use of a CTE by querying the airplanes table directly:

SELECT plane, max_weight 
FROM airplanes
WHERE engine_type = 'jet'
ORDER BY max_weight DESC;

However, I wanted to demonstrate the basic components that go into a CTE and how you can access that CTE from within the top-level SELECT statement. Both the CTE and top-level statement can certainly be much more complex—and usually are—but the principles remain the same.

Working with CTEs in the top-level SELECT statement

As mentioned earlier, a CTE is basically a named result set. When you query the CTE from within the top-level statement, the data is returned in a tabular format, similar to what you get when you query a view, permanent table, temporary table, or derived table (such as that produced by a subquery in a SELECT statement’s FROM clause). This means that you can work with the CTE in much the same way as you can those other object types. For example, one common approach to referencing a CTE within the top-level query is to join it with another table, as in the following example:

WITH mfcs AS
  (SELECT manufacturer_id, manufacturer FROM manufacturers)
SELECT a.plane, m.manufacturer, a.max_weight
FROM airplanes a INNER JOIN mfcs m
  ON a.manufacturer_id = m.manufacturer_id
WHERE a.engine_type = 'jet'
ORDER BY a.max_weight DESC;

The WITH clause defines a single CTE named mfcs. The CTE’s SELECT query returns the manufacturer_id and manufacturer values from the manufacturers table. The top-level SELECT statement then joins the airplanes table to the mfcs CTE, based on the manufacturer_id column in each one. The following figure shows the statement’s results.

As this example demonstrates, you can treat the CTE much like any other table structure in your top-level query. However, just as you saw earlier, you can also recast this statement without a CTE by joining the airplanes table directly to the manufacturers table:

SELECT a.plane, m.manufacturer, a.max_weight
FROM airplanes a INNER JOIN manufacturers m
  ON a.manufacturer_id = m.manufacturer_id
WHERE a.engine_type = 'jet'
ORDER BY a.max_weight DESC;

Because there is so little data, the difference in performance between the two statements is negligible, but that might not be the case with a much larger data set. However, as is often the case with MySQL, it can be difficult to know which approach is best without running both statements against a realistic data set. Even then there might not be a significant difference in performance, in which case, it might come down to developer preference.

As noted earlier, MySQL often supports multiple ways to achieve the same results, as the preceding examples demonstrate. Common table expressions can sometimes help simplify code and make it more readable, which is a big point in its favor, but performance should generally be the overriding consideration.

Comparing different approaches usually requires that you test them on a valid data set, in part, because it can be difficult to find specific recommendations when comparing approaches. Not many database developers, for example, would be willing to say that you should always use CTEs rather than inner joins in all circumstances, or vice versa.

That said, you might come across recommendations that are less rigid and are perhaps worth considering, such as when comparing CTEs with subqueries. For instance, a CTE is often considered to be a better option if your SELECT statement includes multiple subqueries retrieving the same data, as in the following example:

SELECT manufacturer_id, plane_id, plane, max_weight,
  (SELECT ROUND(AVG(max_weight)) FROM airplanes a2
    WHERE a.manufacturer_id = a2.manufacturer_id) AS avg_weight,
  (max_weight - (SELECT ROUND(AVG(max_weight)) FROM airplanes a2
    WHERE a.manufacturer_id = a2.manufacturer_id)) AS amt_over
FROM airplanes a
WHERE max_weight > 
  (SELECT ROUND(AVG(max_weight)) FROM airplanes a2
    WHERE a.manufacturer_id = a2.manufacturer_id);

If this statement looks familiar to you, that’s because I pulled it from my previous article in this series, which covers subqueries. As you can see, the statement includes three subqueries, all of them the same, which can result in a fair amount of redundant processing effort, depending on how the database engine chooses to handle the query. The following figure shows the results returned by this statement.

Instead of using subqueries, you can achieve the same results by defining a CTE that retrieves the average max_weight value for each manufacturer. Then, in your top-level query, you can join the airplanes table to the CTE, basing the join on the manufacturer IDs, as shown in the following example:

WITH mfc_weights (id, avg_weight) AS
  (SELECT manufacturer_id, ROUND(AVG(max_weight))
  FROM airplanes GROUP BY manufacturer_id)
SELECT a.manufacturer_id, a.plane_id, a.plane, 
  a.max_weight, m.avg_weight,
  (a.max_weight - m.avg_weight) AS amt_over
FROM airplanes a INNER JOIN mfc_weights m 
  ON a.manufacturer_id = m.id
WHERE max_weight > m.avg_weight;

In this case, the CTE specifies the column names to use for the result set, so the manufacturer_id values are returned as the id column. Additionally, the CTE groups the data in the manufacturers table by the manufacturer_id values and provides the average avg_weight value for each one.

The top-level query then joins the airplanes table to the CTE but limits the results to those airplanes with a max_weight value greater than the average weight returned by the CTE. Notice that, in place of the subqueries, the statement now uses the avg_weight column from the CTE.

Once again, the performance difference between these two approaches is negligible because we’re working with such a small data set. Only by running the statements against a more realist data set can we get a true picture of their performance differences. In my opinion, however, the CTE makes the code more readable, that is, it’s easier to follow the statement’s logic.

Defining multiple CTEs in one WITH clause

Up to this point, the examples in this article included only one CTE per WITH clause, but you can define multiple CTEs and reference any of them in your top-level statement. Just make sure that you assign different names to the CTEs and separate them with commas. For example, the following WITH clause defines three CTEs, which are all referenced in the top-level SELECT statement:

WITH 
  jets AS
    (SELECT plane, engine_type, engine_count, max_weight
    FROM airplanes WHERE engine_type = 'jet'),  
  turbos AS
    (SELECT plane, engine_type, engine_count, max_weight
    FROM airplanes WHERE engine_type = 'turboprop'),
  pistons AS
    (SELECT plane, engine_type, engine_count, max_weight
    FROM airplanes WHERE engine_type = 'piston')
SELECT * FROM jets
UNION ALL
SELECT * FROM turbos
UNION ALL
SELECT * FROM pistons;

The three CTEs are similar except that they each pull data based on a different engine_type value. The top-level SELECT query then uses the UNION operator to join them altogether. (The UNION ALL operator combines the results from multiple SELECT statements into a single result set.) The following figures shows part of the results returned by this statement.

This is a fairly basic example, but it demonstrates the concept of defining multiple CTEs and referencing them in the top-level query. In this case, the three CTEs operate independently of each other, but you don’t always have to take this approach. For instance, the WITH clause in the following example also includes three CTEs, but in this case, the second CTE (mfc_avg) references the first CTE (mfcs), while the third CTE (pl_avg) stands alone:

WITH
  mfcs (id, mfc) AS
    (SELECT manufacturer_id, manufacturer FROM manufacturers),
  mfc_avg (id, mfc, avg_parking) AS
    (SELECT m.id, m.mfc, ROUND(AVG(a.parking_area))
    FROM mfcs m INNER JOIN airplanes a 
      ON m.id = a.manufacturer_id
    GROUP BY manufacturer_id),
  pl_avg (avg_all) AS
    (SELECT ROUND(AVG(parking_area)) FROM airplanes)
SELECT id, mfc, avg_parking
FROM mfc_avg m
WHERE avg_parking > (SELECT avg_all FROM pl_avg);

As this example demonstrates, a CTE can reference a CTE that comes before it. However, this works in one direction only; a CTE cannot reference one that comes after it. In this case, the mfc_avg CTE joins the airplanes table to the mfcs CTE and groups the data based on the manufacturer_id value. The top-level query then retrieves data from this CTE, but returns only those rows with an avg_parking value greater than the average returned by the pl_avg CTE. The following figure shows the results returned by this statement.

Something worth emphasizing is that the WHERE clause in the top-level query includes a subquery that retrieves data from the pl_avg CTE. Not only does this point to the inherent flexibility of CTEs, but also to the fact that CTEs and subqueries are not mutually exclusive.

Working with recursive CTEs

One of the most useful aspects of the CTE is its ability to perform recursive queries. This type of CTE—known as the recursive CTE—is one that references itself within the CTE’s query. The WITH clause in a recursive CTE must include the RECURSIVE keyword, and the CTE’s query must include two parts that are separated by the UNION operator. The first (nonrecursive) part populates an initial row of data, and the second (recursive) part carries out the actual recursion based on that first row. Only the recursive part can refer to the CTE itself.

To help understand how this work, consider the following example, which generates a list of even numbers up to and including 20:

WITH RECURSIVE counter (val) AS
  (SELECT 2
  UNION ALL
  SELECT val + 2 FROM counter WHERE val < 20)
SELECT * FROM counter;

The name of the CTE is counter, and it returns only the val column. The nonrecursive part of the CTE’s query sets the value of the first row as 2, which is assigned to the val column. The recursive part of the query retrieves the data from the CTE but increments the val column by 2 with each iteration. The query continues to increment the val column by 2 as long as val is less than 20. The top-level SELECT statement then retrieves the data from the CTE, returning the results shown in the following figure.

Note: Since the recursive query says < 20, you might be inclined to think it would not return 20 in the output. But the iteration that returns 20 does occur, but it stops iterating because the value is not less than 20 anymore.

When building a recursive CTE, be aware that MySQL places several limitations on the recursive part. The second SELECT statement cannot contain aggregate functions, window functions, the DISTINCT keyword, or the GROUP BY or ORDER BY clause.

Performing a recursive query can be useful when working with hierarchical data. To demonstrate how this works, I used the following code to create and populate a table named airline_emps, which stores the IDs and job titles for a group of fictitious employees, along with the ID of the person each one reports to:

CREATE TABLE airline_emps (
  emp_id INT UNSIGNED NOT NULL,
  job_title varchar(50) NOT NULL,
  reports_to INT UNSIGNED NULL,
  create_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_update TIMESTAMP NOT NULL 
    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (emp_id),
  CONSTRAINT fk_emp_id FOREIGN KEY (reports_to) 
    REFERENCES airline_emps (emp_id) );

INSERT INTO airline_emps
  (emp_id, job_title, reports_to)
VALUES
  (1, 'big boss', NULL),
  (2, 'divsional boss', 1),
  (3, 'supervisor', 2),  
  (4, 'chief', 2),
  (5, 'designer', 3),
  (6, 'top exec', 1),
  (7, 'overseer', 6),
  (8, 'team leader', 6),
  (9, 'organizer', 8),
  (10, 'controller', 8),
  (11, 'specialist', 10),
  (12, 'analyst', 9);

SELECT * FROM airline_emps;

Everyone except for emp_id 1 (big boss) reports to another individual. For example, the overseer reports to the top exec, who in turn reports to the big boss. I included a SELECT statement along with the INSERT statement so you can verify the data after it’s been added to the table.

With this data in place, you can now create the following recursive CTE, which finds each person’s position level in the company and how that position fits into the reporting hierarchy:

WITH RECURSIVE emps AS
  (SELECT emp_id, job_title, reports_to, 
    1 AS emp_tier, CAST(emp_id AS CHAR(50)) AS emp_path
  FROM airline_emps
  WHERE reports_to IS NULL
  UNION ALL
  SELECT a.emp_id, a.job_title, a.reports_to, 
    e.emp_tier + 1, 
    CONCAT(a.emp_id, ' / ', e.emp_path)
  FROM airline_emps a INNER JOIN emps e
    ON a.reports_to = e.emp_id)
SELECT * FROM emps
ORDER BY emp_tier, emp_id;

Because this is a recursive CTE, it is separated in two parts that are connected with the UNION ALL operator. The nonrecursive part populates the first row, based on the NULL value in the reports_to column. This row is for the big boss, who is at the top of the hierarchy. The nonrecursive part also assigns the value 1 to the emp_tier column and assigns the emp_id value to the emp_path column, converting the value to the CHAR data type. The first row returned by the CTE looks similar to that shown in the following figure.

The recursive part of the CTE uses an inner join to match the airline_emps table to the emps CTE. The join is based on the reports_to column in the airline_emps table and the emp_id column in the emps CTE. The join condition makes it possible to recurse through each level of the reporting hierarchy, based on the reports_to value. The recursive part then increments the emp_tier column by 1 with each new level in the hierarchy.

For example, emp_id 2 (divisional boss) and emp_id 6 (top exec) both report directly to emp_id 1 (big boss), so the emp_tier column for these two rows is incremented by 1, resulting in a value of 2 for each row. This means that they’re both in the second tier of the employee hierarchy. The next layer in the hierarchy are those individuals who report to the divisional boss or top exec, so the emp_tier column for these rows is set to 3. This process continues until there are no tiers left.

During this process, the emp_path column is also updated in each row by concatenating the emp_id vales to provide a representation of the reporting hierarchy. For instance, the reports_to column for emp_id 9 will show that the organizer reports to emp_id 8 (team leader), who reports to emp_id 6 (top exec), who reports to emp_id 1 (big boss), with each layer separated by a forward slash. The following figure shows the data returned by the query.

The top-level SELECT statement retrieves data only from the CTE, without joining to any other tables. The statement also includes an ORDER BY clause that sorts the results first by the emp_tier column and then by the emp_id column.

Using CTEs with DML statements

Earlier in the article, I mentioned that you can use CTEs with statements other than SELECT. I also stated that my focus in this article was primarily on how the CTE is implemented with the SELECT statement. However, I want to show you at least one of the alternative forms so you get a sense of what that might look like (and to whet your appetite a bit).

The following example shows a CTE used with an UPDATE statement to modify the data in the airline_emps table created in the previous section:

WITH rpts AS
  (SELECT emp_id FROM airline_emps
  WHERE reports_to = 8)
UPDATE airline_emps
SET reports_to = 7
WHERE emp_id IN (SELECT * FROM rpts);

The WITH clause and CTE work just like you saw in other examples. The clause includes a single CTE named rpts that retrieves the emp_id values for those employees who report to emp_id 8. The query returns the values 9 and 10.

The top-level UPDATE statement uses the data returned by the CTE to update the reports_to column to 7 for those two employees. The UPDATE statement’s WHERE clause includes a subquery that retrieves the data from the CTE, so the statement will update only those two rows.

After you run this update statement, you can rerun the SELECT statement from the previous section to verify the changes. I’ve included the statement here for your convenience:

WITH RECURSIVE emps AS
  (SELECT emp_id, job_title, reports_to, 
    1 AS emp_tier, CAST(emp_id AS CHAR(50)) AS emp_path
  FROM airline_emps
  WHERE reports_to IS NULL
  UNION ALL
  SELECT a.emp_id, a.job_title, a.reports_to, 
    e.emp_tier + 1, 
    CONCAT(a.emp_id, ' / ', e.emp_path)
  FROM airline_emps a INNER JOIN emps e
    ON a.reports_to = e.emp_id)
SELECT * FROM emps
ORDER BY emp_tier, emp_id;

The statement returns the results shown in the following figure.

Notice that employees 9 and 10 now show a reports_to value of 7. In addition, the emp_path value for each of the two rows has been updated to reflect the new reporting hierarchy.

Working with MySQL common table expressions

The CTE can be a powerful tool when querying and modifying data in your MySQL databases. Recursive CTEs can be particularly useful when working with self-referencing data, as the earlier examples demonstrated. But CTEs are not always intuitive, and you should have a good understanding of how they work before you start adding them to your current database code, especially if you want to use them to modify data. For this reason, I recommend that you also review the MySQL documentation on CTEs, along with any other resources you have available. The more time you invest upfront in learning about CTEs, the more effectively you’ll be able to utilize them in your MySQL queries.

Appendix: Preparing the demo objects and data

For the examples in this article, I created the travel database and added the manufacturers and airplanes to the database. If you want to try out these examples for yourself, start by running the following script on your MySQL instance:

DROP DATABASE IF EXISTS travel;
CREATE DATABASE travel;
USE travel;
CREATE TABLE manufacturers (
  manufacturer_id INT UNSIGNED NOT NULL,
  manufacturer VARCHAR(50) NOT NULL,
  create_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_update TIMESTAMP NOT NULL 
    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (manufacturer_id) );
CREATE TABLE airplanes (
  plane_id INT UNSIGNED NOT NULL,
  plane VARCHAR(50) NOT NULL,
  manufacturer_id INT UNSIGNED NOT NULL,
  engine_type VARCHAR(50) NOT NULL,
  engine_count TINYINT NOT NULL,
  max_weight MEDIUMINT UNSIGNED NOT NULL,
  wingspan DECIMAL(5,2) NOT NULL,
  plane_length DECIMAL(5,2) NOT NULL,
  parking_area INT GENERATED ALWAYS AS ((wingspan * plane_length)) STORED,
  icao_code CHAR(4) NOT NULL,
  create_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_update TIMESTAMP NOT NULL 
    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (plane_id),
  CONSTRAINT fk_manufacturer_id FOREIGN KEY (manufacturer_id) 
    REFERENCES manufacturers (manufacturer_id) );

After you’ve created the database, you can add sample data to the manufacturers table by running the following INSERT statement, which inserts seven rows:

INSERT INTO manufacturers (manufacturer_id, manufacturer)
VALUES (101,'Airbus'), (102,'Beagle Aircraft Limited'), (103,'Beechcraft'), 
  (104,'Boeing'), (105,'Bombardier'), (106,'Cessna'), (107,'Embraer');
SELECT * FROM manufacturers;

I included a SELECT statement after the INSERT statement so you can confirm that the seven rows have been added to the table. The first row in the table has a manufacturer_id value of 101, and the subsequent rows are incremented by one. After you’ve populated the manufacturers table, you can run the following INSERT statement to add data to the airplanes table:

INSERT INTO airplanes 
  (plane_id, plane, manufacturer_id, engine_type, engine_count, 
    wingspan, plane_length, max_weight, icao_code)
VALUES
  (1001,'A340-600',101,'Jet',4,208.17,247.24,837756,'A346'),
  (1002,'A350-800 XWB',101,'Jet',2,212.42,198.58,546700,'A358'),
  (1003,'A350-900',101,'Jet',2,212.42,219.16,617295,'A359'),
  (1004,'A380-800',101,'Jet',4,261.65,238.62,1267658,'A388'),
  (1005,'A380-843F',101,'Jet',4,261.65,238.62,1300000,'A38F'),
  (1006,'A.109 Airedale',102,'Piston',1,36.33,26.33,2750,'AIRD'),
  (1007,'A.61 Terrier',102,'Piston',1,36,23.25,2400,'AUS6'),
  (1008,'B.121 Pup',102,'Piston',1,31,23.17,1600,'PUP'),
  (1009,'B.206',102,'Piston',2,55,33.67,7500,'BASS'),
  (1010,'D.5-108 Husky',102,'Piston',1,36,23.17,2400,'D5'),
  (1011,'Baron 56 TC Turbo Baron',103,'Piston',2,37.83,28,5990,'BE56'),
  (1012,'Baron 58 (and current G58)',103,'Piston',2,37.83,29.83,5500,'BE58'),
  (1013,'Beechjet 400 (same as MU-300-10 Diamond II)',103,'Jet',2,43.5,48.42,15780,'BE40'),
  (1014,'Bonanza 33 (F33A)',103,'Piston',1,33.5,26.67,3500,'BE33'),
  (1015,'Bonanza 35 (G35)',103,'Piston',1,32.83,25.17,3125,'BE35'),
  (1016,'747-8F',104,'Jet',4,224.42,250.17,987000,'B748'),
  (1017,'747-SP',104,'Jet',4,195.67,184.75,696000,'B74S'),
  (1018,'757-300',104,'Jet',2,124.83,178.58,270000,'B753'),
  (1019,'767-200',104,'Jet',2,156.08,159.17,315000,'B762'),
  (1020,'767-200ER',104,'Jet',2,156.08,159.17,395000,'B762'),
  (1021,'Learjet 24',105,'Jet',2,35.58,43.25,13000,'LJ24'),
  (1022,'Learjet 24A',105,'Jet',2,35.58,43.25,12499,'LJ24'),
  (1023,'Challenger (BD-100-1A10) 350',105,'Jet',2,69,68.75,40600,'CL30'),
  (1024,'Challenger (CL-600-1A11) 600',105,'Jet',2,64.33,68.42,36000,'CL60'),
  (1025,'Challenger (CL-600-2A12) 601',105,'Jet',2,64.33,68.42,42100,'CL60'),
  (1026,'414A Chancellor',106,'Piston',2,44.17,36.42,6750,'C414'),
  (1027,'421C Golden Eagle',106,'Piston',2,44.17,36.42,7450,'C421'),
  (1028,'425 Corsair-Conquest I',106,'Turboprop',2,44.17,35.83,8600,'C425'),
  (1029,'441 Conquest II',106,'Turboprop',2,49.33,39,9850,'C441'),
  (1030,'Citation CJ1 (Model C525)',106,'Jet',2,46.92,42.58,10600,'C525'),
  (1031,'EMB 175 LR',107,'Jet',2,85.33,103.92,85517,'E170'),
  (1032,'EMB 175 Standard',107,'Jet',2,85.33,103.92,82673,'E170'),
  (1033,'EMB 175-E2',107,'Jet',2,101.67,106,98767,'E170'),
  (1034,'EMB 190 AR',107,'Jet',2,94.25,118.92,114199,'E190'),
  (1035,'EMB 190 LR',107,'Jet',2,94.25,118.92,110892,'E190');
SELECT * FROM airplanes;

The INSERT statement uses the manufacturer_id values from the manufacturers table. These values provide the foreign key values needed for the manufacturer_id column in the airplanes table. In addition, the first row is assigned 1001 for the plane_id value, with the plane_id values for the other rows incremented accordingly. As with the previous INSERT statement, I’ve included a SELECT statement for confirming that the data has been properly added.

 

The post Introducing the MySQL common table expression appeared first on Simple Talk.



from Simple Talk https://ift.tt/SMgR1ze
via

Don’t Just Chase the Shiny

Fish are beautiful creatures, but they have one minor issue. The main thing I remember from the years I fished is that fish can be susceptible. If you have a fishing lure that shows off with a bright, colorful, shiny appearance that splashes around just right, fish will lose their minds and go after it, much to their detriment. Note, of course, that these are the same fish that are frightened away if you are making any noise whatsoever in the area, so they aren’t exactly dumb; they just have a weakness.

For many of us, new features and products lure us in for a ride. I know I look forward to September each year to get the next iteration of the iPhone. When Microsoft releases a new version of SQL Server, I start poking at it immediately to find new features and start working on how to use (and write about) those features.

About a month ago, I wrote an editorial called “The Good, The Bad, and Suboptimal of Sticking to What You Know.” One of the commenters had a concern with it, in that it was felt that I was suggesting that you use every new and shiny thing out there. While it was clearly mentioned in the text that not all new features are necessarily valuable (and they did say they didn’t read the whole thing!), I want to do what I can to clarify that point. “Everything that glitters, is not gold.”

When I came up with that horribly long title to the previous post, I did it because I wanted to emphasize this was about simply sticking to what you know and ignoring everything new. I stand by the sentiment that it is terrible to stick your head in the sand and just flat ignore new technology/techniques. The image in my mind for this is someone still using tape drives because it was “good enough when I started, and it is good enough now.” Ask some people like this about backing up to the cloud and they look at you funny thinking “clouds are water vapor.”

That sort of thing is where it really starts to be a concern. New features that can save you time and energy if you just look for them. For example, in SQL Server, there is a new feature called GENERATE_SERIES. This function will output a table of values for a given range.

For example:

SELECT *
FROM  
GENERATE_SERIES(0,999999) AS numberSeries;

This returns a set of rows from 0 – 999999 with no breaks in the sequence. The best way we typically did this before this function was added was something like this:

;WITH digits (I) AS (--set up a set of numbers from 0-9
        SELECT I
         
        FROM   (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS digits (I))
        SELECT D1.I + (10*D2.I) + (100*D3.I) + (1000*D4.I) + (10000*D5.I)
               + (100000*D6.I) AS value
 
        --gives us combinations of every digit
        FROM digits AS D1 CROSS JOIN digits AS D2
             CROSS JOIN digits AS D3
             CROSS JOIN digits AS D4
             CROSS JOIN digits AS D5
             CROSS JOIN digits AS D6;

I am not sure who first coded this, but if it was Itzik Ben Gan I would not be surprised. Either way, suffice it to say that I would have never devised this method out of my own brain. Before this was devised, most of us would have used a loop and a counter.

First off, the main thrust is that as a T-SQL programmer who has used a numbers table, that you actually hear about GENERATE_SERIES. The next step is deciding if it is right for you. It is much simpler to code, so it must be great, right? It is new, it is shiny, and why not?

I am not going to answer that question for you here. Both methods have pros and cons, so much like any technical topic, you can boil it down to that well-known programmer answer: “It depends.”

What I am imploring you to do is simple. Keep up as much as you can and know about the different techniques and changes coming as time passes. If you are still backing up using tape drives, better choices are available in 2023 (as there were in 2022, and 2021…).

Conclusion

The point of both of these editorials is simple. Don’t get stuck in a time-period you are comfortable with using tools you are satisfied with, and never change. Be on the lookout for new and better methods, tools, techniques, etc. While everything that glitters isn’t gold, gold does in fact glitter too.

Just don’t be that fish grabbing at something shiny in the water without verifying what it is. Sometimes it is lunch, sometimes it is a scary trip you would have rather avoided!

 

The post Don’t Just Chase the Shiny appeared first on Simple Talk.



from Simple Talk https://ift.tt/hR58pgM
via

Wednesday, January 4, 2023

Azure Function and User Assigned Managed Identities

Let’s talk about authentication between Azure Functions and resources used by Azure Functions and conclude with many poorly documented secrets about how to use User Assigned Managed Identity. When we build Azure functions, they usually need to authenticate against other Azure resources: Azure SQL Database, Storage Accounts, Service Bus and many more.

Each of these services have an authentication that we can call “Meh!”: Azure SQL has SQL Standard Logins, storage accounts have SAS tokens, service bus, shared access keys and so on. These are not the safest methods possible. If the key leaks, you will have a security problem because anyone with the key will be able to access the resource.

There are multiple solutions for this problem, some of them would pass through Key Vault, used to store secrets, keys and passwords. But let’s go directly to the best one: Remove the usage of keys at all. 

How the Azure Function can authenticate against other services without using any key?

We can assign an identity to the Azure Function and use this identity to authenticate on other resources. You can think about the identity as a special kind of Azure AD user. As with any other user, it can receive permissions in Azure resources, allowing your function to access the resources

Instead of using a shared key in your system or configuration files, using an identity leaves it up to Azure to manage the access from the function to other resources. There will be no secret access key which could be exposed in your system.

The two kinds of identity

The identity we set to a Function App (or other Azure Resource) is called a Managed Identity. There are two kinds of Managed Identity: The System Assigned Managed Identity and the User Assigned Managed Identity.

First of all, it’s important to understand that for both types, we are responsible to set the identity permissions, which is explained later.

The System Assigned Managed Identity is the perfect example of the KISS principle (Keep It Simple): You just turn it on in an Azure Function. The identity is created with the same name as your function app. You can give permissions to this identity and that’s it, your function will be able to access the resources you need.

When you delete the function app, the identity with all its permissions is deleted as well.

The User Assigned Managed Identity is a bit more complex. Why would you need a more complex solution?

If you have multiple Function Apps and all of them requires access to the same resources, using System Assigned Managed Identities becomes a problem. The management of permissions for each individual function identity is at least annoying, and it’s also prone to mistakes.

The solution is to create a custom identity and assign the same identity to all Function Apps which requires the same set of permissions. In this way, you manage the permissions on a single identity, instead of many.

This is the rule: If the permissions are needed by a single function, use a System Assigned Managed Identity and the identity lifecycle will be managed together the function lifecycle. If many functions need the same set of permissions, use a User Assigned Managed Identity and you will need to manage the permissions only for a single identity.

 

System Assigned Managed Identity

User Assigned Managed Identity

Usage

Used by one single function

Can be assigned to multiple Function Apps and other cloud apps

Lifecycle

Is created when turned on in the Function App and dropped together the Function App

Created and dropped independently of the Function App. Someone needs to manage the identity

How does it work

It simply works

It may require variables or properties to work, but these will not contain any sensitive information

Enabling System Assigned Managed Identity

As I mentioned before, these are very simple. You can just access the Identity tab and turn the identity on. The name of the identity is the name of the function app.


Enabling User Assigned Managed Identity

User Assigned Manage Identities have an independent life cycle. This means you need to create them directly from the Marketplace. To do this, locate the User Assigned Managed Identity in the marketplace resources and create it as illustrated on the following images:



The creation itself is a generally simple matter of choosing the resource group and name of the identity. Consider the company standards for naming and resource group distribution. Some questions you should ask:

  • Are you going to share this identity with objects in different resource groups?
  • Are you going to share this identity across different projects?
  • Are you going to share this identity across different environments (dev/uat/production)?

Of course, the more granular the identity permissions are, the better, but you are using this object because you want to share the same set of permissions across different App objects to begin with.


After creating the identity, you will be able to see it in the chosen resource group.


The next step is to assign the identity to the function app. The Identity tab has the option to include a User Assigned Managed Identity to the app. The following images illustrate the steps used for this.



As you may notice on the images, it’s possible to assign multiple identities to the same Function App. We can assign one System Assigned Managed Identity as well as multiple User Assigned Managed Identity. The usage of multiple identities is usually managed by code. In some situations, can be done by configurations as well.

The scenario with multiple identities, where maybe your security requires different identities to access each resource, goes beyond the subject of this blog.

Assigning permissions to the Identity

In this section, I will discuss the details of how the identity gets access to resources that you choose.

RBAC Permissions

Role Based Access Control is the usual access control used for most Azure services. In our examples, I will illustrate Service Bus and Storage Accounts usage of RBAC permissions. Let’s consider our function will need access to a storage account and a service bus namespace. The identity given to the function needs to receive RBAC permission on both.

The method to set RBAC permissions on the services is always similar.

  1. Click Access Control (IAM)


  1. Click Role Assignments tab

     


  1. Click + Add button and choose: Add Role Assignment menu item


  1. Select the role you would like to assign and click Next button


  1. Select Managed Identity


There isn’t much different between selecting Managed Identity or User, Group or Service Principal. You can find the identity in both ways. The Managed Identity option only makes it easier to locate Managed Identities

  1. Click Select Members link, then on the Select Managed Identities tab, open the Managed Identity drop down

This drop down summarizes to you all available Managed Identities in the subscription. The System Assigned Managed Identities are related to azure objects, while User Assigned Managed Identities are independent.


  1. Select the identity you created


  1. Click the Review + Assign button

Service Bus

Service Bus has three main roles you would like to assign: Service Bus Data Owner, Service Bus Data Receiver and Service Bus Data Sender. Probably you will assign the last two to your functions, depending if they send data to service bus or receive data from service bus.


You can assign permissions on the service bus level, the topic level or queue level. This brings an interesting decision to be made: you can use a single identity with access to multiple queues and topics or use multiple identities, one for each set of resources a function need.

The latter is safer, of course. The first option, on the other hand, can lead to situations where a function has access to queues and topics it doesn’t need to access.

Here come the corporate procedures again: Does your company has a security team responsible for this? If they have, they should be thrilled to hear this explanation and move forward with the most secure option. Otherwise, no one will care about the additional security and will be annoyed by your proposal to make it more difficult to manage. In this case, the first option is better.

Setting the permissions use the traditional RBAC procedure, defining roles for identities on the correct object.

Storage Accounts

Storage Accounts have many different roles available because they offer different services: Blob, File, Queue and Table. In this way, you have roles intended to manage the storage account and roles intended to manage the data inside the storage account.


Storage accounts brings the same dilemma than the Service Bus: You can control the permissions in a granular way, giving the functions only the permissions needed, or you can give all the permissions to a single identity and set it on the functions. The granular way is always technically better for security, but it always depends if the company is willing to manage it correctly.

The granularity in the storage account can be controlled not only by service (blob, queue, table and files), but by each element on the services. For example, you can set RBAC permission on the level of reach blob container.

Key Vault

Key Vaults can use RBAC as permission control method, but the most common method for permission control are the access policies. On the Access configuration tab in a Key Vault, you can choose rather to use RBAC or access policies to control the permissions.


Let’s focus on the access policies option. You can create access policies giving permissions to access the Keys, Secrets and Certificates.


Once again, you face the granularity problem: If function A needs access to Secrets and function B needs access to Certificates, will you use a single identity with access to certificates and secrets, or would you use two identities, one with access to secrets and the other with access to certificates?

Key Vault granularity goes further: The access control is made by type of object: Key, Secrets or certificates. Once the permission is given, the function will have access to all secrets, or all keys or all certificates. What if the function needs access only to some keys, but not to others?

The solution is to use multiple key vaults, organizing the objects according the app which will access them. Only by doing so you can ensure each function will have access only to the information the function needs to use, and not to information related to other functions.

SQL Databases

The possibilities in relation to SQL Databases are wider. Some microservices implementation types would build one database for each microservice, isolating the data.

Others would implement a single database, and that’s when the same security granularity problem comes into focus: Would you use one single identity with read and write permission? Different identities for read and write? Different identities for each database schema? The same kind of considerations as all other resources. There is no right and wrong answer. There is the safer and less safe. Less safe doesn’t mean wrong. It does however mean a correct choice between risk and amount of management work is needed. The granularity choice is a complex one to be done by a skilled security team. The developer work is to introduce the best options when they are not yet being used.

Important Secret: The usual library to access SQL Server, System.Data.SqlClient, doesn’t support authentication with managed identities. You need to use a different library, Microsoft.Data.SqlClient. Luckily, the code is the same, the only change I identified was the support to managed identities authentication.

The permissions are set using TSQL and the security rules specific to SQL Server, they are not set using RBAC. You can find an example below:

create user [MyFunctionApp] from external provider
alter role db_datareader add member [MyFunctionApp]

Important but out of scope: You also need to deal with SQL Firewall, but this is out of the scope of this blog. You can take a look on the vide on https://www.youtube.com/watch?v=RKZy5MkqFDQ&list=PLNbt9tnNIlQ5pVwZFRVpoBG8uQTs8aIcz&index=26 . The same principles of Service Connection and Private Endpoints also applies to Key Vaults, Storage Accounts and Service Bus.

The secrets of User Assigned Managed Identity

We would expect that User Assigned Managed Identity would just work, exactly as System Assigned Managed Identity. Unfortunately, that’s not so simple. There are many secrets to make User Assigned Managed Identity work. These secrets are not well documented and are different for each service.

Service Bus

In order to work with Service Bus, a User Assigned Managed Identity requires two configuration variables to be created: Azure_Client_ID and AZURE_TENANT_ID.

The first contains the Client Id generated to identify the Managed Identity, the second is the tenant id of the managed identity.



 

Without these variables you will get an error message inside Application Insights which will be similar to this:

“Azure.Identity.CredentialUnavailableException: EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://ift.tt/FzeGBty;

The documentation doesn’t explain much, especially because we were expecting it to work out of the box, but these variables are needed. Create the variables and it will work.

Key Vault

While the System Assigned Managed Identity simply works, a User Assigned Managed Identity requires a special property in the Function App object. The property is called keyVaultReferenceIdentity and needs to contain the object Id of the Managed Identity.

It would be simple if we could set this property on the UI, but this property isn’t available even on Azure CLI. We need to make a REST PATCH call to Azure API to set this property.

The code below is built to be called in BASH, you can use Cloud Shell for this:

appResourceId=$(az webapp show -g MyResourceGroup -n MyFunctionApp --query id -o tsv)
az rest --method PATCH --uri "${appResourceId}?api-version=2021-01-01" --body "{'properties':{'keyVaultReferenceIdentity':'/subscriptions/bcae138f-2b24-4931-b715-4aacd2463ef0/resourcegroups/MyResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/functionIdentity'}}"

The first statement retrieves the app resource id, while the second completes the PATCH call to set the property.

If you don’t set this property, the Function App will use the System Assigned Managed Identity or it will complain the identity is not enabled.

It’s not only for Function Apps

App Services, Virtual Machines, Container Apps or AKS, all kind of apps running on Azure can receive a managed identity and identify themselves to other services using this managed identity. It’s possible that each specific combination has its own tricks to work, such as the two I explained above.

This increases the entire security of the entire environment.

The corporate problems: Spreading the correct solution

Among corporations, we always face many challenges to implement mentality-changing solutions. The users spent too many years using passwords, keys and secrets and sometimes it may be challenging to explain why using identities is better.

Usually, you will face outdated standards and “we always did like this” approaches. My suggestion is to follow the guidance of the corporation you work for, but not accept it quietly, look for openings to improve it. Let’s analyze some options.

Expose problems with existing patterns

Sometimes, corporations create patterns for software development and these patterns live beyond their creator. The spread of such patterns create repetition and over time usually lacks a check if they are still the correct option.

The solution is to find the correct person open to hear about how it really works and analyze the best way to implement it. When attempting to change any kind of security practices, you should consider socializing the solution with people on the security team.

Introduce the Idea of Layered Security

Layered Security is a security approach to protect your applications from attack. The core idea is to protect every layer of your application and not only the entry point.

Companies not familiar with this concept may see this as additional work. They may think it’s enough to have a firewall and may consider not important to protect the access from one internal resource to another. For these companies, a mind changing may be needed, introducing the importance of Layered Security.

The concept of Layered Security changes this. The point is: If a hacker manages to cross your firewall, or find another entry point, they should face more security restrictions. If you don’t use the Layered Security approach and a hacker work around your entry point, they will be in, with access to all your information.

It’s the role of a skilled security professional to define the security guidelines to be followed by the company. But when the best security approaches are not in place, is the role of the developer to talk to these security professionals to highlight what could be better. Usually, they should like very much to know about additional security configuration they have available for the security guidelines.

Spread the knowledge among the team

It’s very common to work with development teams with very uneven knowledge about Function Apps and really much of the cloud functionality available. It can be useful for teams to organize knowledge sharing sessions to increase the knowledge of the team, establishing higher levels of software development standards.

The most secure method to authenticate functions and the methods to choose between User or System assigned managed identity is a great subject for a knowledge sharing session, especially since the answer requires knowledge of the exact problems you are attempting to solve.

Work around permission issues

The work to manage RBAC (Role Based Access Control) permissions require a higher-level permission than contributor. In order to manage these permissions, you need to have User Access Administrator permission.

Security and Cloud teams will typically have some resistance to provide these permissions and without understanding their purpose, they are right. The only way to allow you to work without providing these permissions is to provide you with a sandbox to work, where you have these permissions, and make all the deployment using DevOps pipelines, ensuring the correct configuration in UAT and Production environments.

Conclusion

Ensuring the best security possible is important and usually a forgotten subject. Many developers think “if it works, it’s fine”, but there are many ways that a working application may be a high risk for security.

The post Azure Function and User Assigned Managed Identities appeared first on Simple Talk.



from Simple Talk https://ift.tt/TcpXjdM
via