Thursday, May 26, 2022

Datamarts and exploratory analysis using Power BI

Power BI Datamarts is an important new feature announced during BUILD. This new feature expands Power BI possibilities in directions which may be unexpected to many Power BI users. Next, discover more about what this means for Power BI users and developers.

What’s a single source of truth?

Before explaining Datamarts, I will need to start from the beginning. Every company needs a single source of truth.

Could you imagine if, when checking the total of active customers in the company, one e-mail report has a number, one Power BI dashboard has a different number, and the production database has a third one?

In my country we have an old saying “Who has one watch knows the time, who has two watches only knows the average”. Every company needs to be sure to have a single watch and keep it always on time. A single source of truth.

Data warehouses are one implementation of this single source of truth. It’s beyond the Power BI work. ETL is used to extract data from all production databases to a Data Warehouse. Power BI uses the Data Warehouse as a source and becomes the serving layer for the company’s data platform.

Image showing data starts at several data sources, moves to Data Factory for Ingestion, moves to Data Lake House, to Data Models and Reporting and Analysis

This is a good practice. It’s not always followed or a technical requirement, but it’s a good practice. I wrote before about the relation between ETL and Power BI in this other article: https://www.red-gate.com/simple-talk/blogs/power-bi-etl-or-not-etl-thats-the-question/

What’s a data mart?

According to its theorical definition, a data mart is a subset of the data warehouse. A data warehouse can contain complex structures, such as slowly changing dimensions (also know as dimension type 2). These structures are not simple to be used by an end user.

These complex structures hold important historical information which can be useful, but most users will need more focused information. That’s where the data marts come to the rescue.

A data mart can be a more focused and more user-friendly set of data, extracted from the data warehouse and prepared for the end user. 90% of the time the user requirements will be fulfilled by dashboards and reports created from the data mart. But there is also those 10% of questions which appear out of the blue from a CEO request. These questions may require an exploratory analysis over the data mart or even the data warehouse. That’s why there is the old saying “A data warehouse doesn’t have a response time, but a delivery time”.

Image showing Data Warehouse vs Data Mart

Power BI, working as a serving layer, can use a data warehouse or a data mart as a source. More than that, many people, including me, would consider Power BI as a tool to build data marts using a data warehouse as a source.

Exploratory analysis vs explanatory analysis

You may have heard before about how Story Telling knowledge is important to build Power BI reports. It is. That’s because Power BI reports are very powerful for explanatory analysis.

You start with the data. A lot of historical data inside the company data warehouse. From this data, conclusions need to be made and call to actions based on these conclusions need to be defined. Once conclusions are made, the reports are the tool used to explain it to the end users, convincing them about your conclusions.

Using Power BI reports, you can make explanatory analysis in Power BI applying story telling techniques. But what about exploratory analysis? What can Power BI offer for exploratory analysis? Explore the possibilities next.

Exploring data with Power BI interactive reports

As you may know, Power BI reports are interactive. The user can view the reports in different ways, in different points of view.

The question you may need to ask is: Are the interactive reports enough for exploratory analysis?

I will use some concepts from books about story telling to try to answer this question. I like one analogy from one specific book. Exploratory analysis is the work of opening 100 oysters to find 1 pearl. Explanatory analysis is the work of explaining about that pearl to your users. It’s a bad practice to provide the users with the 100 oysters and leave to them the work to find the pearl.

However, while studying storytelling, you also need to know your users. You tell stories to your end user, such as a businessman who wants to know what’s hidden in the middle of the data. But if your user is a data analyst whose responsibility is to explore the data and find new possibilities, this guy will need to see the 100 oysters and find the pearl by himself.

There are many tricks to achieve this. Creating dynamic measures on the visuals, allowing the user to change the measure in the visual, creating dynamic hierarchies and much more.

Image showing Power BI vs Excel

In my humble opinion, with a good amount of work you can fulfil the user needs up to a point. But you know your users need more when the users keep asking you to receive the data in Excel. This is how the users tell you they want more exploratory power over the data.

Power BI building tools

Before building a report, you need to import data and build a model. You can use Power Query to import data with an entire language for this, the M language. For the model, there is DAX to build measures.

These tools focus is to build a model and from there build a story. However, they can be used for exploratory analysis. Power Query can be used to build different transformations on the source and check the results. You can build, edit, drop, build again, the entire back-and-forth of an exploratory analysis. The same can be done with DAX measures. You can create, change, adjust, in such a way to explore the existing data and discovering what’s needed.

Besides these tools, there are also an R visual and a Python visual, both allowing analysis of data using these languages.

All these tools enable using Power BI for exploratory analysis. However, is this analysis so easy as something done directly in SQL, Python or R over the data source?

In my humble opinion, using these tools for exploratory analysis is possible, but it’s a work around. That’s what is about to change with the use of Power BI Datamarts.

Bottom-UP design

Building a data warehouse, data marts and using Power BI as the serving layer is a state-of-the-art scenario, but you don’t always have the option to build it this way.

