Wednesday, May 24, 2023

Data Intelligence on light speed: Microsoft Fabric

This article is based on exciting information just released at Microsoft’s Build conference on May 23, 2023.

What we have today

When Synapse Analytics was created, technical sessions inspired me with some comparisons and explanations, and I reproduced them in my own technical sessions and writing.

Synapse was created from a request from many Microsoft customers. They requested to be able to use one single tool for the entire data intelligence platform: Ingest Data, store, process, query, apply data science, and generate reports.

Synapse is a real Swiss Army knife: We can make ingestion using Synapse Data Factory; query and process the data using different methods, Serverless SQL Pool or Dedicated SQL Pool; and apply data science using spark pool and additional ML frameworks. Finally, Synapse is also linked to Power BI, allowing us to use some shortcuts to create visualizations.

This unique set of features were always great, much better than the isolated tools we had before. But on the light of Microsoft Fabric, we can notice the missing points on Synapse:

  • The integration of the different tools was limited. It was the best for the time, but compared with Microsoft Fabric, the integration was limited.
  • We still need to decide between different infrastructure resources, such as Serverless SQL Pool and Dedicated SQL Pool, instead of using all together over the data.
  • We still need to make decisions about infrastructure, especially the size of the dedicated SQL Pool. Many times, decisions were based mostly by guess.
  • It doesn’t totally isolate storage and processing. When using a Dedicated SQL Pool, processing and storage are tied together.

Synapse is considered so advanced that only a few noticed these problems, and not all the problems. Microsoft Fabric, the new product announced during BUILD, exposes to us this and more.

What’s Microsoft Fabric

Like Synapse, Microsoft Fabric brings all the services needed for a data intelligence environment aggregated together, heavily integrated and built in a way that requires far less technical effort for the implementation.

The image below illustrates the services included in Microsoft Fabric

Interface gráfica do usuário, Aplicativo Descrição gerada automaticamente

In the following sections I will introduce these new concepts.

Data Intelligence as Software as a Service (SaaS)

Microsoft Fabric arrives, breaking standards and solidifying new ones. In the cloud environment, we are used to classify the services as Infrastructure as a service (IaaS), Platform as a service (PaaS) and SaaS. Synapse is classified as a PaaS, while Microsoft Fabric is officially classified as SaaS. The following chart shows the general areas that each level of management that each level of hosted management provides.

A screenshot of a cell phone Description automatically generated

Undoubtedly, the level of managed services provided by Microsoft Fabric is way above Synapse. Many tasks in Synapse would need to be carefully configured, yet in Microsoft Fabric brings a kind-of auto-settings, just working out of the box.

Usually, when we think about a SaaS service, we think about an end user application, such as Office 365 or many other applications where the user just uses it. It’s a concept that usually doesn’t match software used to ingest, transform, model and generate intelligent results from data.

That’s what Microsoft Fabric is, a software breaking the barriers of what we know about cloud software and services.

A different environment

Microsoft Fabric is not located inside the Azure environment but rather inside Power BI Portal. This leads to a very different environment than the one we have in Synapse.

But the new environment is not like anything we know about Power BI Portal as well. The environment is organized for different experiences: You select a experience according to the kind of task you would like to execute, and the environment will adapt to the usual tasks related to this experience.

The following experiences are available:

  • Power BI: The typical Power BI environment and tools
  • Data Factory: Using this persona, you can create and manage dataflows and data pipelines as in data factory.
  • Data Activator: This is an entirely new feature which enables you to create triggers over your visuals in Power BI
  • Data Engineering: This experience involves multiple tasks. It’s responsible for creating and managing the lakehouses, but it’s also the one that will allow you to create notebooks and orchestrate them with pipelines.
  • Data Science: Using this experience, you can apply Azure ML techniques over your data.
  • Data Warehouse: This experience allows you to model your data as in a SQL database and use SQL over your data. It’s difficult to compare this to anything else. We can create many star models over our data lake and these models will be reused by our Power BI datasets, making it easier to have a central model for all our reports.
  • Real-time Analytics: This persona is in some ways comparable with Power BI Streaming Dataflows, allowing ingestion of real time data.

Changing from ingestion (Data Factory), processing (Data Engineering), Modelling and SQL (Data Warehouse), and more is just a matter of choosing the correct experience to make the work over the same sets of data.

The change of the personas is like a method to focus the environment on the kind of activities you would like to execute. The object’s creation itself is still happening inside a Power BI workspace.

Besides that, the main new objects: a lakehouse and a data warehouse, have their own way to switch the work between one and another.

Microsoft Fabric and OneLake

OneLake is the core service in Microsoft Fabric. It provides a data lake as a service, allowing us to build our data lake without all the trouble of provisioning it first. It’s the central data storage for all data in Microsoft Fabric and it’s provisioned for the tenant when the first Microsoft Fabric artifact is created.

The name OneLake also matches very well with the shortcut feature in the OneLake: We can create shortcuts to files located externally and access them directly as if they were in our own lake.

The image below illustrates how the OneLake relates with the other Microsoft Fabric features.

Interface gráfica do usuário Descrição gerada automaticamente

Onelake, Lakehouse and Workspaces

The lakehouse is one of the core objects we can create inside a Onelake. We create the lakehouse using the Data Engineer persona and the lakehouse will be contained inside a Workspace, which we know as a Power BI Workspace.

Interface gráfica do usuário, Aplicativo Descrição gerada automaticamente

Once we create a lakehouse, we can use Data Factory to ingest data into the files area or the tables area.

Interface gráfica do usuário, Aplicativo Descrição gerada automaticamente

The Files area is the unmanaged area of the lake, which accepts any kind of file. That’s where we put the RAW files for further processing. The Tables, on the other hand, contains data only in Delta format.

The lakehouse optimizes the Tables area with a special structure capable to make a regular delta table up to 10x faster while still maintaining full Delta format compliance.

However, the lakehouse is not the biggest data structure we have. This position is reserved for the OneLake. It is an invisible, auto-provisioned data storage containing all the data for data warehouse, lakehouses, datasets and more.

In this way, we can build an enterprise architecture using Workspaces to hold departmental lakehouses. The data can be shared across multiple departments using lakehouse shortcuts. This ensures the domain ownership of the data and a relationship between domains at the same time.

Tela azul com letras brancas Descrição gerada automaticamente

This is only the starting point of an enterprise architecture: The OneLake ensures a unified management and governance of the data. Data Lineage, Data Protection, Certification, Catalog Integration and more are unified features provided by the OneLake to all lakehouses created in an enterprise.

All these features are inherited from the Power BI environment, ensuring an Enterprise Governance environment to the company.

OneLake and Processing Isolation

When using Synapse, the Synapse Dedicated Pool stores and process the data. This is a scenario where storage and processing are tied together.

In OneLake, storage and processing are independent. The same data in the OneLake can be processed by many different methods, ensuring the storage and processing independence.

Let’s analyse the different methods we have available to process the data in OneLake.

Spark Notebooks

All the workspaces enabled for Microsoft Fabric have a feature called Live Pool. The Live Pool allows the execution of notebooks without the need to previously make the Spark Cluster configuration.

Once the first code block is executed in a notebook, the Live Spark Pool kicks in in a few seconds and makes the execution.

We can process the OneLake data using Spark Notebooks with the advantage of the Live Pools

Data Factory

Data Factory objects, such as pipelines and dataflows, inside the Power BI environment are a start of a unification of the ETL tools: We have the Pipelines and Dataflows from data factory and the dataflows from Power BI.

Diagrama Descrição gerada automaticamente

These two are now united and working together under Microsoft Fabric. We have an additional advantage: the Dataflows Gen2.

The Dataflows Gen2 are an advance in relation to the Power BI Dataflows or Wrangling Dataflows we are used to. One of the most interesting features, in my opinion, is the possibility to define the target of a transformation, what we never could do in Power BI Dataflow (or Wrangling Dataflows)

Interface gráfica do usuário, Aplicativo Descrição gerada automaticamente

SQL Queries

The Microsoft Fabric provides two different methods to access the data using SQL, as if the data is in a regular database.

One of the methods is using the Lakehouse object. This object provides us a SQL Endpoint, which allows us to model the tables and query the data using SQL.

The second method uses a Data Warehouse object, which provides a complete SQL processing environment over the data in the OneLake.

The table below highlights all the differences between the Lakehouse SQL Endpoint and the Data Warehouse. Some of these differences are available in the documentation; some are my personal conclusions.

Microsoft Fabric Offering

Warehouse

SQL Endpoint of the Lakehouse

Processor Engine

SQL MPP – Polaris

Optimization Engine

Vertipaq

Vertipaq for Tables

Storage Layer

Open Data Format – Delta

Primary Capabilities

ACID compliant

Full data warehouse with transactions support in T-SQL

