When I first heard about SQL Server 2012’s SEQUENCE object – I thought it was an interesting feature to be added and one that I have been asked about by customers in the past (from those who had worked on different database platforms).  But when I looked at the CYCLE argument of SEQUENCE, that’s when I really got interested.

I wondered if it could be used in the service of implementing hash partitioning (of sorts) – allowing me to evenly distribute rows across a set number of partitions based on a hash key.  In this scenario I want the distribution to be evenly spread out, but NOT partition based on other business keys (like a datetime column or other attribute that has business or application meaning).

So will a column with a sequence default also work as a partition key? 

I started off by creating a new table based on AdventureWorkDWDenali’s FactInternetSales table:

-- Create demonstration Fact table, no constraints, indexes, keys

-- Tested on version 11.0.1750 (SQL Server 2012 RC0)

USE [SequenceDemo];

GO

CREATE TABLE [dbo].[FactInternetSales](

       [ProductKey] [int] NOT NULL,

       [OrderDateKey] [int] NOT NULL,

       [DueDateKey] [int] NOT NULL,

       [ShipDateKey] [int] NOT NULL,

       [CustomerKey] [int] NOT NULL,

       [PromotionKey] [int] NOT NULL,

       [CurrencyKey] [int] NOT NULL,

       [SalesTerritoryKey] [int] NOT NULL,

       [SalesOrderNumber] [nvarchar](20) NOT NULL,

       [SalesOrderLineNumber] [tinyint] NOT NULL,

       [RevisionNumber] [tinyint] NOT NULL,

       [OrderQuantity] [smallint] NOT NULL,

       [UnitPrice] [money] NOT NULL,

       [ExtendedAmount] [money] NOT NULL,

       [UnitPriceDiscountPct] [float] NOT NULL,

       [DiscountAmount] [float] NOT NULL,

       [ProductStandardCost] [money] NOT NULL,

       [TotalProductCost] [money] NOT NULL,

       [SalesAmount] [money] NOT NULL,

       [TaxAmt] [money] NOT NULL,

       [Freight] [money] NOT NULL,

       [CarrierTrackingNumber] [nvarchar](25) NULL,

       [CustomerPONumber] [nvarchar](25) NULL,

       [OrderDate] [datetime] NULL,

       [DueDate] [datetime] NULL,

       [ShipDate] [datetime] NULL,

)ON [PRIMARY];

GO

Next I created the sequence object (increment by 1, with a min of 1, max of 10, caching of 10 at a time and a cycling of values):

CREATE SEQUENCE dbo.Seq_FactInternetSales

    AS int

    START WITH 1

    INCREMENT BY 1

    MINVALUE 1

    MAXVALUE 10

    CYCLE

    CACHE 10;

After that, I added a new column to the Fact table called PartitionBucketKey and associated it with the new sequence object:

ALTER TABLE [dbo].[FactInternetSales]

ADD PartitionBucketKey int DEFAULT

(NEXT VALUE FOR dbo.Seq_FactInternetSales);

Next, I created a partition function and scheme:

-- Create a new partition function

CREATE PARTITION FUNCTION pfFactInternetSales (int)

AS RANGE LEFT FOR VALUES (1,2,3,4,5,6,7,8,9);

-- Create a new partition scheme

-- And yes, being lazy about the FGs, as I just want to see whether the

-- individual partitions fan-out the way I want...

CREATE PARTITION SCHEME psFactInternetSales

AS PARTITION pfFactInternetSales

ALL TO ( [PRIMARY] );

Next up, I created a clustered index on the table referencing the PK columns used in the original version of this table but then referencing the PartitionBucketKey in partition scheme:

-- Create it on the new column referencing the sequence

CREATE CLUSTERED INDEX IX_FactInternetSales

ON  dbo.FactInternetSales(SalesOrderNumber, SalesOrderLineNumber)

ON psFactInternetSales (PartitionBucketKey);

It’s show time.  Now I went ahead and populated 60,398 rows from the original table.  Not much for this test I realize, but this was just an initial proof-of-concept:

INSERT dbo.FactInternetSales