Many times, the data is spread among many different data sources. Sometimes these data sources can be set of Excel files, SharePoint lists or many other data sources which would make the ETL process more complex.

These data sources, using technologies built for modest sized data, will start to grow and will create problems during their growth.

This is the kind of scenario where building a data warehouse can happen in the reverse order: You start building small data marts, using the data sources and resources you have available. Later, you can merge these data marts into a single data warehouse. This is called a bottom-up design.

Building a data warehouse is a challenge regardless of top-down or bottom-up design. When using the bottom-up architecture, the risk is to end up with many data marts that can’t be merged, because they don’t fit in a bigger scenario. It’s like a puzzle. Working on isolated pieces without a view of the entire image may result in pieces that don’t match.

Image showing Top Down vs Bottom Up

Once again, the Datamart feature in Power BI can help with the bottom-up scenario. When you face the need to retrieve the data from many disconnected and not so trustworthy sources, you can use the Datamarts in Power BI as a starting point to consolidate the data sources.

What’s Power BI Datamarts?

Power BI Datamart is a new feature announced in public preview during Microsoft BUILD. This feature requires the use of Power BI Premium or Premium Per User (PPU).

The Datamart uses an underlying Azure SQL Database to store its data. This creates very powerful possibilities. When creating a Datamart, you can import the data from many different sources to this Azure SQL Database using Power Query. The Datamart will also automatically create and manage a dataset linked to the internal Azure SQL Database.

Image showing data flowing from sources to Data Mart to SQL to Dataset

Some architectural details:

  • The dataset model is built on the Datamart
  • Renaming the Datamart renames the dataset
  • The tables in the dataset use direct query but have support for caching, which is done transparently for us
  • It also supports dataflows as sources
  • You have limited control over the settings of the dataset
  • You have very limited control over the underlying Azure SQL Database. It’s provisioned by Power BI.

After learning about the architecture, here are the main features you can expect from the Power BI Datamart:

  • It provides a UI to build a data mart in the portal
  • This UI is basically the use of Power Query to import data. The portal doesn’t support the use of Power Query with datasets, you need to use Power BI desktop.
  • Using Datamarts, you can build Power Query ETLs using the portal. The data imported by Power Query will be saved in the Azure SQL Database
  • You can build a model using the imported tables.
  • You can define relationships, create measures, and configure the attributes and tables.
  • The UI provides additional resources for exploratory analysis
  • The Datamart UI provides data exploration features

There are two new tabs, one for query design, another one for SQL. On both tabs you can explore the data to discover useful information in your data.

The UI also allows you to download the query results to Excel, to expand the exploratory analysis possibilities

  • Support for incremental refresh

Incremental refresh is essential for big tables, and they are expected in a data mart. The configuration is very similar to the incremental refresh configuration you may already know, but the data is being inserted in the Azure SQL Database.

Image showing the incremental refresh dialog

  • Support for role-based permissions configuration

Image showing the Row security settings

  • Integrated with Power BI Deployment Pipelines
  • Datamarts allow a read-only connection to the Azure SQL Database. This is probably the most powerful tool for exploratory analysis

To understand this new feature, implement a Datamart step-by-step.

Important: The new Power BI feature is called “Datamart”, while the theoretical concept is called “Data mart”.

Implementing a Power BI Datamart

This will be the starting point:

  • An Azure SQL Database using the sample AdventureWorskLT
  • You need to execute the script Make_big_adventure.SQL adapted for the AdventureWorksLT. You can find it on https://github.com/DennesTorres/BigAdventureAndQSHints/blob/main/make_big_adventureLT.sql
  • You need a premium Power BI workspace, either premium by capacity or premium per user
  • Recommendation: The Azure SQL Database is recommended to have 10 DTU’s or more. Less than that and some slowness may be noticed
  • Recommendation: If you create a non-clustered index on the table BigTransactionhistory, column TransactionDate, the access to the database will be faster.

After preparing the environment, it’s time to start to build the Datamart.

Creating the Datamart: First stage, importing the tables

  1. In the premium workspace, click New button and select the Datamart menu item

An image showing the New menu with Datamart (Preview) selected

  1. On the Datamart design window, click the Import data from SQL Server image in the centre of the screen

Mind you also have options for Excel and Dataflows highlighted, but you also can use the Get Data button and use different kinds of data sources

An image showing the Start building your datamat dialog. You can start with SQL Server, Excel, or Datflow

  1. In the Connect To Data Source window, fill the Server textbox with the address of your Azure SQL Database
  2. On the Connect To Data Source window, fill the Database textbox with the database name
  3. On the Connect To Data Source window, fill the user name and password with the Azure SQL Authentication

If your data source were on premises, you could use a gateway for it, but in this case, it’s not needed.

A dialog showing the connection properties to the database

  1. Click Next button
  2. On the Power Query window, under Choose Data, select the tables you will include in your Datamart. In this example, include bigTransactionHistory, bigProduct and SalesLT.ProductModel

A dialog showing the Power Query Choose data list. SalesLT.ProductModel, bigProduct and bitTransactionHistory are selected

  1. Click the Transform data button