Read Only, system generated SQL Endpoint for lakehouse for T-SQL Querying and serving.

Supports queries and views on top of lakehouse delta tables only

Recommended Use Case

  • Data Warehousing for Enterprise Use
  • Data Warehousing supporting departmental, business unit or self-service use
  • Structured Data Analysis in T-SQL with tables, views, procedures and functions and Advanced SQL Support for BI
  • Exploring and querying delta tables from the lakehouse
  • Staging Data and Archival zone for analysis
  • Medallion architecture with zones for bronze, silver and gold analysis
  • Pairing with warehouses for enterprise analytics use cases

Development Experience

  • Warehouse editor with full support for T-SQL data-ingestion, modeling, development and querying UI experience for data ingestion, modeling and querying
  • Read/Write support for 1st and 3rd party tooling
  • Lakehouse SQL Enpoint with limited T-SQL support for views, table valued functions and SQL Queries
  • UI experiences for modeling and querying
  • Limited T-SQL support for 1st and 3rd party tooling

T-SQL Capabilities

Full DQL, DML and DDL T-SQL support. Full transaction support

Full DQL, no DML, limited DDL T-SQL Support such as SQL Views and TVFs

Data Loading

SQL, pipelines, dataflows

Spark, pipelines, dataflows, shortcuts

Delta Table Support

Reads and Write Delta Table

Reads Delta table

Power BI

Microsoft Fabric is deeply linked to the Power BI environment. We can in many points of our work, either from a lakehouse or a warehouse, start the creation of a Power BI report.

The best is the access method: Power BI has a new access method to the OneLake, called Direct Lake.

Direct Lake is a new connection method between Power BI Datasets and the OneLake.

When we use DirectQuery, every refresh requires a new load of the source, which makes the connection slower. On the other hand, when we use Import, the data is stored in memory and the performance is better, but when the data is updated, a refresh on the dataset is needed. Updates are not immediately visible on datasets and reports.

The Direct Lake connection mix the best of both scenarios: It has the performance of the Import mode for keeping the data in memory, and the real time update of the data achieved by the DirectQuery.

Uma imagem contendo Diagrama Descrição gerada automaticamente

What about Azure Synapse and Data Factory

Customers using Data Factory and Synapse Dedicated Pool can also expect easy ways to migrate to Microsoft Fabric. Micorosoft is focused on making the transition as smoothy as possible.

Data Factory users have even the benefit of Gen2 dataflows, which are not supported by Azure data factory. So, you have advantages in developing dataflows and pipelines using Microsoft Fabric and you will an easy migration path from one to another.

Conclusion

Microsoft Fabric seems to be the start of a new era. In a time of Open AI/ChatGPT and co-pilots, we are getting an extremely powerful tool making complex data solutions accessible to all companies and the in the future we can think about a co-pilot for Microsoft Fabric

The post Data Intelligence on light speed: Microsoft Fabric appeared first on Simple Talk.



from Simple Talk https://ift.tt/0bgDpJn
via

Self Review: Practical Graph Structures in SQL Server and Azure SQL

I just finished writing this book a few weeks ago, and as I read it, I thought “why not review my own book?” Of course, the question that first comes to mind is “are you insane?” It seems like a no-win proposition. Anything less than “best book evah” and it will seem like false modesty. In reality what I want to do is write out my feelings on where SQL Server’s feature is, what I covered, and how I feel about it.

Today the book arrived at my doorstep and I knew this is the time to press upload on this blog too.

This is a book I have worked on for many years informally, but over two and a half years ago, I sent my proposed table of contents to my then-editor Jonathan Gennick. Jonathan works for a different publisher now but is still listed as the book’s editor.

In other words, I worked really hard on this book on and off for a very long time. (The off times were both health-related and my hopes for SQL Server 2022 to make even more progress.) I had high hopes for it, and in the end… well, let’s not give it away yet. Am I proud of this book? Yes, and not just because of the likelihood that Apress wouldn’t let me write again if I didn’t say I was. Honestly, if I wasn’t proud of the book, I would I have done what I could to quit the project.

I do fear two things:

  1. I missed something huge and/or fantastic in the tool
  2. I get complaints because I don’t go deep enough into all the different uses of graphs.

One thing I wanted to make clear when I wrote this is that it is a book about programming in T-SQL as of May 2023. I did start out the book with a bit of theory and a little design, but what I set out to show was to give examples of everything you can do right now in T-SQL. In this task, I think. I did at the very least, adequately.

While it is not reflected in the book, as I was thinking about how to describe the content, I realized the book really could be considered to have 3 main sections:

Section 1: Chapters 1 and 2 basically try to establish what a graph is, how it can be used, etc. If I do a second edition someday, this will likely need to be deeper. But it is what led me down the path to working with graph structures.

Section 2: Chapters 3 and 4 are syntax and techniques. Showing how the SQL Server Graph objects work, showing off the specific SQL Graph syntax. In some respects, this goes back to using things like recursive CTEs where useful.

Section 3: The last four chapters of the book give some basic examples of how to use a graph.

  • Chapter 5 implements the tree structure using SQL Graph.
  • Chapter 6 shows an alternative solution for storing a graph, adds helper tables to optimize viewing data from the graph, and then shows how queries using all the methods perform.
  • Chapter 7 implements a directed acyclic graph that is not a tree, showing a few techniques that use SQL Graph syntax specifically and some of the ways you get around current limitations.
  • Chapter 8 contains a relatively simple network structure that implements people following each other and their interests. It, too, shows the performance of different queries.

It is probably not a big surprise that SQL Server’s graph implementation is fairly weak at this point and that they did not make any syntactical changes to the feature in 2022. The stark reality is, if no one uses this feature, it may languish for years to come. Even with the product’s limitations, it is a useful feature once you get past the somewhat complex syntax used to work with graph data in SQL Server. And putting this graph syntax together with basic relational coding can give you something pretty useful.

The bottom line is that I feel like If you want to use the SQL Server graph feature in your company software, this book will do well in introducing and demonstrating the feature as it stands in SQL Server 2022. But of course, that is my opinion; I look forward to your opinion. You can email me at louis@drsql.org if you have comments, negative or positive.

I will also occasionally peek at the reviews on Amazon and other booksellers, so please say if you have feelings or things I should add to a future iteration of the book. Anything I learn will show up on this blog and in my github repository: https://github.com/drsqlgithub/GraphBook1 .

 

The post Self Review: Practical Graph Structures in SQL Server and Azure SQL appeared first on Simple Talk.



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

Monday, May 22, 2023

Optimizing MySQL: Adding Data to Tables

Welcome back to the MySQL optimization series! In case you haven’t been following this series, in the past couple of articles we have discussed the basics of query optimization, and told you how to optimize SELECT queries for performance as well.

In this blog, we’re further learning ways to optimize INSERT operations and look at alternatives when you need to load more than a few rows in the LOAD DATA INFILE statement.

How Does INSERT Work?

As the name suggests, INSERT is the query that’s used to create data in tables in a database. The internal functioning of a basic INSERT query is pretty much identical to that of aSELECTstatement as seen in the previous article, first, the database checks for permissions, opens tables, initializes operations, checks whether rows need to be locked, inserts data (updates the indexes), and then finishes coming to a stop.

We can back this up by performing some profiling:

D:\Redgate\Blogs\October 2022\Optimiziation Series\Optimizing INSERT Queries\Images\INSERT Profiling - 1.png

Image 1 – INSERT Query Profiling – the Query

D:\Redgate\Blogs\October 2022\Optimiziation Series\Optimizing INSERT Queries\Images\INSERT Profiling - 2.png

Image 2 – INSERT Query Profiling – Status and Duration

To know what these status codes mean in detail, please refer to preview blog about SELECT queries where we explain them one by one, but in a nutshell, the profiling codes outlined above enable MySQL to figure out the following things, amongst others:

  • Whether appropriate privileges have been set.
  • Whether tables are ready to perform any operations on (i.e., whether they are locked or not.)
  • How best to perform the INSERT operation. This step includes*:
    • Sending the query to the server.
    • Parsing the query.
    • Scanning the table for any indexes or partitions.
    • Inserting rows into tables
    • Adding data to applicable indexes.
    • Closing the process.

* Do note that each step takes up a proportion of the total time INSERT queries take. According to the MySQL documentation, the fastest process is the closing of the query, the second fastest one pertains to sending the query to the server and parsing it, and the slowest is adding data to the table. (Note that for very small amounts of data, connecting to the server can be more costly).

As far as profiling is concerned, it’s indeed helpful when performing read operations, but not very much in other cases: knowing how queries work is a good thing to do, but when optimizing INSERT queries, profiling doesn’t take us far and that’s why we need to employ techniques that we’ll share with you in a second.