(ProductKey, OrderDateKey, DueDateKey, ShipDateKey, CustomerKey,

PromotionKey, CurrencyKey, SalesTerritoryKey, SalesOrderNumber,

SalesOrderLineNumber, RevisionNumber, OrderQuantity, UnitPrice,

ExtendedAmount, UnitPriceDiscountPct, DiscountAmount, ProductStandardCost,

TotalProductCost, SalesAmount, TaxAmt, Freight, CarrierTrackingNumber,

CustomerPONumber, OrderDate, DueDate, ShipDate)

SELECT ProductKey, OrderDateKey, DueDateKey, ShipDateKey, CustomerKey,

PromotionKey, CurrencyKey, SalesTerritoryKey, SalesOrderNumber,

SalesOrderLineNumber, RevisionNumber, OrderQuantity, UnitPrice,

ExtendedAmount, UnitPriceDiscountPct, DiscountAmount, ProductStandardCost,

TotalProductCost, SalesAmount, TaxAmt, Freight, CarrierTrackingNumber,

CustomerPONumber, OrderDate, DueDate, ShipDate

FROM [AdventureWorksDWDenali].[dbo].[FactInternetSales];

Now I’ll check if the 60,398 rows were divided up evenly over the 10 partitions:

SELECT partition_number, row_count

FROM sys.dm_db_partition_stats

WHERE object_id = object_id('[dbo].[FactInternetSales]')

clip_image001

It worked.  And if you look at the individual rows, you’ll see the cycle of sequence values were defined based on the PK composite key (SalesOrderNumber, SalesOrderLineNumber):

SELECT SalesOrderNumber, SalesOrderLineNumber, PartitionBucketKey

FROM [dbo].[FactInternetSales]

ORDER BY SalesOrderNumber, SalesOrderLineNumber

clip_image003

Okay, so it works.  But is this a wise thing to do? 

I don’t know yet.  I have other questions about this technique and I’d like to do more testing on various scenarios.  But I do like the fact that I’m able to leverage a native engine feature in service of another native engine feature.  Time will tell if this is a viable pattern or a known anti-pattern.

Categories:
SQL Server 2012

Update: ** Make sure to check out the comments at the end of this post.  There are some interesting differences in behavior between transactional replication (pull/push subscribers) versus merge replication's behavior.  ** 

Yesterday I was working on implementing transactional replication with the goal of limiting the permissions each replication account ran under.  I created three separate domain accounts for the snapshot, log reader and distribution agents.  These accounts had no other permissions before I began:

·        I created logins on the publisher and distributor (in this case, the same SQL Server instance) and I added the snapshot and log reader agent accounts to the db_owner role of the distribution and publisher databases. 

·        This was a push subscription, so I also added the distribution agent to the db_owner role for the distribution database, but I did not grant it access to the publication database.  I did make the distribution agent a member of db_owner for the subscription database (which was located on a separate server and default instance).

·        I gave the snapshot agent “write” permissions and the distribution agent “read” permissions to the snapshot share.

By the way, all this talk of db_owner makes it sound like I wasn’t limiting permissions all that much; however this fixed database role membership is indeed a minimum requirement in this implementation.  It’s also typically more restrained then what I’ve seen out in the field. Usually I’ll see the use of domain accounts with sysadmin used to manage everything in the replication topology.  I don’t usually see a separate set of accounts configured for each agent role, nor do I see them set up for each unique topology (for very large environments, the administrative overhead may not make this a practical choice – but that’s another discussion altogether).

I did leave out one step though – and I’ll get to that in a moment.  After applying the permissions I described, I set up the new publication and new subscription, and the data flowed correctly with no issues and no sysadmin permissions required.

The step I specifically left out was the adding of the distribution agent to the Publication Access List (PAL).  According to Books Online, “Access to a publication is controlled by the publication access list (PAL).”  Also according to Books Online, the distribution agent for a push subscription must “Be a member of the PAL.”  I wondered why? And if this is such a key area – why don’t we hear much discussion of the PAL?  If you search the replication forums, you’ll find very few questions about it (searching today, I found 26 loosely related threads).  Either this means that most shops use high privilege accounts and haven’t pushed further to find out the role of PAL – or the PAL role isn’t entirely what it seems to be (as its described, it seems to suggest that the distribution agent account needs membership in order to synchronize).

Now if it must be a member, why was transaction replication working properly (rows were moving fine from publisher to distributor and distributor to subscriber). 

My first assumption was that I missed something or that somehow the distribution agent account was getting implied permissions either through group membership.