A picture containing graphical user interface Description automatically generated

  1. On the Power Query window, under Queries, click the table bigProduct

An image showing Queries [3] bigProduct, bigTransactionHistory, and SalesLT ProductModel

  1. On the Query Settings tab, rename it to Product

An image showing the Query settings Properties Name bigProduct. Applied steps source, Navigation1

  1. Repeat the steps to rename the table bigTransactionHistory to TransactionHistory
  2. Select the Product table
  3. Select the columns Size, Weight, SellStartDate, SellEndDate and DiscontinuedDate
  4. Use the button Remove Column to remove the unneeded columns

An image showing the column view and removing a column

  1. Right-click the table SalesLT ProductModel
  2. Disable the option Enable Load

You will merge the information about the product model with the product details. You don’t need the ProductModel table as part of the model. When the Enable Load is disabled, the name of the table appears in Italic among the queries

An image showing SalesLT ProductModel and right-click menu with Enable load selected

  1. Select the table Product
  2. Click the Merge queries button

An image showing the choices Merge queries and Merge queries as new

  1. On the Merge window, on the Right table for merge, select the table SalesLT ProductModel
  2. On the Merge window, Product table, select the ProductModelID field
  3. On the Merge window, SalesLT ProductModel table, select the ProductModelID table

An image showing the Merge dialog. Select a table and matching columns to create a merged table. Product table with several rows returned. Right table for Merge SalesLT ProductModel. Join kind Left outer

  1. Once the match message appears in a green bar on the lower side of the window, click the Ok button
  2. On the new SalesLT ProductModel column, click the expand button

Image showing the SalesLT ProductModel and expand button

  1. On the window opened from the expand button, select the Name field, and uncheck all the others

Image showing the columns ListPrice ProductModelId and table SalesLT ProductModel under that Name is selected

  1. Click the OK button
  2. Double click the Name.1 column header and change the name to ProductModel

Image showing where to change the column name

All the steps executed so far are registered on the properties window, Applied Steps. This is exactly how Power Query works, but until now this experience was available only on dataflows or in Power BI desktop.

One important performance detail about the steps is to know if the steps will be executed in the source database, converted into a single native query on the source database, or if the sequence of transformations prevent this.

The usual way to check this is to right click the last transformation and check if the option View Data Source Query is available. If it’s available, it means the transformations are good enough to be executed as a single native query.

Image showing query settings and how to View data source query

An image showing the data source query

The UI in the portal has some additional features beyond the desktop UI. If you move the mouse over the last step, it tells you how the step will be executed. You can see the same on every step.

An image showing This step will be evaluated by the data source

Creating the Datamart: Second stage, creating a date dimension

A model needs a date dimension. Every fact happens on a date and the date is an important dimension to analyse the fact. In this example, the TransactionDate column is found in the TransactionHistory table.

Why is the TransactionDate field is not enough, you may ask.

When analysing the facts, it might be analyzed by Year, Month, Day, Day of the week, and much more. If relying only on the TransactionDate field, you will need to create DAX measures, and this would impact the performance of your model.

Building a date dimension, which will be stored in the underlying Azure SQL Database for the Datamart, you will not have the need to build so many DAX expressions and the model will have better performance.

You could say there is a “not so old saying” about this: The better the underlying model, the fewer custom DAX expressions will be needed to build in the model. The date dimension is one great example of this, and the Datamart brings the possibility to create a better underlying model, leaving the DAX expressions only for dynamic calculations which really can’t be created in the underlying model.

There are many different methods to create a date dimension. In this example, I will use the M scrips created by Chris Webb on the following blog: https://blog.crossjoin.co.uk/2013/11/19/generating-a-date-dimension-table-in-power-query/

Execute these step-by-step directions to create the date dimension:

  1. On the top menu, click New Query -> Blank Query

An image showing the Power Query menus and Get Data Blank Query

  1. Paste the query copied from Chris Webb’s blog above

An image showing Connect to data source and the query pasted in

  1. Click Next button
  2. In the Properties window, change the name of the new query to BuildDateDimension

You may notice this query is in fact a custom M function. The details about custom M functions are beyond this article, but you can learn more about them watch the recording of some technical sessions about advanced ETL with power query: https://www.youtube.com/watch?v=IjLlqTdF2bg&list=PLNbt9tnNIlQ6s597rRyoGx_sLn4rrHOzv

This function requires two parameters, StartDate and EndDate, to build the date dimension. You can provide these parameters dynamically, so you will always have an updated date dimension. On the next steps, retrieve these values from the TransactionHistory table.

Query settings menu Properties Name BuildDataDim

  1. Right click the TransactionHistory table and click the Duplicate option in the context menu

Image showing right-click menu with Duplicate selected

  1. Repeat the previous step, resulting in two copies of the TransactionHistory table.

Why duplicate and not reference? Since all the transformations will be converted to native queries anyway, duplicating makes it easy to convert each of the queries into an independent native SQL query. If you use reference, future changes to the source query would affect the new query.

I wrote a blog post exactly about this example, you can read more on https://ift.tt/NKvsbcW. 

