Problems displaying this newsletter? View online.
SQL Server Central
Featured Contents
Question of the Day
The Voice of the DBA
 

Refactoring SQL Code

One of the things I see software developers often talking about is how they refactor code. As they touch a class, method, etc., they may take the time to refactor the code to make it cleaner, perform better, or just add some documentation. It seems that a regular part of a software developer's job is refactoring code in the codebase.

That is unless they see a "don't touch this, no idea how it works" comment. There are plenty of those, and often everyone leaves that code alone.

I was thinking about this when I saw this article on strategies to refactor sql code. The article seems written more for PostgreSQL, but there are items that relate to T-SQL as well. The main thrust of the article is about trying to rewrite code to DRY (don't repeat yourself). The more changes you can make to shrink code, either to make it easier to read or avoid repeating those copy/paste items, the better off your team will be. It's easy to think those copies aren't a big deal, but it's easy to update code in one place because that solves the problem you were given, and forget to fix all the copies.

I don't know that anyone should implement all the techniques listed, but they are things to think about. Using CTEs, Views, APPLY, the WINDOW clause, and more can help improve the health of your codebase and make it easier for all the members of your team to understand how the system works.

I wonder how many of you have a refactor mentality when you touch code, or do you tend to leave things alone and add new queries/objects/etc. to your database. I wonder if the fear of breaking something that might be used by other code is on your mind. Or maybe you suffer from "not invented here" (NIH) and just add your own code.

If you refactor code, then what things do you look to change or improve? Any tips/tricks/guidelines you'd share with others? If you don't refactor code, why not?

I think testing is a big part of refactoring. If you have tests, then you can be less worried about your changes breaking something. There is a great video on practical refactoring. It's from the software engineering view, and it's long, but it's worth a watch if you have a few moments.

I wish more people tested their SQL code and refactored poorly written (or poorly performing) code on a regular basis.

Steve Jones - SSC Editor

Join the debate, and respond to today's editorial on the forums

 
 Featured Contents
SQLServerCentral Article

Working with JSON/JSONB Data in PostgreSQL using Python

sabyda from SQLServerCentral

This article discusses how to work with JSON data in PostgreSQL using Python.

External Article

How to Monitor and Optimize Batched Deletion Processes in SQL Server

Additional Articles from SimpleTalk

Batched deletions are a common strategy in SQL Server to manage large datasets without overloading the system, but poorly tuned deletes can cause blocking, long-running transactions, and heavy log usage. Learn how to monitor and optimize these processes for smooth, efficient database performance.

Blog Post

From the SQL Server Central Blogs - What’s New at AWS re:Invent 2025 – Day 1 Highlights

Anup Sivadas from SQLSailor.com

Day 1 is an absolute thrill at re:Invent! I normally dedicate this dynamic day to connect with new faces, explore the bustling expo hall, engage with customers and service...

T-SQL Fundamentals

Site Owners from SQLServerCentral

For anyone else who needs to write queries or develop T-SQL code for SQL Server, Azure SQL Database, or Azure SQL Managed Instance

 

 Question of the Day

Today's question (by Alessandro Mortola):

 

The Read Committed Snapshot Isolation behaviour

I am currently working with Sql Server 2022 and AdventureWorks database. First of all, let's set the "Read Committed Snapshot" to ON:
use master;
go

alter database AdventureWorks set read_committed_snapshot on with no_wait;
go
Then, from Session 1, I execute the following code:
--Session 1
use AdventureWorks;
go

create table ##t1 (id int, f1 varchar(10));
go

insert into ##t1 values (1, 'A');
From another session, called Session 2, I open a transaction and execute the following update:
--Session 2
use AdventureWorks;
go

begin tran;
update ##t1 
set f1 = 'B'
where id = 1;
Now, going back to Session 1, what happens if I execute this statement?
--Session 1
select f1
from ##t1
where id = 1;
 

Think you know the answer? Click here, and find out if you are right.

 

 

 Yesterday's Question of the Day (by Steve Jones - SSC Editor)

What is the PRODUCT

In SQL Server 2025, what does this return?

CREATE TABLE Numbers
( n INT)
GO
INSERT dbo.Numbers
(
n
)
VALUES
(1), (2), (3)
GO
SELECT PRODUCT(n)
FROM dbo.Numbers

Answer: 6

Explanation: PRODUCT is a new function in SQL Server 2025 that produces a product of all the values passed in. In this case, 1*2*3. Ref: PRODUCT - https://learn.microsoft.com/en-us/sql/t-sql/functions/product-aggregate-transact-sql?view=sql-server-ver17

Discuss this question and answer on the forums

 

 

 

Database Pros Who Need Your Help

Here's a few of the new posts today on the forums. To see more, visit the forums.


SQL Server 2017 - Administration
Deny Connect problem - I have a login I need to deny connect to on a server, but it is "hidden" inside a Windows Security Group instead of directly added to SQL Server security. I cannot deny connect to the whole group. I need to specifically not allow this specific login to connect to this server. But when I […]
SQL Server 2019 - Administration
Veeam Backup DAG issue. Access to availability group is not permitted. - Hi all,   Has anyone encountered an issue whereby using a distributed availability group to migrate data from cluster 1 to cluster 2 leaves stale GUIDs in the Veeam postgres database causing the backups to fail with the above error?   Anyone have a fix?   Thanks  
SQL Server 2019 - Development
CAST datetimeoffset(7) as a datetime in UK format - I have a view where I am casting a datetimeoffset(7) field to smalldatetime or datetime as my reporting application won't accept the datetimeoffset(7) format.  Problem is I am trying to get this field to show up in UK format.   I am using CAST to get my results.  I can get the format I need by […]
what are the downsides of TDE not running vs running? - hi for the 2 years i've been here I believe we've had "encryption" turned off in what i only know as the way we tell ssms to communicate with our sql servers ...and i've always thought meant also the server itself relaxing how it communicates back to whatever client is asking for data. recently an […]
Reporting Services
Catalog max connection pool size: 100 - Seeing this message repeated every 10 seconds in the RSHostingService_yyyy_mm_dd_hh_mm_ss.log file. Can anyone advise: a) Why this is being reported so frequently? b) Does it indicate the limit is being hit? c) If b is true, how can I increase it? I've had a look through the configuration files and can't find anything specifying "100" […]
Editorials
Your Security Checkup - Comments posted to this topic are about the item Your Security Checkup, which is is not currently available on the site.
How Important Are Real Time Decisions? - Comments posted to this topic are about the item How Important Are Real Time Decisions?
SQLServerCentral.com Website Issues
Website Stability 2025/12/05 - All week we've had issues with the site being up and down. There's been a tremendous amount of traffic to various pages, many of them old. Lots of redirects, and lots of volumes (hundreds or thousands of requests/sec). It seems like someone scanning archive.org and then hitting us from their various points. We have put […]
403 Forbidden - I created a post (or tried) in the 2022 Admin forum. https://www.sqlservercentral.com/?post_type=topic&p=4694880 But it's now inaccessible. Not sure what I did wrong.
Article Discussions by Author
Unlocking Data Transformation: My journey with dbt (Data Build Tool) on SQL Server - Comments posted to this topic are about the item Unlocking Data Transformation: My journey with dbt (Data Build Tool) on SQL Server
Putting the Player with the Number - Comments posted to this topic are about the item Putting the Player with the Number
Fabric Mirroring - Comments posted to this topic are about the item Fabric Mirroring
T-SQL in SQL Server 2025: The UNISTR Function - Comments posted to this topic are about the item T-SQL in SQL Server 2025: The UNISTR Function
SQL Server 2022 - Administration
Help! MEMORY_ALLOCATION_EXT wait stalls - Hi I have an overnight process that moves allot of claims records Been working fine for many years. Now it hits this part of the code (across a linked server) and gets the (1596567ms)MEMORY_ALLOCATION_EXT wait type and will sit there forever and never move any records - no delta movements at all. Used to complete […]
SQL Server 2022 - Development
This doesn't make sense to me - making me crazy - er - Hi So I have the below select query that won't return results if I have it this way:   --DOES NOT RETURN-- AND EXISTS (SELECT 1 FROM edi.dbo.PEC_RGT_EDI_834_Inbound_Exception xx WHERE (xx.SubscriberNumber = x.subscribernumber OR x.MBI = xx.mbi) AND xx.LastDateProcessed>'05/31/2022') But will return results with this very small change: --DOES RETURN-- REPLACE ABOVE WITH BELOW AND […]
 

 

RSS FeedTwitter

This email has been sent to {email}. To be removed from this list, please click here. If you have any problems leaving the list, please contact the webmaster@sqlservercentral.com. This newsletter was sent to you because you signed up at SQLServerCentral.com.
©2019 Redgate Software Ltd, Newnham House, Cambridge Business Park, Cambridge, CB4 0WZ, United Kingdom. All rights reserved.
webmaster@sqlservercentral.com

 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -