Wednesday, September 14, 2022

T-SQL Tuesday #154 – SQL Server 2022, IS DISTINCT FROM

Despite my recent job change from full time T-SQL code jockey/architect to website editor for Simple-Talk, I will always be at heart at T-SQL programmer. While I will mostly be writing professionally in the foreseeable future will in support of an article, I will also continue writing code for several databases that I use for multiple personal reason housed on a SQL Server Express server on the desk beside me.

The Invitation: T-SQL Tuesday #154 Invitation – SQL Server 2022 (glennsqlperformance.com)

When I saw the topic of this T-SQL Tuesday was to write about what I have been doing with SQL Server 2022, I figured I would note the two things I have been doing recently. First, I wrote a chapter about security changes in SQL Server 2002 for a forthcoming book entitled “SQL Server 2022 Administration Inside Out” for Pearson with a great group of people that should be out later this year, early next at the latest. There are a few things I found out writing that chapter that I am keen to use, one of them being the more granular UNMASK permissions for the Dynamic Data Masking feature, but since I won’t be writing multi-user production code in the future, I probably won’t be masking any data, much less need granular masking capabilities.

The other thing I have been doing is trying out some of the new features coming in SQL Server 2022 that I will absolutely be using even in my hobby databases. There are tons of new features in 2022, as there always is. But the ones that excite me are the T-SQL improvements. In this article I am going to highlight 1 feature that is immediately a standout.

IS (NOT) DISTINCT FROM

The MOST exciting change from a T-SQL standpoint is: IS NOT DISTINCT FROM. This feature solves an age-old issue for T-SQL programmers and is worth its weight in gold. It is basically an equals comparison operator like =, but treats NULL as an individual value. Unlike =, this new operator returns only TRUE or FALSE, but not UNKNOWN. Writing queries that compare to values that can contain NULL is tedious, mostly because of code like the following:

SELECT CASE WHEN 1 = NULL THEN 'True' Else 'False' end,
       CASE WHEN NOT(1 = NULL) THEN 'True' Else 'False' end

The fact that both of these comparisons return False is confusing at times even to me, and I have written on the whole NULL comparison and negating NULL values things about as many times as I have dealt with it in production code. But using IS DISTINCT FROM, this is no longer the case:

SELECT CASE WHEN 1 IS DISTINCT FROM NULL 
               THEN 'True' Else 'False' end,
       CASE WHEN NOT 1 IS DISTINCT FROM NULL
               THEN 'True' Else 'False' end

Where this is really important is doing a query where you are looking for differences between two sets of data (often for a merge type operation). So consider the following table (from WideWorldImporters, which you can get here) :

SELECT COUNT(*), 
       SUM(CASE WHEN LatestRecordedPopulation IS NULL 
           THEN 1 ELSE 0 END)
FROM Application.Cities;

This returns 37940 total rows and 11048 rows with a NULL population value. Now, let’s join the table to itself on the PK and the population value

SELECT *
FROM   Application.Cities
          JOIN Application.Cities AS C2
            ON C2.CityID = Cities.CityID
WHERE.LatestRecordedPopulation 
                         = Cities.LatestRecordedPopulation;

This returns 26892 rows, which you can do the math, is 37940-11048. Looking at this, without thinking about NULL values (who does initially?), this has to return every row in the table. But clearly not. Usually this becomes obvious when a few customers living in one of those cities isn’t showing up on a report (or maybe even not getting their shipments.)

The pre-SQL Server 2022 way of handling this properly this was to do something like this:

SELECT *
FROM   Application.Cities
          JOIN Application.Cities AS C2
               ON C2.CityID = Cities.CityID
                  AND C2.LatestRecordedPopulation = 
                                      Cities.LatestRecordedPopulation 
                    OR (C2.LatestRecordedPopulation IS NULL
                        AND Cities.LatestRecordedPopulation IS NULL);