An image showing a list of queries including TransactionHistory (2) and TransactionHistory (3)

  1. Select the first duplicated query
  2. Select the TransactionDate field
  3. Right-click the column header and click the Remove other columns in the context menu

An image showing the right-click menu of TransactionDate. Remove other columns is selected

  1. Click the button on the TransactionDate header
  2. Click the Sort Ascending menu item

Right-click menu of TransactionDate and Sort Ascending is selected

  1. Click the Keep top rows menu item

Image showing menu. Keep Rows --> Keep top rows

  1. On the Keep to Rows window, type 1

Image showing Keep top rows. Specify how many rows to keep. Number of rows 1

  1. Click the Ok button
  2. On the top menu, change the data type to Date

A date dimension should never include time. If your business needs time, you would need to create a time dimension and include date and time information in different fields

However, these sample tables don’t include time, so changing the data type just ignores the time.

Image showing list of data types. Date is selected

  1. Right-click the date value and select the item Drill down on the context menu

Even after reaching a single value, the result is still a table. The parameter for the function, on the other hand, needs to be a value. Using the Drill down option you are retrieving the date as a single value

Images showing TransactionDate menu. Drill down is selected

  1. Right-click the duplicated table you are working with and disable the option Enable Load

This query will be used only as parameter for the function, you don’t need it in the model. Besides this, if you don’t disable the load, the Power Query UI will convert the single value to table again, adding a new step to the query.

Image showing menu for TransactionHistory (3). Enable Load is selected

  1. Repeat the steps 33-43 for the 2nd duplicated query, but this time sorting the data in descending order
  2. Click the first duplicated table and rename it to MinDate
  3. Click the second duplicated table and rename it to MaxDate

An image showing list of Queries and last two are changed to MaxDate and MinDate

The steps of these queries show some additional features. On the image below you may notice a red database symbol besides one step. This means that step will not be transformed into the native data source query. As a result, all the steps after it will also not be part of the native data source query, they will be executed by Power BI.

On this example, these are the last steps, conversion of the last value retrieved, so there is no problem at all

An image showing the applied steps

  1. Select the BuildDateDimension function
  2. On the button besides the StartDate parameter, change the option to query
  3. On the StartDate drop down, select the MinDate query
  4. On the button besides the EndDate parameter, change the option to query
  5. On the EndDate drop down, select the MaxDate query

An image showing Enter parameters. StartDate is MinDate. EndDate is MaxDate

  1. Click the Invoke function

A new query will be created using the M code needed to invoke the function, what will produce the date dimension

  1. Rename the new query as DateDim

An image showing QuerySettings Properties. Name DateDim Applied steps Fx source

An image showing list of Queries. DateDim is now added

  1. Click the Save button

After clicking the save button, the data will be loaded into the Datamart.

An image showing Objects --> Tables. DateDim, Product, TransactionHistory

Renaming the Datamart

The Datamart is created with an auto-generated name. At some point you would like to rename the Datamart.

Clicking on the workspace name in the list of workspaces on the left side, you will see the Datamart and the auto-generated dataset.

On the Datamart menu, you will find a Rename command.

An image showing the datasets and datamarts and how to rename the datamart.

Once you rename the Datamart, the auto-generated dataset will be renamed at the same time.

An image showing the Rename Datamart dialog

An image showing the list of datasets and datamarts and this time they are renamed to a friendly name AdvWorks

Building the model

The fourth tab on the lower toolbar inside the Datamart is the Model tab. On this tab, you can make model configurations for the tables. It’s time to build the model.

An image showing the icons and the meaning of each one. Data, Design, SQL, Model

  1. Click the Model tab

An image showing the Model and there are 3 tables shown

  1. Organize the tables, leaving the fact table, TransactionHistory, in the middle.
  2. Drag the Date field from DateDim table to the TransactionDate field in the TransactionHistory table
  3. On the Create Relationship window, adjust the cardinality of the relationship. It needs to be 1 to many from DateDim to TransactionHistory

An image showing the Create Relationship dialog

  1. Drag the ProductId field from the Product table to the ProductId field on the TransactionHistory table
  2. On the Create Relationship window, adjust the cardinality of the relationship. It needs to be 1 to many from Product to TransactionHistory

An image showing the model but now the tables are connected with one-to-many arrows

  1. Select the ActualCost field in the TransactionHistory table
  2. On the top toolbar, change the format of the field to Currency

An image showing how to change the format to currency

  1. Right click the DateDim table and click the menu item Mark as Date Table

An image showing the right-click image and Mark as date Table

  1. On the Mark as Date Table window, select the Date field

An image showing Mark as date table dialog

  1. Select the TransactionDate field in the TransactionHistory table.
  2. On the Properties window located on the right side, under Formatting, select the date format containing only the date

An image showing the format of TransactionDate

  1. Select the Date field in the DateDim table
  2. On the properties window located on the right side, under Formatting, select the date format containing only the date

The newly built model will be stored in the auto-generated dataset created together in the Datamart. This dataset can become the base model for all users of the Datamart. Of course, there are many modelling features still missing, such as hierarchies and aggregation tables, but it’s a good start.

Exploratory Analysis: The Design tab

The Design tab is one of the two tabs available to allow exploring the data in the Datamart. Here’s a small example:

  1. Drag the TransactionHistory table to the middle of the Design tab
  2. Drag the DateDim table to the middle of the Design tab

An image showing TransactionHistory and DateDim in the design tab

  1. Click the “+” sign on the TransactionHistory table and select the Merge queries option

An image showing the right-click menu and Merge queries is selected

  1. On the Merge window, under the Right table for merge, select the DateDim table
  2. On the Merge window, in the TransactionHistory table, select the TransactionDate field
  3. On the Merge window, in the DateDim table, select the Date field
  4. Click the Ok button

An image showing the Merge dialog. TransactionHistory and right table is DateDim. Join kind is left join

An image showing DateDim and TransactionHistory. Both are connected

  1. On the lower window with the table visualization, click the Expand button besides the new DateDim column

The DateDim table with expand icon

  1. On the window with the field names to expand, uncheck all the fields and check only Year and MonthName

An image showing the fields. Year and MonthName are selected

An image showing the design. Year and Month name are now in the list of fields

  1. On the merged query, click the “+” sign and select the Group By option

An image showing the menu. Group By is selected

  1. On the Group By window, select the option Advanced
  2. On the Group By window, click the Add Grouping button once to complete 3 grouping fields
  3. On the Group By window, click the Add aggregation button once to complete 2 aggregation fields
  4. On the Group By window, select Year, MonthNumberOfYear and MonthName as the 3 grouping fields
  5. Under New Column Name, type QtyOrders
  6. On Operation drop down to the right of QtyOrders, select Count Rows
  7. On the 2nd New Column Name, type OrdersTotal
  8. On the Operation drop down to the right of OrdersTotal, select Sum
  9. On the Column drop down, to the right of Sum operation, select ActualCost

An image showing the Group by dialog

  1. Click Ok button

As a result, you have the total of the orders by month

An image showing the results. For each year and month there are totals for QtyOrders and OrderTotal

Exploratory Analysis: The SQL tab

The 2nd tab which allows exploratory analysis is the SQL table. You can execute SQL statements over the Datamart

Type the following statement on the SQL tab:

select Year, MonthName,sum(ActualCost) as OrdersTotal
 from TransactionHistory
inner join DateDim
    on TransactionHistory.TransactionDate=DateDim.Date
Group By Year, MonthName

Click the Run button to execute the query

An image showing the Run icon

At the moment I’m writing this article, the results window still has a small secret. You can view the results together with the SQL statement, but you need to resize the window from top to bottom for that.

An image showing the results

An image showing that it's possible to see then query when expanding the top

The user can click the Excel button to open the query result in Excel

An Excel file will be downloaded. Once you open it, you will need to click the button Enable Editing. After that, a second message will appear, and you will need to click the button Enable Content.

An image showing Enable Editing

An image showing Enable Content

Excel will connect directly to the Azure SQL Database and execute the query. The user using Excel needs permission to connect to the underlying Azure SQL Database.

On the Native Database Query window, click the Run button. The query will be executed, and the result inserted in Excel.

An image showing the Native Database Query and the Run button

An image showing the results in Excel

Yes, you have access to SQL

The Power BI Datamarts underlying technology is an Azure SQL database. After all the exploratory analysis features mentioned above, the icing on the cake is a direct connection to Azure SQL Database.

First, you need to locate the connection string for the Azure SQL Database. In the Datamart settings, under Server Settings, you can find the connection string and copy it to be used for connection in another application. For example, you can use SSMS, paste this connection on SSMS connection string to access the Azure SQL Database.

An image for AdwWorks settings

The authentication is made with Active Directory – Universal with MFA. The login is the Power BI login.

An image showing the Connect to Server dialog for SQL Server

You may notice there are no tables in the database, only views. All the tables created in the model appear as views. The database is completely read only, but the ability to connect to the Datamart using any tool capable to connect to SQL is a very powerful feature.

An image showing the list of database objects in Object Explorer and the Views in the dataset

On my blog about Power BI and ETL, one of my arguments was the fact the ETL in Power BI was only capable to save the data to Power BI. The evolution of the technology always makes the borders between different technologies more difficult to find. I may need to update that article soon.

An image showing the results of running select top 10 * from transactionhistory

Using the Datamart to build reports

The Datamart should become the central single source of truth for one area of the company. Whether the Datamart is built using a top-down or bottom-up approach, it’s still a central single source of truth.

For example, if the Datamart is using the bottom-up approach, it will be the central point to integrate all user’s data sources, such as excel, sharepoint lists and many kinds of data sources starting from a small spreadsheet and growing in an uncontrolled rate. It will not be the central point for the entire company, but for one company branch, for example.

On the other hand, in a top-down approach the Datamart is built as a subset of the company data warehouse. This subset may be focused on one branch, and it will be the single source of truth to this branch.