The first thing I validated was the current PAL list of accounts (looking explicitly for my distribution agent account – called SQLskills\SQLskillsDistAGT).  Looking at the PAL, this account had NOT been explicitly granted membership somehow through other activities:

clip_image002

Perhaps SQLskills\SQLskillsDistAGT was gaining access through group membership?  Seemed unlikely to me, but I checked nonetheless by using EXECUTE AS LOGIN and querying the sys.login_token to see the groups associated with that account:

clip_image004

I didn’t see any connections or group memberships that would map to the PAL. 

My next thought was to examine the SQL Server Agent job and ensure it really was running under the context of SQLskills\SQLskillsDistAGT. The SQL Server Agent Job for the distribution agent was owned by the Administrator account, but the job step itself was running as the SQLskills\SQLskillsDistAGT proxy:

clip_image006

The proxy maps to a security credential, which in this case was my SQLskills\SQLskillsDistAGT account.  I validated the mapping by querying sys.credentials (checking the credential_identity column):

clip_image008

So the mapping was what I expected. 

But was the job really connected as that account?  I ran a few test transactions at the publisher and again confirmed that rows were flowing to the subscriber.  I then queried sys.dm_exec_sessions for the distribution agent session, checking the login name and running a few times to ensure it was incrementing the logical reads:

clip_image010

Logical reads were incrementing and the job was indeed running under the account.

So where are we?  Basically, I could find no connection whatsoever between the PAL membership and my distribution agent account. 

So because I wanted to be absolutely sure (and because this was a test environment) I removed all accounts from the PAL (including “sa”).  I did so one-by-one, testing to see if it broke replication.  And guess what?  Replication just kept on working.  I even restarted the agents to see if it would initiate some kind of challenge-response, and it did not. 

So is PAL access required?  And if so, what is the boundary of that requirement?

I logged off of my Administrator account and logged in to the publisher/distributor SQL Server instance as the SQLskills\SQLskillsDistAGT.  I then opened up SSMS and looked to see if I could view the publication:

clip_image012

No publications to be seen, even though this account is actually responsible for running the distribution agent and is doing so successfully.

I then jumped back on my Administrator account and first added SQLskills\SQLskillsDistAGT to the public role of the publication database (required in order to be seen in PAL) and then I added SQLskills\SQLskillsDistAGT to the PAL:

clip_image014

clip_image016

After doing this, I logged aback in as the distribution agent account, and sure enough, I can now “see” the publication (and also launch a new subscription, more importantly).

clip_image018

So this now made sense why PAL wasn’t the talk of the town.  Most DBAs I’ve worked with set up replication with their own high privilege credentials – even when designating other credentials for the replication agents.  Once they do, the agents work as advertised.  It’s when the agent account wishes to participate independently of the DBA that the PAL helps restrict the visibility of available publications.

If you’ve seen other variations or even contradictions related to the PAL - I’d love to hear about it.  We can help flesh out some of the ambiguities around this feature on this post.

Categories:
Replication

I received a question today about the impact of data compression on the transaction log.  While most of the time we talk about data compression from a data page and memory utilization perspective, I hadn’t actually directly tested the impact to transaction logging and I wanted to see it for myself. 

Here is just a very small scale test using data from AdventureWorks.HumanResources.Employee into two tables – one with a clustered index that is not using compression and one that is using page compression (I used a separate database just to keep things clean):

USE [CompressionTest];

GO

CREATE TABLE [dbo].[Employee](

      [EmployeeID] [int] IDENTITY(1,1) NOT NULL,

      [NationalIDNumber] [nvarchar](15) NOT NULL,

      [ContactID] [int] NOT NULL,

      [LoginID] [nvarchar](256) NOT NULL,

      [ManagerID] [int] NULL,

      [Title] [nvarchar](50) NOT NULL,

      [BirthDate] [datetime] NOT NULL,

      [MaritalStatus] [nchar](1) NOT NULL,

      [Gender] [nchar](1) NOT NULL,

      [HireDate] [datetime] NOT NULL,

      [SalariedFlag] [bit] NOT NULL,

      [VacationHours] [smallint] NOT NULL,

      [SickLeaveHours] [smallint] NOT NULL,

      [CurrentFlag] [bit] NOT NULL,

      [rowguid] [uniqueidentifier] NOT NULL,

      [ModifiedDate] [datetime] NOT NULL,

      [EncryptedNationalIDNumber2] [varbinary](128) NULL

) ON [PRIMARY];