Now we have checked the either they are the same value, or they both have a value of NULL. This query returns every row in the table, but it is kind of tricky code. And looking for differences is even more difficult, because you have to check to see if the values are different, if column 1 is null and column2 is not, and again vice versa. Another way this is often done is to change the population comparison to

AND COALESCE(C2.LatestRecordedPopulation.-100) = 
             COALESCE(Cities.LatestRecordedPopulation,-100)

Which is safe from a correctness standpoint (assuming you can coalesce your values to something that is 100% not possible), but not from a performance one. This eliminates index seek utilization for these columns and makes it slower. That isn’t always an issue, but for larger data sets, you may end up with more scans than you hoped.

Using the new syntax, we can simply write this as:

SELECT *
FROM   Application.Cities
         JOIN Application.Cities AS C2
           ON C2.CityID = Cities.CityID
              AND C2.LatestRecordedPopulation 
                    IS NOT DISTINCT FROM 
                           Cities.LatestRecordedPopulation;

The name of the operator might be a little bit confusing because of the words FROM and DISTINCT, it really makes sense. DISTINCT has a seemingly different usage here, but really it is the same meaning. If the value is the same, it is not distinct from one another, and if it is different, it is distinct. And the DISTINCT operator in the SELECT clause honors NULL values as a single bucket too. Now, go back and change the previous query to IS DISTINCT FROM and 0 rows will be returned.

This feature would have saved me many many hours over the years! Is this alone a reason to upgrade to SQL Server 2022 alone? Since I have never been the one to write those checks, and I use the free Express edition for my hobby databases… I can say an unqualified “Yes” to that!

 

The post T-SQL Tuesday #154 – SQL Server 2022, IS DISTINCT FROM appeared first on Simple Talk.



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

Monday, September 5, 2022

Synapse Analytics: When you should use (or not use) Synapse

Synapse is a great data lake house tool. This means in a single tool we have resources to manage a data lake and data warehouse.

The Synapse Serverless Pool is great to manage data lakes and for a great price: around us$ 5,00 for each TB of data queried. This makes it a great choice.

For the data warehouse, on the other hand, it’s a bit different. Before Synapse, there was Azure SQL Data Warehouse. This product was rebranded as SQL Dedicated Pool. The change on the product name helped to put down an old mistake: People believe that for a Data Warehouse in the cloud they need to use Azure SQL Data Warehouse.

The idea was reduced, but a lot of people still think they need to use Synapse for a Data Warehouse. This is a mistake. A data warehouse is not related to a tool. It’s a database. Some tools may be better or worse for the data warehouse. In relation to Synapse, as the usual answer from every specialist, “It depends”.

What’s the Synapse SQL Dedicated Pool

Understanding what is the SQL Dedicated Pool is the key to understand when you need to use it or not. The most common misconception is to believe the SQL Dedicated Pool is only a simple database. It’s not.

The SQL Dedicated Pool is a MPP tool. MPP stands for Massive Parallel Processing. This is an architecture intended to break down a processing request between many processing nodes, join the processing result from the individual nodes and return the final result. It’s much more than simple parallel processing, its’s a distributed processing broke down in many physical nodes.

 

The data is stored in a structure optimized for the MPP execution. What you may see as a single database is in fact a total of 60 databases. Each table is broken down in 60 pieces. This can be a great organization for the MPP execution, but there are more details to analyse.

Synapse Dedicated Pool Service level

The service level of the SQL Dedicated Pool defines the number of physical nodes the dedicated pool will have. Any service level below DW 1000 will use only one node. DW 1000 is the first level with 2 nodes and the number grows up to 60 nodes.

The number of databases used to broke down the data is fixed, always 60. These databases will be spread among the physical nodes the dedicated pool contains. For example, if the dedicated pool has two nodes (DW 1000), each node will contain 30 databases.

The first important point is the service level: You should should never use a dedicate pool with less than DW 1000.

 

Below DW 1000, there is no real MPP. However, your data is optimized for MPP. Your data is broken down is 60 pieces. Without using a MPP, you will be losing performance instead of getting better performance.