These are some important points which makes the Datamart a good local single point of truth:

  • Calculations which in other ways would be made using DAX formulas and turn the model slower, can be done using physical tables and result in a better model
  • The model stored in the auto-generated dataset can be used as a base for all local reports and additional models.
  • There are many features for exploratory analysis, including direct SQL access to the data

There are three different methods to use the Datamart:

  • Use the portal to create reports based on the auto-generated dataset

The reports will be using the auto-generated dataset directly. Depending on the number of different departments using the auto-generated dataset, this may not be the best solution

  • Create reports directly accessing the underlying Azure SQL connection

This is a very good solution, but every report solution using this direct connection would need to build the model again, without re-using the model already built in the auto-generated dataset

  • Use Power BI desktop to create reporting solutions using the auto-generated dataset as a source

This is probably the best solution for the use of the Datamart. You will be able to re-use the model built in the auto-generated dataset and customize it with additional information needed.

Summary

The Datamarts are more than a very powerful feature, it’s also a critical point in the Power BI evolution. More consistent data exploration tools and consistent tools to create a local single source of truth. It has the potential to change the architectures used to build in Power BI, and I believe everyone all will be looking forward to the new features to come.

 

The post Datamarts and exploratory analysis using Power BI appeared first on Simple Talk.



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

Wednesday, May 25, 2022

How to troubleshoot and fix PostgreSQL performance issues

PostgreSQL is a popular database that is used by many applications. It’s been in active development for 30 years! PostgreSQL (or Postgres) is a powerful database management system (DBMS) that you can use and worry less about performance.

Although Postgres has a powerful optimizer and can fix performance issues for you, sometimes you have to tweak your query to improve your query performance. You will find why in the next section.

Many developers tend to write the query first and then optimize it later. This is often not a good practice because it makes the query more complex and will make it harder to understand and thus difficult to optimize. This is why it’s better to write the query the right way from the start.

This article talks about specific techniques to improve query performance; however, the most important thing is to understand how a database engine processes the query, what a query planner is, and how it decides what execution plan to use.

In this tutorial, you will learn about optimization techniques when you imagine yourself as a database engine. Think from the perspective of a database engine, and then decide what your query should be optimized for.

It’s not an easy task to optimize a query, but if you understand the basics of query optimization, you can go far and make your queries performant.

Understanding the SQL nature

Why would two queries that give the same result drastically differ in execution time? It’s a difficult question.

The source of the problem is that SQL is a declarative language. That means you describe what the result of the query should be and not how the query should be executed.

The reverse is true for the imperative language. It means you describe how the result will be obtained through the sequence of the steps that will be executed.

Under the hood, the database optimizer chooses the best way to execute the query. How is best determined? Many factors come into play such as storage structures, indexes, and data statistics.

Setting up a Postgres database

First set up the environment used in this tutorial so that you can follow up on the performance issues that will be tackled.

I’m assuming that you have already installed Postgres on your machine. Begin by creating a new database.

$ sudo -u postgres psql -c "CREATE DATABASE testdb;"

Note: The shell commands run in this tutorial are used on a Linux/Mint system.

Now, the testdb database has been created.

Setting up Postgres tables

To be able to create tables, you need to be connected to the database through a SQL client or a command line tool like psql.

If you want to access the database from the command line, you can use the following command:

$ sudo -u postgres psql

and to connect to the database, you can use:

postgres=# \c testdb
testdb=#

The prompt postgres=# indicates that my machine is, by default, connected to the postgres database. Once that prompt is changed to testdb=#, you are connected to the testdb database.

This example creates two tables: genders and employees. Feel free to name them with your conventions. I just prefer the plural nouns for tables.

For the rest of this tutorial, I’ll use a SQL client like DBeaver, so don’t be surprised when you no longer see the prompt testdb=#.

Create the genders table:

CREATE TABLE genders (id int, name text);

INSERT INTO genders
VALUES (1, 'male'), (2, 'female');

Confirm with SELECT *:

SELECT * FROM genders;

Editor’s note: For simplicity of the examples, only two genders are listed, but, in practice, there will be more.

Create the employees table:

CREATE TABLE employees (id serial, gender_id int, hire_date date);

Now populate 5 million entries in the employees table:

INSERT INTO employees (gender_id)
SELECT x % 2 + 1
FROM generate_series(1, 5000000) AS x;

UPDATE employees SET hire_date = '2020-04-01' WHERE id < 101;
UPDATE employees SET hire_date = '2021-04-01' WHERE id BETWEEN 101 AND 1000000;
UPDATE employees SET hire_date = '2022-04-01' WHERE id BETWEEN 1000001 AND 5000000;

Note that the first column gender_id in the previous query contains 1’s and 2’s and is evenly distributed across the 5,000,000 records. However, the hire_date column is distributed non-uniformly to be able to play with different distributions in this tutorial.

To see the differences in performance, look at execution time. If you’re using psql, turn on the execution time with \timing. The DBeaver SQL client calculates the execution time for you.

This example aggregates the genders table by how many females and males are employees.