GO

CREATE CLUSTERED INDEX [IX_Employee]

ON [dbo].[Employee]

(

      [EmployeeID] ASC

)

ON [PRIMARY];

GO

CREATE TABLE [dbo].[Employee_Compressed](

      [EmployeeID] [int] IDENTITY(1,1) NOT NULL,

      [NationalIDNumber] [nvarchar](15) NOT NULL,

      [ContactID] [int] NOT NULL,

      [LoginID] [nvarchar](256) NOT NULL,

      [ManagerID] [int] NULL,

      [Title] [nvarchar](50) NOT NULL,

      [BirthDate] [datetime] NOT NULL,

      [MaritalStatus] [nchar](1) NOT NULL,

      [Gender] [nchar](1) NOT NULL,

      [HireDate] [datetime] NOT NULL,

      [SalariedFlag] [bit] NOT NULL,

      [VacationHours] [smallint] NOT NULL,

      [SickLeaveHours] [smallint] NOT NULL,

      [CurrentFlag] [bit] NOT NULL,

      [rowguid] [uniqueidentifier] NOT NULL,

      [ModifiedDate] [datetime] NOT NULL,

      [EncryptedNationalIDNumber2] [varbinary](128) NULL

) ON [PRIMARY];

GO

CREATE CLUSTERED INDEX [IX_Employee_Compressed]

ON [dbo].[Employee_Compressed]

(

      [EmployeeID] ASC

)WITH (DATA_COMPRESSION=PAGE) ON [PRIMARY]

GO

Now the test is very simple.  I perform a full backup, and an initial transaction log backup:

BACKUP DATABASE CompressionTest TO DISK = 'c:\temp\CompressionTest.bak';

BACKUP LOG CompressionTest TO DISK = 'c:\temp\throwaway.trn';

Next, I insert 290,000 rows into the uncompressed table:

SET NOCOUNT ON;

INSERT dbo.Employee

(NationalIDNumber, ContactID, LoginID, ManagerID, Title, BirthDate,

MaritalStatus, Gender, HireDate, SalariedFlag, VacationHours,

SickLeaveHours, CurrentFlag, rowguid, ModifiedDate, EncryptedNationalIDNumber2)

SELECT NationalIDNumber, ContactID, LoginID, ManagerID, Title, BirthDate,

MaritalStatus, Gender, HireDate, SalariedFlag, VacationHours,

SickLeaveHours, CurrentFlag, rowguid, ModifiedDate, EncryptedNationalIDNumber2

FROM AdventureWorks.HumanResources.Employee;

GO 1000

Data used is 74,288 KB:

EXEC sp_spaceused 'dbo.Employee';

Querying the log record length from fn_dblog shows 120,503,216 bytes:

SELECT SUM([log record length])

FROM fn_dblog (NULL, NULL);

Backing up the transaction log produces a file that is 121,964 KB in size:

SELECT SUM([log record length])

FROM fn_dblog (NULL, NULL);

Now to insert rows into the table with data compression:

INSERT dbo.Employee_Compressed

(NationalIDNumber, ContactID, LoginID, ManagerID, Title, BirthDate,

MaritalStatus, Gender, HireDate, SalariedFlag, VacationHours,

SickLeaveHours, CurrentFlag, rowguid, ModifiedDate, EncryptedNationalIDNumber2)

SELECT NationalIDNumber, ContactID, LoginID, ManagerID, Title, BirthDate,

MaritalStatus, Gender, HireDate, SalariedFlag, VacationHours,

SickLeaveHours, CurrentFlag, rowguid, ModifiedDate, EncryptedNationalIDNumber2

FROM AdventureWorks.HumanResources.Employee;

GO 1000

Data used is 36,800 KB (versus 74,288 KB):

EXEC sp_spaceused 'dbo.Employee_Compressed';

Querying the log record length from fn_dblog shows 100,677,612 bytes versus the uncompressed 120,503,216 bytes:

SELECT SUM([log record length])

FROM fn_dblog (NULL, NULL);

Backing up the transaction log produces a file that is 102,158 KB in size (versus 121,964 KB):

SELECT SUM([log record length])

FROM fn_dblog (NULL, NULL);

So on a much larger scale – you can imagine the transaction log size reduction could be non-trivial.  Mileage will vary on the overall compression you can get from specific tables and data – but this is just another potential benefit to be aware of.  And as an aside, compressed rows are written to the transaction log in the ROW compression format and not the PAGE type.