If for any reason you believe you need a SQL Dedicated Pool below DW 1000 in production, that’s because you don’t need a SQL Dedicated Pool, a simple Azure SQL Database may do the job.

Data Volume

Synapse usually makes an interesting recommendation to us: Never use a clustered columnstore index on a table with less than 60 million records in Synapse. If we analyse this recomendation, we may discover some rules about when to use or not use Synapse.

 

First, it’s important to better understand the columnstore indexes and how important they are.

Let’s columnstore indexes features and behaviours:

  • They are specially optimized for analytical queries
  • The index is compressed
  • They are in memory
  • Allow batch mode execution and optimization

The columnstore indexes are very important for data warehouses. We would be losing a lot by not using them. Why Synapse doesn’t recommend them for tables smaller than 60 millions ?

The physical structure of the columnstore indexes use segments with 1 million rows each. The segments are “closed” and compressed on each million records. That’s why the 60 million recomendation: Synapse breaks down each table in 60 pieces. 60 pieces with 1 million rows each makes a total of 60 millions. Any table with less than 60 million rows will have less than 1 million rows on each of their pieces, resulting in incomplete segments and affecting the work of the columnstore index.

Is this a rule to be always followed? Not at all, that’s why it’s just a recommendation. A data warehouse uses star schemas. Usually, the fact table is way bigger than the dimension tables. It’s ok if we have some small dimension tables around a very big fact table, this is not a problem. The problem is when your entire model has no table with the size which requires Synpase for a better processing.

Consumers

Synapse can be very good as a central data source for BI systems such as Power BI, Qulick and more. However, if there is no directly BI system consuming the data, if most of the consumers are other applications receiving data through ETL processes, maybe Synapse is not the better option. Data lakes could perform the same task for a lower cost in this situation.

Summary

Should you use Synapse ? Your volume of data, the need for an MPP and the consumers of your data can provide a good guidance about whether Synapse is a good choice for your solution or not.

The post Synapse Analytics: When you should use (or not use) Synapse appeared first on Simple Talk.



from Simple Talk https://ift.tt/9SzEZwV
via

Thursday, September 1, 2022

Starting my dream job…

A new adventure, there in your eyes.

It’s just beginning,

Feel your heart beat faster.

Reach out and find your

Happily ever after!

Well, here I am. My first new job in over 20 years and it is a dream come true. I have always wanted to do more to help people learn about technology and being the Editor of the Simple Talk website is going to be a great place to do that. I have admired the heck out of the people who I am following and I have worked with them all over the years.

How that dream comes out, who knows? I won’t pretend the back of my head isn’t filled with the little voices telling me “you are the imposter” like we are playing a game of Clue only we are looking for the person who shouldn’t be there rather than a murderer. As I said, I have known the previous editors and they were all the greatest… can I keep up.?

I have come to realize that practically everyone has that same voice echoing frustrations in their cavernous skull boxes. And it is okay. It probably is the only thing standing between some of us trying to fly without wings over the edge of the Grand Canyon (or since Redgate is headquartered across the pond from me, the White Cliffs of Dover). Doubt makes us work smarter along with harder when it isn’t making us doubt our ability to do anything.

I don’t want to be better than my predecessors, or worse, or even the same. I want to be me and do the things that I am good at and surround myself with people who make me look (but not feel) dumb.

I wrote this the night before I start at Redgate and am publishing it 10 minutes before my first meeting. As I often do,  I read this to my editor (my wife Dr Valerie Davidson, real Dr of Education, not like my drsql Twitter handle!), she asked “do you really want to come off sounding so scared?” I just want to be honest about how I feel the night before I start.

I want to say that I feel like a 10 year old kid about to board their first roller coaster with an inversion. Excited beyond words and also scared to death. Will this be the most amazing thing, or will it kill me? I have experienced first roller coaster rides with several people who were scared of it for too long, some with tears (ok, maybe that was me). Most get finished with that first ride and it becomes something they like. A few hate it. Others, it becomes an obsession (this was me.)