SELECT g.name, count(g.name)
FROM genders AS g, employees AS e
WHERE g.id = e.gender_id
GROUP BY 1;

This query takes around 10.7 seconds on my machine.

name  |  count  
--------+---------
 female | 2500000
 male   | 2500000

Tracking the execution time is the easiest way to diagnose a performance issue. Next, find out more ways to diagnose and fix performance issues.

Using EXPLAIN

One of the most important tools for debugging performance issues is the EXPLAIN command. It’s a great way to understand what Postgres is doing behind the scenes. The result would be the execution plan for the query. This plan is a tree of nodes that Postgres uses to execute the query.

Run this to see the plan for the previous query:

EXPLAIN SELECT name, count(g.name)
FROM genders AS g, employees AS e
WHERE g.id = e.gender_id
GROUP BY 1;

which outputs the following in my case:

Finalize GroupAggregate (cost=757108.87..757113.87 rows=200 width=40)
   Group Key: g.name
   -> Sort (cost=757108.87..757109.87 rows=400 width=40)
        Sort Key: g.name
        -> Gather (cost=757049.58..757091.58 rows=400 width=40)
            Workers Planned: 2
            -> Partial HashAggregate (cost=756049.58..756051.58 rows=200 width=40)
                 Group Key: g.name
                 -> Hash Join (cost=38.58..675062.54 rows=16197408 width=32)
                      Hash Cond: (e.gender_id = g.id)
                      -> Parallel Seq Scan on employees e (cost=0.00..101737.73 rows=2550773 width=4)
                      -> Hash (cost=22.70..22.70 rows=1270 width=36)
                           -> Seq Scan on genders g (cost=0.00..22.70 rows=1270 width=36)

 

When you explore each node of the previous execution plan, you’ll find different data access algorithms whether it is a sorting, grouping, hash aggregating, or hash joining. These algorithms are computed by the Postgres optimizer. The optimizer chooses the best way to execute the query. This decision depends on the data and the query itself.

But how to read such execution plan? Look at the bottom of that plan. You’ll see a sequential scan is done on genders table. This means that the optimizer has chosen a simple sequential scan on all rows of genders table.

This seq scan is followed by parentheses and includes some information: the cost, rows, and width. The cost has two numbers; the estimated startup cost (e.g., if you have a sort node, it would be the time to do the sorting), and the estimated total cost which assumes all available rows, related to this node, are retrieved.

The rows value defines the estimated number of rows output by this node.

The width indicates the estimated average width of rows output size (in bytes) by this plan node.

How fast the query is executed depends on the selectivity ratio. This ratio is the ratio of the number of retained rows to the total number of rows in the stored table.

It’s better to seek a low selectivity ratio to avoid the read operation cost.

The worst-case scenario is to have a selectivity ratio of 1. In this case, the optimizer will do a full scan of all the rows in the table. The engine consecutively reads all the rows in a table and checks the filter condition on each block.

Note: A block is the unit of storage that is used to transfer data from disk to memory. The block size is fixed, and it’s 8192 bytes in Postgres.

To understand how the optimizer makes different decisions depending on the selectivity ratio, filter a big chunk of the employees table by the following query:

EXPLAIN SELECT hire_date
FROM employees
WHERE hire_date = '2022-04-01';

The following execution plan is returned:

Seq Scan on employees (cost=0.00..152753.19 rows=4924828 width=4)
   Filter: (hire_date = '2022-04-01'::date)

Note that this big chunk that is filtered out is around 4 million rows out of the total 5 million rows. That’s why there is a high selectivity ratio. Since the optimizer is smart, it has chosen the sequential scan algorithm.

However, the optimizer can choose a different execution plan for the same query if you just change the filter condition in the WHERE clause.

EXPLAIN SELECT hire_date
FROM employees
WHERE hire_date = '2020-04-01';

which results in the following execution plan:

Gather (cost=1000.00..109114.76 rows=1 width=4)
  Workers Planned: 2
  -> Parallel Seq Scan on employees (cost=0.00..108114.66 rows=1 width=4)
       Filter: (hire_date = '2020-04-01'::date)

This is because the selectivity ratio is low (100 rows out of 5 million rows returned), so the Postgres optimizer plans two workers to execute the query in parallel.

Note that you can look at a detailed execution time of the query by the EXPLAIN ANALYZE command. Just write it before the SELECT statement.

Using indexes

PostgreSQL (like any relational database) allows additional, redundant data structures to speed up the table access more than a sequential scan.

These data structures are called indexes.

Indexes are described as “redundant” because they do not store new information than the data is already stored in the table.

What exactly do indexes do? They provide data access paths to the table. They allow you to access the rows without having to read the entire table.

If there is a filtering condition on the table, then the index allows you to only read the blocks that match the condition. These are determined by the pointers. The underlying data structure is a heap. A heap is a tree-like data structure which means rows are stored in an unordered fashion.

The cost of the heap algorithm becomes higher than the full scan if the selectivity ratio is high.

For small values of selectivity, the cost is proportional to the number of blocks that match the condition.

The next section demonstrates how creating an index will speed up queries in different scenarios.