Another thing to remember is that no matter what database management system is in use (INNODB, etc.), many queries go through the same steps – INSERT queries share many steps with SELECT queries too, however, while there are a lot of shared steps, it’s important to remember that all queries are different in their own regard too – an INSERT query is different from a SELECT query in that SELECT queries benefit from indexes and partitions, while they generally make INSERT queries slower.

Advanced DBAs will also know that INSERT queries are sometimes used in concert with SELECT queries – we’ll start from the basic ways that will help you improve your INSERT query performance, then gradually evolve towards more complex scenarios.

Basic Ways to Improve INSERT Query Performance

To improve INSERT query performance, start with the advice above: profile your queries, then remove indexes or partitions on a table if necessary. All indexes and partitions will make all INSERT queries slower because of one simple reason – every time data is inserted into a table, all indexes and partitions on that table must be updated for the database to know where the row resides. That’s true no matter what kind of partitions or indexes are in use – the more partitions or indexes exist on a table, the slower your query will become.

Note: Remember that performance tuning must be treated as a holistic activity and we are focusing on tuningINSERT statements only here. Indexes are needed by most of your SQL statements and unless you are adding a LOT of data to your table, removing them just to make a particular INSERT operations go a little bit faster (and then killing read performance) is typically not desirable.

Another very popular and simple way to improve query performance is to combine small operations into a single, larger operation. We can also lock tables and unlock tables only when all operations are completed, and these approaches look like so:

D:\Misc\INSERT Query Optimization\Screenshot_1.png

Image 3 – a basic way to improve INSERT query performance.

And that’s the crux of it – to optimize INSERT query speed, we need to “think big” in terms of queries. The whole magic goes like this: instead of having many queries that insert a couple of rows each, run one huge query that inserts many rows at once after making sure that all the table locks, index updates, and consistency checking are as delayed as possible (ideally delay these processes until the very end of the query.)

When it is feasible, delaying everything isn’t hard and can be done by following some or all these steps. Consider performing these steps if you’re working with more than a million rows and (or) whenever you see that your INSERT queries can be combined into a single operation just like in the example above (it’s not necessary to follow the steps from the top to bottom – following one or two steps will usually be a good start):

  1. Lock the tables before inserting data into them and unlock them once all the data has been inserted, but not before (see example above.) By locking your tables, you will ensure that the data within them will not be modified while the data will be inserted.
  2. Consider starting a transaction (START TRANSACTION) before running INSERT queries – once done, issue a COMMIT query.
  3. Avoid adding any indexes before insert operations have been completed.
  4. If possible, make sure that the table you’re inserting data into is not partitioned because partitioning splits your table into sub-tables and once you insert data into your table, MySQL has to go through a couple of additional steps to figure out which partition to insert what data into, etc. Also, while the proper use of partitions help improve the performance of SELECT statements, partitioned tables will inevitably take up a little more space on the disk, so be wary of that.

Follow these steps and that’s it – you’re on the way to INSERT heaven! However, do note that these are only the basics and such an approach may not cover your scenario – in that case, we may need to perform some additional optimization by allocating the number of I/O threads within InnoDB by modifying my.cnf (refer to the options in the screenshot below), or improve query performance by doing other things you will learn in this article. Keep reading – your INSERT query performance will soon skyrocket!

Improving INSERT Query Performance Beyond the Basics

Once you’re sure that all of your INSERT queries are profiled and doing what you expect, employ the basic steps outlined above to improve their performance. If that didn’t help, consider the following advice:

  • We can start an explicit transaction using START TRANSACTION or issue autocommit=0, run all of our INSERT queries, then run a COMMIT query. By doing so we delay commit operations until after the very last INSERT query has been finished – in that case, MySQL saves time because it doesn’t commit SQL statements as soon as they’re executed, but commits them all at once later instead. The bigger the data set is, the more time will be saved.
    Such an approach isn’t very feasible with billions of rows (INSERT queries are not designed for more than 50 or 100 million rows at a time – somewhat depends on hardware in use – and we need to use LOAD DATA for that since INSERT statements come with a lot of overhead – more on that later), but if we’re dealing not dealing with that many rows, it certainly could be viable.
  • We can modify the my.cnf file and add or modify the following options to increase the I/O capabilities of InnoDB (the main storage engine within MySQL):
    D:\Redgate\Blogs\October 2022\Optimiziation Series\Optimizing INSERT Queries\Images\InnoDB IO.png
    Image 3 – Increasing I/O Capabilities of InnoDB
    • The innodb_read_io_threads option sets the number of threads handling read operations – in most cases, the value of 32 is sufficient and should be left at default.
    • The innodb_write_io_threads option sets the number of threads handling write operations – in most cases, the value of 32 is also sufficient and should be left at default.
    • The innodb_io_capacity option defines the total I/O capacity of InnoDB and its value should be set at the maximum value of IOPS available to the server
      It is mostly related to the threads that perform various database-related tasks in the background (working with the buffer pool, writing changes, etc.) – these threads are trying to not have a negative effect on InnoDB at the same time. for more information, head over to the MySQL documentation over here.
    • For more details on optimizing my.cnf for general performance, I previously posted the following article on Simple-Talk: Optimizing my.cnf for MySQL performance.
  • We can insert more data at once by using the bulk insert operation available within the INSERT statement itself. When using such an approach, we can avoid defining the columns we load the data into if we load the data into all of them at once as well. Do note that if we elect to ignore columns and we have an AUTO_INCREMENT column, we must specify the value as NULL (an example is given below.)

D:\Misc\INSERT Query Optimization\Screenshot_2.png

Image 4 – INSERT INTO Example

Additional considerations for INSERT performance

These steps previously covered will help you optimize your INSERT queries; however, these are only the basics. Advanced DBAs know of a couple of additional ways to improve their INSERT query performance and some of advanced tips include combining INSERT statements with SELECTstatements too!

Locks and Inserting rows concurrently

Many of you know that issuing INSERT statements means locks for InnoDB: MySQL deals with each statement differently, and as far as INSERT statements are concerned, InnoDB row-level locks are advantageous for the end-user: the storage engine sets a lock on the inserted row thus not disrupting any operations with any of the other rows in the same table. Users can still work with their InnoDB-based tables as they’re inserting data as long as the rows they need are not locked and they didn’t take a table lock).

Before any row is inserted, MySQL also lets InnoDB know that a row is going to be inserted by setting an insert intention lock. The purpose of that lock is to let other transactions know that data is inserted into a certain position, so that other transactions do not insert data into the same position.

To make the best out of locks within InnoDB, follow the advice above – make use of bulk INSERT statements and consider delaying all commit operations until after the very last INSERT query: bulk INSERT statements will insert data in a quicker fashion and committing an operation only after the last query will be faster as well.

Inserting rows from a SELECT Query

As noted above, INSERT queries are the primary way of inserting data into MySQL, but many DBAs will know that INSERT queries are not always simple either: certain situations may require us to use them in concert with other – typically SELECT – queries too. A query like so would also work quite successfully:

INSERT INTO table_name (FirstColumnName, SecondColumnName)
SELECT  FirstColumnName, SecondColumnName 
FROM another_table [options]

For example:

D:\Misc\INSERT Query Optimization\Screenshot_3.png

Image 5 – INSERT and SELECT Queries Together

Note that in this case indexes will not be beneficial to the table where new rows are being created, but they will be beneficial fetching rows from the table in the SELECT statement. Note that in the sample query, the another_table reference in the query can be the same table. So:

INSERT INTO table_name (FirstColumnName, SecondColumnName) 
SELECT FirstColumnName, SecondColumnName 
FROM table_name [options]

Is possible as well, in which indexes can (depending on if you have a where clause on the table,) can both be helpful and detrimental at the same time.

The CREATE TABLE … SELECT Query

To select data directly into a new table, we can also employ a CREATE TABLE statement together with a SELECT query. In other words, we can create a table and insert data into it without running a separate INSERT query afterwards. There are two ways to do this:

  1. Run a CREATE TABLE statement with a SELECT statement without defining any columns or data types:
    CREATE TABLE new_table [AS] SELECT [columns] FROM old_table;
    MySQL will recreate all columns, data types and data from the old_table.
  2. You can also define the columns and constraints and insert data to the new table like so:
    CREATE TABLE new_table (
    column1 VARCHAR(5) NOT NULL,
    column2 VARCHAR(200) NOT NULL DEFAULT ‘None’
    ) ENGINE = InnoDB
    SELECT demo_column1, demo_column2
    FROM old_table;

Selecting data from one table to insert directly into another table is generally faster than INSERT INTO ... SELECT.

The Best Way to Load Massive Data Sets – INSERT vs. LOAD DATA INFILE