Did I mention I am a theme park fanatic? I often do! This was the picture I took for the company directory. Fun fact, my first interview was from Dollywood where I was about to do some article interviews of some of their hosts. I have a YouTube channel and a theme park blog too.

 

My experience with roller coasters is very similar to my experience with the SQL Server community for the past 20 years (or maybe more, you can see I am not 22 in the picture). I was scared silly to get involved, then I did, then it changed my life forever. I hope I can live up to task of helping others do the same. Either way, I will give it my all and do my best to have no regrets.

Lets go!

The post Starting my dream job… appeared first on Simple Talk.



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

Do not be surprised

For the first time in eleven years of travel, I became profoundly sick while on the road. No, I’m not sharing details of any kind. What I will share is just this; I wasn’t prepared.

When I travel, I look at the weather, where I’m going, how long, and I pack accordingly. I have my presentations and code backed up, locally, at home, and on the cloud. I’m ready for flight cancellations and all sorts of travel mishaps. But I was not ready for being ill. I really should have been.

I think a lot of our emergency preparedness is like this. We think we have our backups, high availability, disaster recovery all set. After all, we’ve experienced a lot of different outages and have learned from them. Further, we know that things go wrong, so we look at what happens to others and try to learn from them, rather than on our own. Yet, chances are, something is going to take you by surprise.

What can you do?

Well, same as you’ve done mostly. Examine and test your preparations. Learn from others. Keep an eye out for changing circumstances. Most of all, practice recovery. Finally, try to develop a resilient attitude about things. That should be as much a part of your preparations as anything else.

Commentary Competition

Enjoyed the topic? Have a relevant anecdote? Disagree with the author? Leave your two cents on this post in the comments below, and our favourite response will win a $50 Amazon gift card. The competition closes two weeks from the date of publication, and the winner will be announced in the next Simple Talk newsletter.

The post Do not be surprised appeared first on Simple Talk.



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

Wednesday, August 31, 2022

Into the unknown, sort of

Over half of my life ago, I was looking for a job. I had written a bunch of triggers and stored procedures at my first job, but I was relatively green. I had just (barely) gotten my degree in Computer Science, and was looking to get out of Cleveland, TN. I checked around and found a headhunter that found me a couple of opportunities.  One was in downtown Atlanta, Georgia. The other was in Virginia Beach, Virginia. Considering traffic in Atlanta and my, at the time, complete fear of driving in heavy traffic… amongst other reasons… I opted for Virginia Beach.  If you want to know where, it isn’t hard to find, I’ve never made it a secret…

I am not going to say that every minute of every day I worked in Virginia Beach was awesome. They have traffic there, they have hurricanes, and I have coworkers there that are human beings. But over the years I worked there, I have honestly loved everyone I worked with and many of the things we have accomplished. It is very hard to say such things about any other job I have had, though to be fair that is a pretty low number of locations. After working there for five years, it was time to try a new location. 

A coworker of mine called me up about working for a startup in Nashville, Tennessee which delivered Internet to schools. I got to work with different data, different concepts, but just as I have for 25 years, I was working with SQL Server designing Databases and writing T-SQL code. After around 4 years there, I was laid off (which was mostly sad only because I missed the day when the FBI came in and carted off materials. It wasn’t like it was anything sinister, more improper influencing kind of stuff. In fact the company still exists in a slightly different form doing a subset of what we did 15 years ago. I even just read today that the company merged with another in the past few months). 

As I was looking for a job to replace that one, my old company was in the process of setting up a location in Nashville as a disaster recovery\call center site.  I went back and managed their call center equipment for a few years until they could fill out a complete staff. If you are reading this, you probably can guess this is NOT my first, second, or third love in life or even technology.  