Unique indexes

A unique index supports any primary key or a unique constraint on the table.

A table can have a single primary key (though it’s not a requirement) and multiple unique constraints. Note that the definition of the genders table didn’t specify id as the primary key.

You can alter the genders table with a new primary key:

ALTER TABLE genders
ADD CONSTRAINT genders_pkey PRIMARY KEY (id);

If, by mistake, you try to alter another primary key in the same table as the following query:

ALTER TABLE genders
ADD CONSTRAINT genders_pkey2 PRIMARY KEY (name);

you will see the following error:

SQL Error [42P16]: ERROR: multiple primary keys for table “genders” are not allowed

What you can do instead is to create a unique constraint on the name column:

ALTER TABLE genders
ADD CONSTRAINT genders_name UNIQUE (name);

For the employees table, the primary key is done here:

ALTER TABLE employees
ADD CONSTRAINT employees_pkey PRIMARY KEY (id);

and the index is created on the same pkey:

CREATE INDEX employees_id ON employees(id);

To utilize these features, create unique indexes on these constraints.

CREATE INDEX genders_id ON genders(id);

and another index on the name column:

CREATE INDEX genders_name_idx ON genders(name);

It is also possible to create a unique index without formally creating a unique constraint. Just add the keyword unique to the index statement:

CREATE UNIQUE INDEX genders_name_idx on genders(name);

Note that if there are any duplicate values in the column, the index will not be created.

How about foreign keys? Alter the gender_id column in the employees table:

ALTER TABLE employees 
ADD CONSTRAINT employees_gender_id_fk FOREIGN KEY (gender_id)
REFERENCES genders (id);

If searches by the foreign key gender_id become slow, you need to explicitly create an index on the column:

CREATE INDEX employees_gender_id on employees(gender_id);

Originally, the query took 10.7 seconds on my machine:

SELECT g.name, count(g.name)
FROM genders AS g, employees AS e
WHERE g.id = e.gender_id
GROUP BY 1;

Now, I get an execution plan that makes use of the index employees_gender_id executed at around 1.4 seconds:

Finalize GroupAggregate (cost=125538.79..125538.84 rows=2 width=40) (actual time=1349.107..1351.767 rows=2 loops=1)
  Group Key: g.name
  -> Sort (cost=125538.79..125538.80 rows=4 width=40) (actual time=1349.101..1351.760 rows=6 loops=1)
       Sort Key: g.name
       Sort Method: quicksort Memory: 25kB
       -> Gather (cost=125538.33..125538.75 rows=4 width=40) (actual time=1349.080..1351.742 rows=6 loops=1)
            Workers Planned: 2
            Workers Launched: 2
            -> Partial HashAggregate (cost=124538.33..124538.35 rows=2 width=40) (actual time=1343.562..1343.563 rows=2 loops=3)
                 Group Key: g.name
                 -> Hash Join (cost=1.04..114121.66 rows=2083333 width=32) (actual time=0.097..790.907 rows=1666667 loops=3)
                      Hash Cond: (e.gender_id = g.id)
                      -> Parallel Seq Scan on employees e (cost=0.00..97063.33 rows=2083333 width=4) (actual time=0.030..302.195 rows=1666667 loops=3)
                      -> Hash (cost=1.02..1.02 rows=2 width=36) (actual time=0.018..0.018 rows=2 loops=3)
                           Buckets: 1024 Batches: 1 Memory Usage: 9kB
                           -> Seq Scan on genders g (cost=0.00..1.02 rows=2 width=36) (actual time=0.012..0.013 rows=2 loops=3)
Planning time: 0.323 ms
Execution time: 1351.849 ms

Note that although there’s an index for the genders table, the optimizer decides on a sequential scan as indicated in the execution plan in this part:

-> Seq Scan on genders g (cost=0.00..1.02 rows=2 width=36) (actual time=0.012..0.013 rows=2 loops=3)

This happens because the genders table is only two rows, so there is no need to create an index on that table because the optimizer is smart enough to choose a full scan algorithm.

Partial indexes

One of the best features of PostgreSQL is partial indexes. Partial indexes are indexes that only cover a subset of the table.

For the unlikely case that the hire date is on an early date like April 4, 2020, create a partial index on the hire_date column:

CREATE INDEX employees_hire_date_2020 on employees(hire_date) where hire_date = '2020-04-01';
SELECT hire_date
FROM employees
WHERE hire_date = '2020-04-01';

And here is the execution plan:

Index Only Scan using employees_hire_date_2020 on employees (cost=0.14..4.16 rows=1 width=4) (actual time=0.022..0.031 rows=100 loops=1)
  Heap Fetches: 0
Planning time: 0.224 ms
Execution time: 0.045 ms

Note that before the index was created, the query took about 400ms to run on my machine.

Conclusion

You’ve have seen how to optimize queries in PostgreSQL and fix the performance issues that you’ve have been facing. This article covered how the optimizer works and how to create indexes, constraints, and partial indexes.

 

The post How to troubleshoot and fix PostgreSQL performance issues appeared first on Simple Talk.



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