Categories:
Performance

My first SQLSaturday (104) experience was a great one.  I got a chance to meet many new people (speakers, organizers and attendees), reunite with several others who I’ve met in previous contexts and also map Twitter handles to “real life” people.  

In addition to socializing with folks, I also got a chance to watch some great talks, including those from Tim Ford, Grant Fritchey, Jim Murphy, Jason Strate and Karen Lopez (and the tail end of a talk from Chris Randall which – although I was late, was really enjoyable and I wished I had seen the whole thing).  While the technical content is interesting, I also liked watching the different presentation styles.  For example, I liked Tim Ford’s easy (and subtle) sense of humor and creative visual layout of the DMVs that made a dense topic more easily accessible.  I also took note of Grant Fritchey’s energy and topic focus (drilling down on parameter sniffing), Jim Murphy’s ability to manage multiple moving parts in a smoothly presented AlwaysOn demo, Chris Randall’s clarity of examples (and he’s got a great sense of humor), Jason Strate’s approachable speaking style + Zen-like PPT format and Karen Lopez’s ability to “own” the room and get people actively engaged in the presentation.

SQLSaturday 104 was also my first chance to present “Performance Issue Archetypes” and I really enjoyed the experience. Plenty of suspense since it was a 2:30PM session.  My session was scheduled at the same time as some popular sessions (like Thomas LaRock’s well-received “Choose Your Own Adventure” session and John Morehouse’s “10 Things That Every DBA Should Know!”)  So even with the concurrent sessions, I was thankful to still get an audience.   I do think I jammed way too much material into one hour.  I think my session could easily have fit into 3 hours with some additional demos added – and that was after some heavy cutting I did a few weeks beforehand.  I’ll likely calibrate this presentation over time – but I did get feedback that folks got actionable value from the talk – so that made me happy (especially since this was the whole point of the talk).

Speaking of which, you can download the PDF of my presentation here.  Just note that there were some twists and turns “off deck” and that the presentation deck itself was the launching point.  Hopefully you can see the presentation in-person someday. 

SQLSaturday 104 was a great way to kick off what promises to be a year of new experiences and a significant workload. Coupled with a full plate of ongoing consulting engagements, I’ll be teaching modules alongside Paul, Kimberly and Jon in the IE2: Performance Tuning and IE3: High Availability & Disaster Recovery Immersion Events.  This means I’ll be heading to Tampa, Chicago, London and Bellevue at minimum.

On a somewhat related note; it’s been about 4 months since I joined SQLskills.  A few people have asked how it’s been so far – and here are my general observations:

·        Bottom line is that it going really well.  With any big move, it’s easy to second guess yourself – particularly since I was leaving a job with plenty of opportunity and 6 years of accumulated benefits and relationships.  I haven’t regretted it though.  Quite the opposite, the last four months have just felt “right”.  I’m working just as hard – but working on the areas that put me in the “flow state” (talking about Mihály Csíkszentmihályi’s flow) for a good majority of the day.  Consulting/writing/teaching/learning.  All good.

·        Of course a major aspect of it is getting the chance to collaborate with Kimberly, Paul and Jon.  It is great to be able to share ideas and brainstorm on tough or interesting scenarios.  The energy level they have is mind boggling.  There is so much to do/learn/investigate that the toughest part is choosing where to focus next.

·        Since October I’ve worked with 24 different customers on various types of engagements. This is by far my favorite aspect of the job. The engagements have covered performance tuning & scalability, health checks, security, benchmarking, high availability and disaster recovery.  I’ve also been involved in some writing projects and will likely have more IP related work throughout this next year interspersed with the Immersion Events.  Regarding events, I do hope to attend and speak at more events, schedule permitting.

·        Paul and Kimberly have also let me get involved in the business side of things (for example – pre-engagements and scoping calls). I appreciate this since I like meeting new people and listening to new problem scenarios (it’s like getting a new puzzle to work on).   

So thankfully, it’s all good.  I hope not to kick the bucket any time soon, since I’m enjoying this.  Lots of work ahead this 2012, but its meeting my initial aspiration I quoted from NYT last October to “make progress in meaningful work every day.”

Categories:
Off Topic

Theme design by Nukeation based on Jelle Druyts