After proper call center/hardware management was hired, I went back to my real love database design and implementation. I started working with a team back in Virginia Beach exclusively and was more or less telecommuting from a different office space. Due to the traffic in Nashville, I gradually introduced my company to the actual concept of telecommuting. It was not accepted with open arms. For several years I did this and was kind of the only one. It was a nightmare at times, because if you have ever joined a meeting where you are the only one remote, it is a pain. But the times, they were changing. Even pre-pandemic, they started hiring people to work from anywhere. So much so that a coworker just moved out of country one day, I don’t even think he told our manager first. 

Over the years, I have only considered changing jobs a few times. I have always had a very short list of places I would consider changing jobs to. Very short. One company on that list had a job I had always wanted, called me and basically said “You have the job” and then interviewed me and said “You have the job” and then I didn’t hear back for a few weeks instead of a few days. They had changed their mind due to a reduction in telecommuting and I wasn’t moving that far away from my aging mother. Kind of funny at this point. 

A few months ago, I learned of a job with one of the other companies on my short list that I had lightly coveted when the previous person took it. This person decide to move on, and t he rest is history (which will probably show up in later blogs!) 24 years and just over 9 months of employment later… I am saying goodbye. It is sad. I am leaving a family behind to deal with 20+ years of code I wrote. Some utilities are from my first stint there over 20 years ago which I still occasionally had to update. 

 But it is time and the new journey is going to be incredible. My next position will be using the other skill I employ more than any other. (And I am not talking about theme park photography). Where am I heading? A place we all know and love. More on that in my next blog.

The post Into the unknown, sort of appeared first on Simple Talk.



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

Tuesday, August 30, 2022

.NET App Services: Containers or not containers, that’s the question

The app services in the title can be function apps, web apps or more. We can deploy the app services on the native app service environment provided by Microsoft or using containers.

What’s the different between using the native environment or using containers?

The differences aren’t many and it’s not easy to identify when it’s better to use the native environment or when its’s better to user containers.

There are two main differences we can identify:

  • The cold startup time is better using the native environment than using a container
  • We need to manage all the patches to a custom container, in the opposite to the native environment. Microsoft manages the patches to the native environment.

These doesn’t appear to be very critical decision points on most situations. But let’s dig further and add more variables.

Certificates and Containers

We can choose to use a Linux container or use a Windows container. There are some differences according to our choice. A few weeks ago, I stumbled upon one of the difference.

In some applications, we may need to insert a certificate inside the container.  WEBSITE_LOAD_CERTIFICATES is a special configuration we can use for this. This configuration makes the app service insert the certificate inside the container.

In windows containers, the app service installs the certificate inside the windows certificate storage and the certificate is recognized by the applications in the container.

On the other hand, if the container uses linux, the certificate is copied to one folder in a DER format. Most of the times the application will need to read the certificate from the file system and use it by code. This would require code change, usually this is not good.

These links contain explanations about this configuration and code to read the certificate from the file system in a Linux container:

https://docs.microsoft.com/en-us/azure/app-service/configure-ssl-certificate-in-code

https://stackoverflow.com/questions/55599001/azure-function-key-vault-reference-for-certificates

Security Scans

This happened to me some weeks ago. A security code scan tool started to complain about one dll: Microsoft.AspNetCore.Http.dll version 2.1.0.

You can find more about this issue on the following links:
https://github.com/dotnet/announcements/issues/165
https://nvd.nist.gov/vuln/detail/CVE-2020-1045#match-6013238

This assembly is a reference included in the package Microsoft.NET.Sdk.Functions . More than that, it’s part of the .NET Core Framework. How to solve a security problema like this?

It’s usual to find security problems with frameworks such as .NET Core. The framework is always evolving. You can check the framework versions and the security patches published on the following links:
https://dotnet.microsoft.com/en-us/download/dotnet/3.1
https://dotnet.microsoft.com/en-us/download/dotnet/6.0

The solution to the security problem is to update the .NET Core framework on the execution machine.