LOAD DATA INFILE is built for blazing fast data insertion from text files. Speed is achieved by ignoring or eliminating overhead posed by INSERT queries done by:

  • Working with “cleaner” data (data only separated by certain denominators (think “,”, “:”, “|”, or not separated at all.)
  • Providing us with the ability to only load data into specific columns or skip loading data into certain rows or columns altogether.

To use LOAD DATA INFILE, make sure you have a file that’s separating its columns by a certain denominator (common denominators include, but are not limited to “,”, the TAB sign, spaces, the “|”, “:”, and “-“ characters, etc.) and preferably one that’s saved in a CSV or TXT format. Save the file in a directory, remember the path towards that directory, then use the following query (replace the path to the file with your file, the “|” sign with your denominator and demo_table with the name of your table) – use IGNORE to ignore all errors posed by the query (duplicate key issues, etc.):

LOAD DATA INFILE ‘/var/lib/mysql/tmp/data.csv’ [IGNORE] INTO TABLE demo_table FIELDS TERMINATED BY ‘|’;

To export data from your database and make the data able to be re-imported by using the LOAD DATA INFILE query, use the SELECT * INTO OUTFILE query – use IGNORE if you want to ignore all errors.

SELECT *
FROM demo_table [IGNORE] 
INTO OUTFILE '/var/lib/mysql/tmp/data.csv' 
FIELDS TERMINATED BY '|';

LOAD DATA INFILE has many parameters that can be used as well. These parameters include, but are not limited to:

  • The PARTITION parameter allows us to define the partition where we want to insert data into.
  • Combining the IGNORE option with the LINES or ROWS options to tell MySQL how many lines or rows to ignore when inserting data.
  • Providing us with the ability to set the values of certain columns by using the SET option (the query below takes data from the file called “demo.csv” and loads the data with its columns terminated by “:” into a table called demo after ignoring the 100 lines from the beginning and also sets the date column to the current date when inserting all of the rows):
LOAD DATA INFILE ‘demo.csv’ INTO TABLE demo FIELDS TERMINATED BY ‘:’ IGNORE 100 LINES SET date=CURRENT_DATE();

LOAD DATA INFILE can be made even faster if we employ DEFAULT constraints. If there are columns that need to be populated with the same data for each row, the DEFAULT constraint will be faster than fetching it from the data stream. That way, all columns having the default keyword will be pre-filled without the need to load data into them.

Such an approach is very convenient to save time when one row consists of the same data and we don’t want to employ ALTER queries (those queries make a copy of the table on the disk, insert data into it, perform operations on the newly created table, then swap the two tables.) An example is given below:

CREATE A TABLE demo_table (
`demo_prefilled_column` VARCHAR(120) NOT NULL 
          DEFAULT 'Value Here’,
) ENGINE = InnoDB;

To dive even deeper into LOAD DATA INFILE, refer to the MySQL documentation itself.

Indexes, Partitions, and INSERT FAQ

If even LOAD DATA INFILE doesn’t help, you may want to look into indexes and partitions. Remember what we said above? The more indexes or partitions your table has, the slower your INSERT query will be. You already know the drill – but you may be pressed with some extra questions, some of them being the following:

Question

Answer

Should I drop all of the indexes before running an INSERT query?

Typically No – while indexes are used to improve the performance of finding rows, and generally slow down INSERT statements usually it is fine to let the INSERT statement process maintain indexes as part of the insert process.

However, in some cases when loading hundreds of millions or billions of rows, indexes should certainly be removed (they can be added again by using an ALTER TABLE query.)

Does using a PRIMARY KEY constraint on a table slow INSERT statements down?

Yes – primary keys are always indexed and indexes make INSERT queries slower.

Does the amount of indexes or partitions on a table make a difference in INSERT query performance?

Yes – the more indexes or partitions you have on a table, the slower your INSERT queries will be.

   

Are LOAD DATA INFILE queries always faster than INSERT statements? Why?

Yes – LOAD DATA INFILE queries always come with less overhead than INSERT queries do.

When optimizing INSERT statements, is there a difference of what storage engine is in use?

Yes – aim to use InnoDB unless you need specific features:

  • MyISAM will make COUNT(*) aggregate queries faster since the storage engine stores the row count inside of its metadata.
  • ARCHIVE will let you archive data with little footprint on the disk.
  • MEMORY is useful for temporary tables since all of its data is stored in the memory.
  • CSV will be advantageous if we need a way to migrate data into some sort of spreadsheet software.
  • For a complete list of storage engines, check the MySQL documentation.

When inserting data, is there a difference if the table we insert data into is locked or not?

Yes – inserting data into locked tables is generally faster than the other way around since database management systems check for table locks as part of the query execution process.

How do I achieve a balance between INSERT and SELECT queries?

Testing – Load testing is important to see what effects any change will have on a system. A lot will depend on how you are using a system, and how concurrent users use a system is important. If users are simultaneously creating and querying data, it is different than if data is loaded in a time window, then queried at other times.

Generally, aim to have only as many indexes and partitions as necessary, SELECT as few rows as possible, and where possible, use LOAD DATA INFILE instead of INSERT.  

Foreign keys – are they a problem for INSERT queries?

No – INSERT queries will be slower on a table with foreign keys since the database must check that there are no foreign key violations, but in most cases, they won’t make much of a performance difference (but will make a large data integrity difference). As is the case with indexes, foreign key constraints should be dropped once we have a lot (hundreds of millions of rows) of data to insert.

The CHECK constraint – does it slow down inserting data?

Yes – the CHECK constraint was introduced in MySQL 8.0.16, and it lets users specify a condition to check before inserting data into a table. Think of it as an integrity check – if a violation of the constraint is found, MySQL shows an error and terminates query execution, or skips inserting the row altogether if the IGNORE clause is specified.

In many cases, the constraint will only be problematic if the constraint evaluates to FALSE instead of TRUE because in that case, queries will fail if no IGNORE clause is specified. Aim to avoid using constraints when inserting larger quantities of data, because they could make your INSERT queries slower. (If you remove one for performance reasons, add it back for integrity’s sake.)

More details about the CHECK constraint can be found on the MySQL blog.

Is it possible to insert data and update it at the same time?

Yes – that can be done by using the ON DUPLICATE KEY UPDATE option on anINSERTstatement. The statement is pretty self-explanatory: if there is a situation where a row of the same value would be inserted into a column, an update of the old row would occur. Such a statement is mostly used to increment column values whenever there are duplicate key issues, but it can have other use cases as well.

Are there any lesser-known ways to improve INSERT query performance?

Yes – if you’re working with bigger data sets, make use of the DEFAULT keyword. The keyword will let you specify the default value of the column and as a result, will automatically be filled in when running LOAD DATA INFILE queries saving you time in return.

When to switch to LOAD DATA INFILE?

Typically, when loading any data where you have many rows to load – There are no set “rules” that define when you should switch INSERT statements to LOAD DATA INFILE where possible, however, keep in mind the following:

  • There are several necessary steps that the DBMS must go through when performing INSERT operations.
  • INSERT operations come with overhead. The more data is inserted, the bigger the overhead is.
  • INSERT query performance can be optimized a lot by using bulk INSERT queries or by delaying index updates and concurrency checking.
  • LOAD DATA INFILE works best when settings inside of my.cnf are optimized for InnoDB.

Balancing INSERT Performance and Reads

To balance out the performance between INSERT and SELECT queries, keep the following in mind:

  • Basics do help – Select as few rows as possible by using a column list with your SELECT of SELECT *, and index only the columns you’re searching through.
  • Normalize your tables – Table normalization helps save storage space as well as increases the speed of your read queries if used properly. Choose a normalization method suitable for you, then proceed further.
    Do note that as with everything, normalization also can have negative effects – more tables and relationships can mean more individual INSERT or LOAD DATA INFILE statements, but if you do everything correctly, your database should roll just fine!
  • Use the proper storage engine – this should be obvious, but you would be surprised how many inexperienced DBAs make a mistake of using an inappropriate storage engine for their use case. If you’re using MySQL, aim to use InnoDB or XtraDB for general use cases.
    If you’re in a testing environment and memory is not an issue, the MEMORY storage engine could also be an option, but note that the storage engine cannot be as heavily optimized and that the data won’t be stored on the disk either – at that point the insert queries would be blazing fast, but the data would be stored in the memory itself meaning that a shutdown of the server would destroy all of your data as well.
  • Use a powerful server – this goes hand in hand with optimizing my.cnf or other files. If your server is powerful enough, balancing the performance of INSERT and SELECT operations will be a breeze.
  • Only use indexes and partitions where necessary and don’t overdo it – aim to index only the columns you’re running heavy SELECT queries on, and only partition your tables if you have more than 50 million records.
  • Consider ditching INSERT statements altogether – if you must import huge chunks of data, consider splitting them into files and uploading those files with LOAD DATA INFILE instead.

Summary

In this blog, we’ve walked you through how best to optimize INSERT queries for performance and answered some of the most frequently asked questions surrounding these sorts of queries. We’ve also touched upon the importance of balancing INSERT and SELECT operations and walked you through a way to ditch INSERT queries altogether when loading lots of data.

Some of the advice we’ve provided in this blog is known by many DBAs, while some might not be known at all. Take from this blog what you will – there’s no necessity to follow everything outlined in the article step by step, but combining some of the advice in this article with the advice contained in other parts of this series will be invaluable for your database and your applications alike.

We hope that this blog has taught you something new, and we’ll see you in the next one.

 

The post Optimizing MySQL: Adding Data to Tables appeared first on Simple Talk.



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

Thursday, May 18, 2023

PostgreSQL Basics: A Template for Managing Database Privileges

In the first two articles of this series about PostgreSQL privileges, we reviewed how to create roles, grant them privileges to database objects, and how object ownership is an important aspect in managing access and control within the database.

When it comes to managing what roles can access or modify an existing object, ownership is the ultimate privilege. Because PostgreSQL privileges work from a Principle of Least Privilege mindset, the owner of an object (table, trigger, function, procedure, etc.) needs to GRANT privilege to other roles.

We discussed how this can be done manually with a GRANT command each time an object is created, however, that is time consuming to manage and easy to miss a detail.

Instead, PostgreSQL provides a method for setting default privileges which are granted on behalf of the object owner as database objects are created. Using default privileges, a role can prepare the database ahead of time to ensure that consistent access privileges are applied while easing the management burden over time.

But how do you go about creating a set of roles and default privileges that will provide the right level of control and access? Let’s dig a little deeper.

Using Default Privileges to Manage Migrations

Recall that default privileges are set per role (which can represent a user or a group of users). That is, each role must specify what privileges it will grant to other roles whenever a specific type of object is created. Consider the image illustration below of a database with a number of objects inside, each owned by a different role.

A picture containing diagram Description automatically generated

A database that allows many roles to create and own objects introduces at least two issues.

First, it means that many roles have the CREATE privilege in each schema. As we discussed in the previous articles, object creators are also the owners by default and have a superuser-like privilege for the object. More than that, however, having the privilege to create objects in a schema creates a potential security issue, the very reason the CREATE privilege was removed from the public role in PostgreSQL 15.

Second, even if you have legitimate reasons for many different roles to create objects in a schema, each of them will need to create and maintain a set of default privileges to ensure the other roles have the access they need. That’s a lot to manage, even more so because it’s challenging to easily visualize default privileges in PostgreSQL, currently.

Instead, consider this second illustration, showing one group role that owns all database objects. In this scenario, the group role cannot login which provides some level of security, and only one set of default privileges must be maintained over time to manage access of database objects and data effectively and efficiently.

Diagram Description automatically generated

Let’s look at how you can start to move towards this kind of security set up within your PostgreSQL databases.

Create High-level Group Roles

In PostgreSQL, roles can be granted membership in other roles and inherit their privileges, something we discussed in the first article. The challenge, then, is to think about the kinds of privileges you need to provide to different roles in your database and how to abstract them into higher sets of roles.

Remember that roles are created at the instance level. Therefore, if you create a ‘read_only' role, it can be used to manage read-only access ('SELECT') in each database. The same can be done with different kinds of privileges from DML access (‘INSERT', ‘DELETE', ‘UPDATE') all the way up to DDL operations (‘CREATE').

A sample “template”, then, can start by creating these three group roles in every database instance. Your needs may be more complex, so please add and adjust as you see fit.

  • The following scripts are a modified version of this Stack Overflow answer to use as a template. I happened upon it last year and thought it does a good job outlining a straightforward process to setting up PostgreSQL database privileges. (It doesn’t hurt that it mentioned the best Database DevOps tool as well! 😊)

PostgreSQL Instance Group Roles

The following two scripts need to be run once on each database instance to create the appropriate roles which we will then be granted privileges within each database.

/*
* This script should be run ONCE per PostgreSQL instance
* to create the group roles that will/can be used in all databases
* for ddl/dml/read_only access 
* 
* In your situation, you may need to create more group roles to
* provide better granularity of privileges.
*/
CREATE ROLE ddl_grp WITH NOLOGIN;
CREATE ROLE dml_grp WITH NOLOGIN;
CREATE ROLE read_only_grp WITH NOLOGIN;

Creating these roles hasn’t done anything of substance, yet. Instead, these roles become a mechanism to manage other privileges as we create a database and schema objects. Even though you cannot connect to a database directly with these roles ('WITH NOLOGIN'), these roles can still own objects and create default privileges.

Next, we can grant membership into these group roles to other roles as necessary. In the example below, we have three types of user roles:

  • Object admins: these roles are allowed to create objects in a database. Creating objects is a DDL action, so we named the role 'ddl_grp'
  • Data admins: these roles are allowed to modify data and associated objects with DML statements, so we named the role ‘dml_grp'
  • Read-only: these roles are allowed to select data from specific schemas or tables. We named the role ‘read_only_grp'

The examples user roles (eg. 'dev_admin1', ‘flyway', ‘dev1', ‘report_usr', etc.) need to exist prior to granting membership in the group role. The key is that any role that is granted membership to the ‘ddl_grp' role will be able to run scripts that create or modify objects in the database as ‘ddl_grp'.

/*
 * Now, grant access to each role as necessary for their
 * job function. Again, these are just ideas of how to get
 * started. More "group" roles may be necessary
 * 
 * These are example roles that might be given access. A good
 * example of a role that should be in the "ddl_grp" is the
 * role that is used by DevOps tools like Flyway to run
 * migrations scripts. This ensures that all objects are owned
 * by that group and all users get access.
 */
GRANT ddl_grp TO dev_admin1, flyway;

GRANT dml_grp TO dev1, dev2;

GRANT read_only_grp TO report_usr1, report_usr2;

With all roles in place and membership updated, we can now turn to the individual database where privileges really matter.

Individual Database Privileges

Now that we have the database roles created, we can focus on the individual database privileges. In this case you have two options.

You could run this script each time a new database is created in the cluster. Or, using a superuser role, you can modify the template database (typically called ‘template1') on your PostgreSQL instance. Any settings that are applied in the template database will automatically set these privileges for each new database that is created from that template.

The script below can be applied as one script, however, I’ve broken it apart to discuss the purpose of each section and how it applies to the database.

Revoke all privileges from PUBLIC

The first thing that should be done for any new database is to revoke all privileges that are granted by default to the PUBLIC role. We discussed in the first article why this is a recommended practice.

/*
 * On EACH database, run this script as a superuser or
 * user that has CREATEROLE and other GRANT privileges.
 * In a DBaaS service like Amazon RDS, this may be a user
 * that was assigned to you for administration
 */
-- For all modern versions of PostgreSQL. This will
-- prevent connections to the database until specifically
-- granted with CONNECT
REVOKE ALL ON DATABASE mydatabase FROM PUBLIC;

-- Prevent anyone from creating objects in the public
-- schema until granted permission. Default on PG15+
REVOKE CREATE ON SCHEMA public FROM PUBLIC;

Notice one nuance here. We are removing ‘ALL' privileges from 'PUBLIC' at the database level, not the schema level of the database. If we removed all privileges from the schema as well, then normal PostgreSQL commands would not work for many users without resetting additional privileges.

Revoking 'ALL' at the database level prevents users from connecting to the database without specific grants applied elsewhere, as shown below.

Grant basic privileges

All roles need the ability to connect to the database and (typically) access temporary tables. However, without additional privileges like USAGE and SELECT, these roles can’t actually do anything in the database yet.

Normally every role would inherit these privileges from the PUBLIC role, but we just revoked those privileges above to give us more control over which roles we want to access each database and the public schema.

-- GRANT connect and access to all roles;
GRANT CONNECT, TEMPORARY 
        ON DATABASE mysuperdb TO ddl_grp, dml_grp, read_only_grp;

Grant usage and other privileges to each group role

Now we get to the good stuff. For each database we can decide which roles can use the database objects ('USAGE') and what they can do per schema. As noted below, this example only shows how to grant privileges on the public schema. If your application has other schemas (which it probably does!), you will need to grant the appropriate permissions on each schema.

First, our 'ddl_grp' (and all members) is allowed to use and create objects in the schema and any sequences. If there are existing objects such as TABLE, SEQUENCE, TYPE, DOMAIN, etc. you do need to run a GRANT statement for each time to set their existing privileges appropriately because default privileges only effect newly created objects. In the example below, I show granting privileges to existing sequences and tables.

/*
 * Below, we grant usage on an application schema called 'myapp'.
 * If your application has a different schema, you will need to
 * update this appropriately. 
 * 
 * Multiple schema names can be separated by a comma  
 */
-- This will allow anyone in the group to use and create
-- new objects in the schema. Because this group will own
-- the objects, they can modify them later.
GRANT USAGE, CREATE
    ON SCHEMA myapp TO ddl_grp;

-- modify privileges for any existing tables and sequences
GRANT ALL
    ON ALL TABLES IN SCHEMA myapp TO ddl_grp;

GRANT ALL
    ON ALL SEQUENCES IN SCHEMA myapp TO ddl_grp;

Next, we move on to the group roles that will be allowed to use objects in a schema and then select data and sequence values. As before, if your database has multiple schemas, the roles will need to be granted usage for each object type in each schema.

-- This will allow all other "group" roles to connect
-- to the myapp schema and access objects if they have
-- have been granted privileges to do so.
GRANT USAGE ON SCHEMA myapp TO dml_grp, read_only_grp;

-- modify privileges for any existing tables and sequences
GRANT SELECT
    ON ALL TABLES IN SCHEMA myapp TO dml_grp, read_only_grp;

GRANT USAGE, SELECT
    ON ALL SEQUENCES IN SCHEMA myapp TO dml_grp, read_only_grp;

Finally, as the user that will be used to create schema objects, set the default privileges for other roles in the database. Notice two things in the following example.

  • We only set default privileges for tables and sequences. You should consider other privileges that your users will need as objects are created and add them to your script.
  • The 'ddl_grp' role doesn’t have any default privileges assigned, nor to any of the roles which are members of it. This is because the group will be the owner of the object and any other member role will automatically inherit the ownership privileges. Nothing more is needed.

Default privileges are normally applied to the role that executes the statement. Therefore, your scripts must temporarily set the role to the owner that will create objects in the future. This requires that the role executing this script is a member of the other role.

Alternatively, and slightly clearer in the long run, you can set the default privileges for another role as part of the ALTER DEFAULT PRIVILEGES statement as long as the current role is a member of it.

In both examples below, the role that is executing the SQL must be a member of the other group role. The second form is a bit more verbose and easier to track at a statement level what privileges are being applied to whom.

Option 1: SET ROLE before assigning privileges

/*
 * Finally, as the user that will run migration scripts (and is
 * a member of the DDL group, setup the default access privileges.
 */
SET ROLE ddl_grp;
ALTER DEFAULT PRIVILEGES IN SCHEMA myapp
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO dml_grp;

ALTER DEFAULT PRIVILEGES IN SCHEMA myapp
GRANT SELECT ON TABLES TO read_only_grp;

ALTER DEFAULT PRIVILEGES IN SCHEMA myapp
GRANT USAGE, SELECT ON SEQUENCES TO dml_grp, read_only_grp;

ALTER DEFAULT PRIVILEGES IN SCHEMA myapp
GRANT UPDATE ON SEQUENCES TO dml_grp;

Option 2: Assign privileges for another role

/*
 * Finally, as a user that has membership in the group role that
 * will run migration scripts setup the default access privileges.
 */
ALTER DEFAULT PRIVILEGES FOR ROLE ddl_grp IN SCHEMA myapp
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO dml_grp;

ALTER DEFAULT PRIVILEGES FOR ROLE ddl_grp IN SCHEMA myapp
GRANT SELECT ON TABLES TO read_only_grp;

ALTER DEFAULT PRIVILEGES FOR ROLE ddl_grp IN SCHEMA myapp
GRANT USAGE, SELECT ON SEQUENCES TO dml_grp, read_only_grp;

ALTER DEFAULT PRIVILEGES FOR ROLE ddl_grp IN SCHEMA myapp
GRANT UPDATE ON SEQUENCES TO dml_grp;

Verify the privileges are set correctly

The last step is to verify that the default privileges are set and ready to do their job. The easiest way to see the result of your work is with the ‘\ddp’ command in ‘psql’.

A close-up of a computer code Description automatically generated with low confidence

This helps us verify that the 'ddl_grp' role set default privileges for all tables and sequences in the public schema.

Obviously, your application and role set up is probably more complex than this example template. However, the principles apply regardless of how many roles and object types you need to manage. Use this as a starting point.

Bringing It Together At Migrations Time

With everything in place, let’s look at how you would use this in practice on a production database (for example).

In the migration pipeline, we set the connection string for the migration script to use our pipeline role, shown as “flyway” above. Ideally, the password for this role would be stored in a vault and is retrieved as part of the pipeline script so that no regular user can authenticate as this role.

At the top of any migration script, then, we first set the role to the 'ddl_grp' role so that any creation DDL will cause the objects to be owned by that group and the default privileges will kick in and be applied correctly! A simple example might look something like this.

/*
 * First set the session role to the high-level 
 * ownership group role
 */
SET ROLE ddl_grp;

-- Create the object
CREATE TABLE test (
    col1 text null,
    col2 int null
);

Once the migration has been applied, you can quickly check that the privileges were applied correctly using the '\dp' command in '\psql'.

A close-up of a code Description automatically generated with low confidence

Success! From this point forward, as long as the 'ddl_grp' is used to create tables and sequences (or any other objects that you set default privileges for), other roles will have the access you defined, and the overall management burden is reduced!

Conclusion

Privileges in PostgreSQL can be complex to think about and manage. Knowing how to grant privileges to roles and membership between roles can quickly improve this burden. However, learning how to setup default privileges in an effective way is where the real power of managing your database begins.

 

The post PostgreSQL Basics: A Template for Managing Database Privileges appeared first on Simple Talk.



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

Monday, May 15, 2023

Changing log growth strategy in SQL Server 2022

When I first saw a bullet item stating SQL Server 2022 would support instant file initialization for log file growth, I was excited. When I later learned it only applies to automatic growths, and only those of 64 MB or less, I was a little less excited. With those limitations, I was skeptical this enhancement could supplant my long-standing practice of using 1 GB autogrowth for log files – at least ever since SSDs and other modern storage became more commonplace.

But after playing with it, I’m a believer.

Since the advent of the instant file initialization feature, data file growths are nearly instantaneous, because the newly-allocated space can be created empty. When log files grow, on the other hand, the new space must be zero-initialized to make sure SQL Server uses the transaction log correctly, as Paul Randal explains in Why can’t the transaction log use instant file initialization?

PREEMPTIVE_OS_WRITEFILEGATHER is the wait type you’ll see if a session is waiting on log file initialization. You can check if an instance is generally suffering this pain by comparing against other prevalent waits in your workload, by checking sys.dm_os_wait_stats:

SELECT wait_type, waiting_tasks_count, wait_time_ms
   FROM sys.dm_os_wait_stats
   WHERE wait_type = N'PREEMPTIVE_OS_WRITEFILEGATHER';

In the days of spinning rust platters, growing a log file was extremely painful, particularly in highly concurrent, write-heavy workloads. For most of my career, this alone has cast log files in general in a negative light. Even on fast and modern storage, log file expansion can be quite disruptive, because all transactions need to wait on any file growth operations.

In most cases, best practice has dictated that you just size your log files as large as possible, to avoid any unexpected growth events. But this isn’t always possible – on systems with many databases, for example, you only have so many drives, and you can’t size all of your log files to fill the disk up front. It is also sometimes difficult to predict which ones will grow more – or in more spiky ways – over time. In these cases, a smaller autogrowth setting for log files can still be a good strategy today, even without this enhancement.

But let’s see the impact of the change.

On two different instances on the same machine, I’ll create the following four databases, each with an 8 GB data file and 32 MB log file – all on the same drive. The differences will just be the version and the log file’s filegrowth setting:

  • SQL Server 2019:
    • 1 GB autogrow
    • 64 MB autogrow
  • SQL Server 2022:
    • 1 GB autogrow
    • 64 MB autogrow
/* values in brackets should all be set before running script 
{2019|2022} = version; {64|1024} = log file size */
CREATE DATABASE ifi_{64|1024}
 ON 
 (
   name     = N'ifi_data',
   filename = 'D:\data\ifi_{2019|2022}_{64|1024}.mdf',
   size = 8192MB, filegrowth = 2048MB
 )
 LOG ON 
 (
   name     = N'ifi_log', 
   filename = 'D:\data\ifi_{2019|2022}_{64|1024}.ldf',
   size = 32MB, filegrowth = {64|1024}MB
 );

Then I’ll set up a simple but log-heavy workload script to execute against each database, measuring the following:

  • total workload duration
  • total duration of PREEMPTIVE_OS_WRITEFILEGATHER waits
  • number of log growth events
  • total virtual log file fragments (VLFs)
  • average VLF size
  • ending log file size

The workload itself is pretty simple:

DROP TABLE IF EXISTS dbo.dummy;

 SELECT TOP (0) ID = IDENTITY(int,1,1),
  name = CONVERT(nchar(2048), N'x') INTO dbo.dummy;

 CREATE UNIQUE CLUSTERED INDEX CIX_dummy ON dbo.dummy(ID);

 INSERT dbo.dummy(name) SELECT TOP (500000) N'x' 
   FROM sys.all_objects AS s1
   CROSS JOIN sys.all_objects AS s2;

You can monitor the impact of this “workload” in a number of ways, including a query against sys.dm_os_wait_stats similar to the one above, as well as an Extended Events session including the following:

CREATE EVENT SESSION [log_size_changes] ON SERVER 
   ADD EVENT sqlos.wait_info_external 
     (WHERE ([wait_type] = N'PREEMPTIVE_OS_WRITEFILEGATHER')),
   ADD EVENT sqlserver.database_file_size_change
   ADD TARGET package0.event_file(SET filename = N'ifi_log_size_changes')
   /* ... */

Just note that some events report durations in microseconds, and others in milliseconds.

Or queries against the default trace, if you still have it enabled:

SELECT t.DatabaseName, 
        GrowthEvents    = COUNT(*), 
        AverageDuration = AVG(t.Duration/1000.0), 
        TotalDuration   = SUM(t.Duration/1000.0)
 FROM
 (
   SELECT [path] = REVERSE(SUBSTRING(p, CHARINDEX(N'\', p), 260)) + N'log.trc'
   FROM (SELECT REVERSE([path]) FROM sys.traces WHERE is_default = 1) AS s(p)
 ) AS p
 CROSS APPLY sys.fn_trace_gettable(p.[path], DEFAULT) AS t
 WHERE t.EventClass = 93
   /* AND t.DatabaseName LIKE N'ifi%' */
 GROUP BY t.DatabaseName;

And checking the output of sys.dm_db_log_info you can see more information about the number of virtual log files and their sizes:

SELECT d.name, 
        VLFCount  = COUNT(li.database_id), 
        AvgSizeMB = AVG(li.vlf_size_mb)
 FROM sys.databases AS d
 CROSS APPLY sys.dm_db_log_info(d.database_id) AS li
 /* WHERE d.name LIKE N'ifi%' */
 GROUP BY d.name;

After running the workload against each database, I observed the following:

Metrics observed during growth events

Those are favorable and promising results – we’re shaving roughly 20% off the workload duration simply by moving to 64 MB autogrowth, entirely due to eliminating PREEMPTIVE_OS_WRITEFILEGATHER waits and capitalizing on instant file initialization. In addition, we see a slight benefit from an improved VLF algorithm (recently documented), resulting in fewer, larger VLFs for the exact same log growth events.

Now, your mileage may vary. On more capable hardware, the percentage of time spent on initialization may be lower, so the benefit might be more subtle. Still, zeroing out a new portion of a log file will never be instantaneous for growth events larger than 64 MB (barring more enhancements in future versions, of course). So, as you start planning for SQL Server 2022, or even if you’re already there, this configuration option is worth testing against your workload and hardware. This is especially true if you’re not in a position to pre-size your log files bigger than you’ll ever need. After all, the fastest file change is the one that doesn’t have to happen in the first place; the next fastest is the one that can take advantage of instant file initialization.

The post Changing log growth strategy in SQL Server 2022 appeared first on Simple Talk.



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

Friday, May 12, 2023

Uncovering the mysteries of PostgreSQL (auto) vacuum

Welcome to the second blog of the “magic of parameters” series. In the first entry, I covered memory parameters, and in this article. In this article will talk about PostgreSQL configuration parameters which manage the (auto)vacuum and (auto)analyze background processes.

Why vacuuming is necessary?

Before we start talking about vacuum and analyze-related parameters, we need to touch on the concept of vacuuming in PostgreSQL. This concept is Postgres-specific, and for DBAs coming from Oracle and Microsoft SQL Server it might feel confusing – you can’t directly map it to any previous experiences. (Note: both Oracle SQL Server do share some similarities in some of their configurations. For example, SQL Server memory optimized tables have a similar process referred to as garbage collection.)

Let’s start by looking at how data is stored in PostgreSQL database. The generic structure of a block is shown in Figure 1.

Figure 1. Generic block structure

Table rows are stored in a heap, and their order is not guaranteed. In Figure 1, you can see free space in the block, which can be filled with new rows of data. If your previous DBA experience is with a lock-based RDBMS engine, you would think that we should set up a fillfactor less than 100% for each table so that there will be some room to maintain most updated records in the same block.

Be ready for a surprise! Although you can define a fillfactor <100%, this option is rarely used in PostgreSQL. The reason is that PostgreSQL never updates a row in place due to how it implements concurrency controls!

Multi-version concurrency control

To allow multiple users to access data concurrently and to avoid waits when data is being updated, PostgreSQL uses multi-version concurrency control (MVCC). It is implemented using Snapshot Isolation (SI): each SQL statement sees a snapshot of data (a database version) as it was when the transaction started, regardless of the current state of the underlying data. This approach provides multiple advantages:

  • It prevents statements from viewing inconsistent data due to table modifications made by other transactions
  • It provides transaction isolation for each session

The modified tuples are saved in a new place, within the same block or in a different block, but if some transactions still are still actively accessing the old versions of the modified tuples, these tuples are kept “alive.”

How does Postgres know which versions should be kept alive, and which can be recycled? Each table has several “hidden” (system) attributes which you can’t see when you execute SELECT * FROM <table>. Two of these hidden attributes are xmin, which contains the ID of the transaction which created the row, and xmax, stores the ID of the transaction which deleted the row (either by updating or by deleting).

Now, for any processes transaction ID that is between greater or equal to xmin and less than xmax, this row is active and should be visible to that transaction. PostgreSQL marks a tuple dead if there are no more active transactions that the row could be visible to. Figure 2 presents a block layout with a dead tuple.

Shape Description automatically generated with medium confidence

Figure 2. Block layout with dead tuple.

What is the effect of MVCC on the database performance? On the one hand, the absence of locking facilitates performance. On the other hand, having multiple versions and thereby dead tuples creates both table and index bloat.

What’s VACUUM for?

VACUUM checks all the blocks and marks the old tuples “dead.” It’s important to remember that VACUUM does not rewrite the block and does not “compress” the data. It simply marks the space occupied by dead tuples as “reusable.” You can compress data and return the unused space back to the operating system by running VACUUM FULL.

What else does VACUUM do?

By this time, it might already feel like “too much information”, especially if that’s the first time you are exposed to the concept of vacuuming in Postgres. But before we proceed further, let’s note that the job of VACUUM is not limited to reclaiming space. In addition, it:

  • Updates data statistics used by the PostgreSQL query planner.
  • Updates the visibility map, marking the blocks with no dead tuples
  • Protects against loss of very old data due to transaction ID wraparound.

If your job is to manage Postgres instances, you might want to do more reading on the topic of vacuuming, beyond what we will cover, but for the start, let’s just keep in mind there are many things vacuum does.

What’s Autovacuum for?

Autovacuum is a daemon which periodically invokes vacuuming of tables and indexes. Autovacuum does not require any scheduling, instead, its behavior is driven by several system parameters, which will be described later in this article.

Myths about the vacuuming process

Since the concept of vacuuming is not as common in other RDBMS and is not all that we;; understood by PostgreSQL newbies (and some experienced people too!), it is a source for multiple common myths.

In this section I will do what I can to dispel these myths.

Myth #1. The vacuum process makes everything run slower

The reality. VACUUM (and by extension, autovacuum) is obviously not cost-free, but the cost is far less than if it was not executed. When rows are being modified, dead tuples begin to accumulate and everything can become slow when the autovacuum does not run regularly.

Tables become bloated (more details on table bloat later in the article), which makes sequential scans slower. Visibility map is not updated, which prevents the usage of index-only scan (PostgreSQL still needs to check the heap to make sure that index does not point to any dead tuples).

Myth #2. The vacuum process blocks other operations

The reality. The VACUUM process is aborted if it is blocking any write operation. The wait time is determined by the deadlock_timeout parameter. In fact, on a busy table, it may be beneficial to run vacuum often (ideally using autovacuum), because otherwise, it might not have a chance to finish for days and weeks, because it is blocked by write operations.

Myth #3. On busy mission-critical databases, it’s a good idea to disable autovacuum and run scheduled vacuum jobs during the quiet time.

The reality. “Busy systems” (in terms of modifying data) may be busy most of the day, not just certain times of the day, with very few exceptions. If you disable autovacuum and run vacuum on a schedule, such as during “quiet time,” vacuum will end up with more job to do (if the system is “busy” there could easily be a lot of dead tuples by that time!). Now, you might end up blocking the tables for longer periods of time, so you need to make sure that there are no write operations for the extended period of time.

In addition, even if the system behavior is predictable in general, there are chance of burst updates, and you may end up with more bloat than expected, with even more severe consequences.

Myth #4. If you use other ways to control bloat, like pg_squeeze, you do not need to run vacuum at all.

The reality. Recall that reclaiming the space is only one of several functions performed by VACUUM. You might be able to reclaim the space, but other vacuum functions won’t be performed, most importantly, old records won’t be frozen. Once again if we are talking about “busy systems” the risk of TXID wraparound is higher.

Myth #5. You need to monitor the autovacuum runs and make sure that all tables are vacuumed at least daily

The reality. On the tables with few writes autovacuum might run once a week or even less frequent. The parameters explained in the next section determine how often vacuuming will be performed on specific tables.

It is possible to view the statistics on updates for each table and to set up some monitoring based on this information, but that would effectively mean replicating the logic of autovacuum. More important is to monitor system performance and tables bloat

The most important parameters that govern the vacuum process

There are many vacuum-related parameters which allow very precise vacuum tuning. However, in practice, it is often enough to set up correctly just a handful of them. Most of them control autovacuum, to help tune the automatic execution of the vacuum process.

  • autovacuum_vacuum_cost_delay: amount of time the process will sleep after the max cost exceeded
    • The default value is 20 ms, which is very conservative and may result in vacuuming not keeping up with changes. Start with reducing it to 10ms, and if necessary, you can go as low as 2 ms.
    • Note that this parameter is different from the naptime (see below)
  • autovacuum_max_workers: max parallel workers (across server) which are invoked for each autovacuum invocation.
    • Most often, this parameter is set to half of the total number of parallel workers defined for the instance, however, it is often beneficial to increase this number even more.
  • autovacuum_naptime: minimum delay between autovacuum runs on any given database.
    • Each time the autovacuum daemon starts, it examines the database and issues VACUUM and ANALYZE commands as needed for tables in that database. Since this setting determines the wake-up time per database, an autovacuum worker process will begin as frequently as autovacuum_naptime / number of databases. For example, if autovacuum_naptime = 1 min and we have five databases, an autovacuum worker process would be started every twenty seconds.
    • The default value for this parameter is 1 min, however, on busy databases with many writes it can be beneficial to increase its value to prevent autovacuum waking up too often. With this parameter, like with many others, there is a trade-off between “too often” and “too much work on each invocation”.
  • autovacuum_vacuum_scale_factor: percentage of changes to the table after which a vacuum should run
    • The default value for this parameter is 0.2; for larger tables, should be reduced to 0.05 (and consider this for all tables for that matter)
  • autovacuum_analyze_scale_factor: percentage of changes to the table after which an analyze should run
    The default value is 0.1; for larger tables, should be reduced to 0.05 (and consider for all tables here as well) respectively.
    • Note: The default for the autovacuum_vacuum_scale_factor is 0.2 (20%) and autovacuum_analyze_scale_factor is 0.1 (10%). While the default values perform acceptably for tables of a modest size (up to around 500MB), for larger tables these values are usually too high.
  • autovacuum_vacuum_cost_limit: The default value of -1 for autovacuum_vacuum_cost_limit results in autovacuum_vacuum_cost_limit = vacuum_cost_limit. However, this value is distributed proportionally among the running autovacuum workers. This is done in order that the sum of the limits of each worker never exceeds the limit on this variable. Therefore, the default value of 200 for vacuum_cost_limit is generally too low for a busy database server with multiple autovacuum workers.should be set to -1
  • vacuum_cost_limit: cumulative cost after which the vacuum should stop, should be set to 200 X number of workers

How to tune (auto)vacuum

Vacuuming is vital for PostgreSQL databases well-being, and autovacuum should never be turned off unless there are really exceptional and unusual circumstances. At the same time, autovacuum should be always tuned for specific environment needs.

Tuning autovacuum is challenging, because we need to take into account the vacuuming speed, level of I/O, and blocking. To start with, the default set of vacuum-related parameters would work adequately. After some time passes, check system bloat and if it appears to be high and adjust the autovacuum settings. What should be considered a high bloat depends on many factors.

On average, bloat below 20% is considered normal. For larger tables, 10% maybe considered a significant bloat, while for small tables, even 50% bloat maybe fine. If the bloat does not result in visible performance degradation, there is no pressing need to address it.

How to determine if your tables are bloated

There are examples of such queries that can be found in many PostgreSQL blogs and company’s websites. Many of the solutions require extensions, if you are up to installing additional extensions to monitor your bloat, you can use the following:

CREATE EXTENSION pgstattuple;

This is one of many extensions provided with PostgreSQL contrib package, so you do not need to download anything, just execute the CREATE statement. The available functions are documented in PostgreSQL documentation.

If you do not want to install any extensions, the following queries will provide good estimates:

table_bloat_check.sql

index_bloat_check.sql

If your system is even somewhat active, it is essential that you monitor the bloat in your data objects.

How to monitor

Although you can find the last time when vacuum/autovacuum and analyze/autoanalyze were executed in the pg_stat_all_tables, we do not recommend monitoring this value. As it was mentioned in the previous section, if the updates didn’t reach a threshold, the is no need for autovacuum to run. However, the pg_stat_all_tables object contains a lot of valuable information which may be very useful for evaluating the database health.

For each table, pg_stat_all_tables contains the following information:

Column

Description

seq_scan

Number of sequential scans on the table

seq_tup_read

Number of tuples read using sequential scan

idx_scan

Number of index scan accesses to the table

idx_tup_fetch

Number of tuples fetched using index scan

n_tup_ins

Number of tuples inserted

n_tup_upd

Number of tuples updated

n_tup_hot_upd

Number of “hot updates” (updates which keep the tuple in the same block)

n_live_tup

Estimated number of live tuples in the table

n_dead_tuples

Estimated number of dead tuples in the table

n_mod_since_analyze

Estimated number of modifications since last analayze

n_ins_since_vacuum 

Estimated number of inserts since last vacuum

last_vacuum

Time of the last vacuum run on that table

last_autovacuum

Time of the last autovacuum run on that table

last_analyze

Time of the last analyze run on this table

last_autoanalyze

Time of the last autoanalyze run on that table

vacuum_count

Total number of vacuum runs on the table

auto_vacuum_count

Total number of autovacuum runs on the table

analyze_count

Total number of analyze runs on the table

autoanalyze_count

Total number of autoanalyze runs on the table

As you can see, this table provides valuable information about the dynamics of each table. However, the only way to see whether the autovacuum is tuned correctly is to run bloat checking queries on regular basis.

Conclusion

It is not uncommon that new PostgreSQL users and even DBAs do not pay much attention to tuning autovacuum and monitoring tables and indexes bloat. This happens since these concepts are Postgres-specific and are not in the mental checklist of database professionals with previous experience elsewhere.

Thereby, it is important to educate yourself about the role vacuum and analyze play in the PostgreSQL databases well-being.

 

The post Uncovering the mysteries of PostgreSQL (auto) vacuum appeared first on Simple Talk.



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

Tuesday, May 9, 2023

Xerox stars for accessibility

I was working for Xerox when the Xerox Star, precursor to all the computer systems in use today, was introduced. Before then, computer users just had command-line or character-based GUIs. The Xerox Star workstations were displayed for the first time for us insiders in a special room, like a secular chapel, guarded over by the priesthood of developers. We were amazed. Many of the ideas had been around, but never combined into a complete graphical system. What were we amazed by? The Graphics? No. The proportional fonts? No. For common usage, this was, at the time, in the science-fiction realm of affordability. It was the accessibility that amazed us.

In the narrowest sense, the windowing system that Palo Alto designed allowed people with disabilities such as poor sight, hearing or motor control to have comparable opportunities to access computing resources. Applications could be configured to provide alternative ways of using their features with different visual clues, without mouse or bypassing the keyboard. Each application had the same style, layout, and menu system, so that you had a good chance of finding yourself around an application well enough to start using it, even the very first time you tried. Folks with perceptual access deficits fared well because any icons were used only in addition to the menus and had accompanying text or ‘mouse-overs’. There were rules for background and foreground colours, text size and do on. A huge amount of work went on in the ensuing years into finding the optimal rules to make the user interface accessible to people of any language, culture, age, or disability.

For many years everyone mostly stuck to the rules. I’ve developed applications that were designed to comply with a corporate usability manual and had to be signed off by teams of usability experts, user representatives and even the unions, and very right too. They were to be used by people for their entire working day, for maybe years and there was a huge productivity payoff for getting everything right. We used ‘usability testing’ where people unfamiliar with our system were asked to perform simple tasks whilst we, in another room behind a two-way mirror, groaned at our simple design mistakes.

Now, pretty much anything goes. I recently came across a black search box with a black background, for example; Microsoft ditched the Xerox Star menu system for its office products in favour of the ‘office ribbon’; Those who stick to the rules for accessibility are made to seem staid, dull and old-fashioned. The rule-breakers look cool and also lock their users in because of the learning required for change. Maybe it is time to fight back.

 

The post Xerox stars for accessibility appeared first on Simple Talk.



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