There are some details capable to make anyone confused. When the .NET project is compiled, the assemblies are inserted in the BIN folder. The version of the Microsoft.AspNetCore.Http.dll is the bad version, 2.1.0, even if the .NET Core framework on the machine is updated. How could this be possible?

We can even think further: if the assembly is in the BIN folder, this means a devOps pipeline would pack and deploy this assembly. How the update on the .NET Core framework would solve this?

The explanation is simple: Framework assemblies in the BIN folder are ignored, and the app uses the .NET Core assemblies.

Checking .NET Version in an App Service

App Services have the Advanced Tools. On the left menu, you under Developer Tools, you can click Advanced Tools and click the link Go on the page which will appear in the middle.

This will open an advanced development environment. On this environment, click  Debug Console on the top menu and choose a CMD console or Powershell console. Both can be used.

Once on the console, you can use one or both of the following statements:

dotnet –version

dotnet –list-runtimes

The first one will tell you the .NET version. You can use the .NET download pages (links above) to confirm your environment is up-to-date with the latest .NET version.

The 2nd one will tell you the exactly version of the main core libraries. The security report usualy will contain exactly the library versions you should have to be safe and you will be able to confirm you have them.

 

 

Security Scans Impact on App Service Containers

If you deploy your app service on the native environment, the app service will make updates to the .NET Core regularly. Microsoft deploys new fixes to the app service environment in 1 or 2 weeks after they are available.

However, if you deploy your app service as a container, it’s your responsibility to make updates to the container. You will be the responsible to create an automated flow in your devOps environment to identify new security features to the environment, update the container image and deploy it again regularly, avoiding down time.

Conclusion

Innitialy the requirement to manage the updates to the app service containers may appear a small difference, but when we check the security updates and the need to create an automated process to apply these security updates to the containers images we end up finding a very good reason to avoid deploying containers to app services and stick to the native environment.

If something changes later, it’s easy to deploy the application to a container when needed.

 

The post .NET App Services: Containers or not containers, that’s the question appeared first on Simple Talk.



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

Thursday, August 4, 2022

Technology is hard

I book my travel almost exclusively through a single airline and its affiliates. There are a lot of reasons for this, but the big one is status. And no, not so I get upgrades (although they are very nice), but so when things go wrong, I have a hotline to getting them fixed. However, I don’t want to talk about that today, I want to talk technology. See, my airline’s web site won’t run properly on my work laptop.

And works everywhere else.

Oh, I’ve tried it all. Changed the location on my VPN. Turned off my VPN. Browser A. Browser B. Browser C (even though I vowed I’d never install that junk ever again). Heck, off-brand Browser D. Uninstall the VPN. Reset the internet connection. Tether from the phone. Install updates. Get on the phone with tech support. Clear the browser cache (like going to a different browser doesn’t obviate the need for this one, but, hey) and the history.

Yet, if I walk three feet to my personal laptop, it works fine. My wife doesn’t have a problem. I can log in from my phone. My children’s laptops also connect. Nope. It’s just the one laptop.

After all that, you know the one thing I have learned?

Technology is hard.

I mean think about it. We have these web pages that work, almost, for everyone, almost, all the time, almost. Yeah, I know, joking. However, they really do work, and for huge swaths of the populace, despite all the wild variation on technologies employed. Yet, when things go south, very tiny as in my case, or huge when systems are hacked or experience internally generated outages, they go very badly wrong. Recovery is hard. Troubleshooting, extremely difficult, even if you have the skill (and too many do not), takes forever. All of it hurting our organizations and causing pain for ourselves.

We are in a position where we’re working miracles, but it’s all with some pretty brittle tech because, frankly, this stuff isn’t easy.

Now, I need to grab my other laptop so I can book a trip.

Commentary Competition

Enjoyed the topic? Have a relevant anecdote? Disagree with the author? Leave your two cents on this post in the comments below, and our favourite response will win a $50 Amazon gift card. The competition closes two weeks from the date of publication, and the winner will be announced in the next Simple Talk newsletter.

The post Technology is hard appeared first on Simple Talk.



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