Thursday, January 29, 2015

SQL query to return multiple SUMs in a single line result

Another good question from one of my customers today --

"... how to take two or more records and summarize them into one record. "  


I can't tell you how many times I've done this when reporting traded volumes.  Daily, weekly or monthly, grouped by symbol, or trader, or even trading desk.... This new customer's data is a little different, but the approach is the same.  This is just a quick post, providing a method to bring your data counts back in single line result-sets.

USE DBA; -- change to your dbname

DECLARE @input TABLE (UserID INT, FiscalYear INT, GiftAmt DECIMAL(5,2))
INSERT @input (UserID,FiscalYear,GiftAmt)
VALUES (1,2012,100.00),
  (1,2012,50.00),
  (1,2013,110.00),
  (1,2014,50.00),
  (1,2014,50.00),
  (1,2014,75.00),
  (2,2012,65.00),
  (2,2014,55.00),
  (2,2014,55.00),
  (2,2014,75.00),
  (3,2012,10.00),
  (5,2011,20.00),
  (5,2013,55.00),
  (5,2014,55.00);

-- Look at your data, see you've got 14 records
-- SELECT * FROM @input

-- Now bring it back out in 4 lines, one for each UserID
SELECT 
UserID,
   ISNULL(SUM(FY1Amt),0.00) [FY1Amt],
   ISNULL(SUM(FY2Amt),0.00) [FY2Amt],
   ISNULL(SUM(FY3Amt),0.00) [FY3Amt],
   ISNULL(SUM(FY4Amt),0.00) [FY4Amt]
FROM
(
SELECT 
UserID,
FiscalYear,
CASE WHEN FiscalYear = 2011 THEN SUM(GiftAmt) END [FY1Amt],
CASE WHEN FiscalYear = 2012 THEN SUM(GiftAmt) END [FY2Amt],
CASE WHEN FiscalYear = 2013 THEN SUM(GiftAmt) END [FY3Amt],
CASE WHEN FiscalYear = 2014 THEN SUM(GiftAmt) END [FY4Amt]
FROM
@input a
GROUP BY
UserID,
FiscalYear 
) x
GROUP BY 
x.UserID

Your results will look like this:

   UserID   FY1Amt  FY2Amt  FY3Amt    FY4Amt
      1          0.00       150.00     110.00       175.00
      2          0.00         65.00       0.00       185.00
      3          0.00        10.00        0.00          0.00
      5        20.00          0.00      55.00         55.00

Now that I think about it, I believe I did a similar post once before, for the single-line result sets. A different method, maybe a bit older.. but the single line output is achieved the same.  If you haven't seen that one already, take a look at it here.

I will warn as I did on that first post.  SQL Server is used to store and manage the data, not to make it pretty. There are many very clever things you can do to manipulate your output, but you've got to be wary of the performance implications. Here's a little information from MSFT on the same thing.  See the the 'Logic separation' section, about keeping the business logic separate from the data manipulation.


Wednesday, January 28, 2015

SQL Server -- Daily DBA Checklist

" If you were running a DB area - What key items would you check / monitor every morning? "

I received that question from one of my customers recently.  A very good question, in my opinion, and one that should be asked of any potential DBA candidate.   

Best case, the DBA would have automated checks in place that run 24/7, proactively notifying, or alerting of any problems BEFORE they occur.  There are many different was to define these type of alerts - SQL Server Agent, SMO, Windows, WMI, and more.  Regardless, if an automated routine is in place, the daily DBA checklist becomes fairly minimal.  One cannot, however, just assume the alerts are running… and the checklist still exists.  I've provided three different groups of checks.  

Group 1    
This 1st group must be done every day.  Each of these items are perfectly alert-able, but the alerts may not be setup yet, so I suggest that each of these checks must occur daily, via automated routine or manually: 
        
          Backups
               a. All backups completed successfully?
               b. Capacity concerns on backup drive?
               c. Backup durations very long?
         Security
               a. Review SQL Server log AND Windows Security Event Log
        Capacity
               a. Data and Log file space -- file sizes, growth?
               b. Disk space - ALL drives -- available disk space?
        
        OS Event Logs/SQL Server Logs
               a. Review for any abnormal events
        Scheduled jobs - (Agent, Windows Scheduled tasks, etc.)
               a. Confirm all scheduled jobs ran successfully
               b. Even check job step duration, make sure nothing is taking too long


Group 2
This 2nd group is also extremely valuable, but it only provides an immediate state, UNLESS the DBA has setup an automated collection.  This can be done using the Data Collector, to capture statistics for Server Activity, Disk Usage and Query Statistics.  These collections can be run every day, creating moving metrics that grow and change as your business activity does.  When certain events or conditions are detected, the DBA can be notified/alerted.  This is not available out of the box with SQL Server.  It’s got to be setup, and managed regularly (see here).  If it is not in place, the checking should still occur, at least on a weekly basis.  Even just the current state is very valuable.

               Review blocking issues
                   a. SQL Server performance counters
              Review table/index fragmentation statistics
                   a. See my query here, using sys.dm_db_index_physical_stats, sys.indexes
              Review performance statistics
                   a. See sp_blitz from Brent Ozar’s team


Group 3
Lastly, this check should be done at least once monthly.  It can be completely automated, but given that it only occurs monthly, the manual invocation is acceptable, too.  Don't just look at the success/fail status of the backup job.  You've got to restore a .bak file and confirm the integrity of the data.  The last thing you want is to be doing an audit, and find your .bak files are unusable.

Restore a backup at least weekly, to validate backup solution

One last thing that I would note is that if the DBA is logging ALL changes that are made everywhere, as is recommended, then he/she should take time to review these metrics on a regular basis, too.  One server or 100, one DBA or a Team -- it's just a very good thing to keep an eye on.

Wednesday, January 21, 2015

When was your SQL Server database last restored?

Just a real quick post... I took on a new project very recently, and I was doing an assessment of their farm.  Last DBCC's, last backups... even last restores.   I had several different statements, but I returned multiple restore dates, when the database data and log file were restored in separate operations.  This statement takes that into account, and just gives you back a single entry, for the most recent restore date for your databases.  It also tells you from what file they were restored.  Check it out.  Let me know what you think.

  /*  
When was your database last restored? 
From what file?                                                              */

     WITH LastRestored AS
     (
    SELECT
            rh.destination_database_name [DatabaseName],
            rh.restore_date [Restored],
            bmf.physical_device_name [SourceFile],
            RowNum = ROW_NUMBER() OVER (PARTITION BY bs.database_name 
                  ORDER BY rh.restore_date DESC )
     FROM
           msdb..restorehistory rh INNER JOIN msdb..backupset bs 
               ON rh.backup_set_id = bs.backup_set_id INNER JOIN msdb..backupmediafamily bmf 
   ON bs.media_set_id = bmf.media_set_id
     )
     SELECT DatabaseName,Restored,SourceFile
     FROM LastRestored
     WHERE RowNum = 1


Your results will look a little something like this:

   DatabaseName                Restored                               SourceFile
   AdventureWorks2012      2015-01-20 21:59:41.130     C:\Backups\AdventureWorks2012_Backup.bak
   ReportServer              2015-01-20 11:39:33.853     C:\SSRS\ReportServerLog.bak
   ReportServerTempDB      2015-01-20 11:39:43.433     C:\SSRS\ReportServerTempDBLog.bak


Here are a couple of references with greater detail on the tables I am targeting:

RestoreHistory                 https://msdn.microsoft.com/en-us/library/ms187408(v=sql.110).aspx
BackupSet                       https://msdn.microsoft.com/en-us/library/ms186299.aspx
BackupMediaFamily     https://msdn.microsoft.com/en-us/library/ms190284(v=sql.110).aspx


Friday, January 2, 2015

Find all user-created objects in your system databases

System databases are for system objects.  Pretty simple.  If user objects are created within the system databases, then we also need to include these databases in our DR plans.  For this and countless other reasons, it really is not a good practice to allow user-defined objects within your SQL Server system databases.

In this post I've just given a couple of quick statements you can use to identify user created objects in any of your system databases.


/*  Use this to find any user-defined objects in the system databases, if exists.  
    As-is, it targets the master database, but works the same in any system db.
To target model or msdb, change the database name in the USE line.            */

USE master;  -- << use master, model or msdb
SELECT
o.name [ObjectName],
        s.name [Schema/Owner],
o.type_desc [ObjectType]
FROM
sys.all_objects o INNER JOIN sys.schemas s
          ON o.schema_id = s.schema_id LEFT OUTER JOIN sys.database_principals po
            ON o.principal_id = po.principal_id LEFT OUTER JOIN sys.database_principals ps
              ON s.principal_id = ps.principal_ID
WHERE
o.is_ms_shipped <> 1; -- 'is_ms_shipped' means it was shipped by MSFT on the cd.  
      -- If is_ms_shipped = 0, that means it is user-created.


In cases of upgraded databases, or database diagramming, I have heard that is_ms_shipped is not always 100% reliable.  I have never actually seen that, but to be safe, you could use this approach, which is a combination of is_ms_shipped and the 'sys' schema name.

SELECT * FROM sys.objects 
WHERE SCHEMA_NAME(schema_id) <> 'sys'  
AND is_ms_shipped = 0  
AND parent_object_id NOT IN (
SELECT object_id  
FROM sys.objects  
WHERE SCHEMA_NAME(schema_id) = 'sys'  
        OR is_ms_shipped = 1); 


These are additional references to the different system catalog views:



Monday, October 13, 2014

More SQL Server Aggregate functions

I mentioned that I would try to get back in here with some more examples using SQL Server's Aggregate functions. I think this is a good one. One of the requests I used to get again and again, was the current net position for all symbols traded on the Equity exchanges. The Ops desk (the Team supporting the traders) needed to know if positions were open for any symbol across these exchanges:    ISLD, BRUT, ARCA, CHX, NSDQ, NYSE.

To handle that, I just created this procedure which was run on the back-end, and would alert them if an open position was found.

  CREATE PROCEDURE dbo.usp_NetPosBySymbol
  AS
  SET NOCOUNT ON
  /*
   Returns the net position by symbol, across the equity exchanges, if exists.
   EXEC dbo.usp_NetPosBySymbol 

  Auth:  Me
  Date:  10/13/2014
  */
  BEGIN
        -- use this method to avoid an IN list in the WHERE clause
DECLARE @Exchanges TABLE (ExchangeName VARCHAR(15))
INSERT @Exchanges (ExchangeName)
VALUES 
('ARCA'),
('BRUT'),
('CHX'),
('DNET'),
('ISLD'),
('NSDQ'),
('NYSE');

IF EXISTS(
SELECT buys-sells AS Difference
FROM (
SELECT Symbol,SUM(Quantity) [buys] 
FROM dbo.Orders o
WHERE Side = 'B' 
         AND EXISTS(
                    SELECT 1 FROM @Exchanges e WHERE e.ExchangeName = o.Exchange)
GROUP BY Symbol) buys JOIN
(
SELECT Symbol,SUM(Quantity) [sells]
FROM dbo.Orders o 
WHERE Side = 'S' 
AND EXISTS(
                     SELECT 1 FROM @Exchanges e WHERE e.ExchangeName = o.Exchange)
GROUP BY Symbol) sells
         ON buys.Symbol = sells.Symbol
WHERE 
  buys <> sells)

BEGIN
SELECT buys.Symbol,Buys,Sells,buys-sells AS Difference
FROM(
SELECT Symbol,SUM(Quantity) [buys] 
FROM dbo.Orders o
WHERE Side = 'B' 
           AND EXISTS(
                      SELECT 1 FROM @Exchanges e WHERE e.ExchangeName = o.Exchange)
GROUP BY Symbol) buys JOIN
(
SELECT Symbol,SUM(Quantity) [sells]
FROM dbo.Orders o 
WHERE Side = 'S' 
             AND EXISTS(
                       SELECT 1 FROM @Exchanges e WHERE e.ExchangeName = o.Exchange)
GROUP BY Symbol) sells
              ON buys.Symbol = sells.Symbol
WHERE 
                   buys <> sells
ORDER BY 
                   buys.Symbol
       END
    END

  SET NOCOUNT OFF
  GO

We're still using the Orders data that we wrote in this post, SQL Aggregate functions, and these are our results:

   Symbol   Buys  Sells  Difference
   BEAS      55    100     -45
   YHOO      50    105     -55

That is just a simple example using SUM.  We first do an existence check, and then we return the net position back to the front end, if exists.

See this for more information, and for a couple more examples using the SUM function:
     http://msdn.microsoft.com/en-us/library/ms187810.aspx

SQL Aggregate functions for count & quantity traded

You're managing a lot of trading data, and you've been asked to provide some statistics back to the trading desks. There are numerous different types of statistics that you could provide, all using SQL Server aggregate functions such as COUNT, SUM, AVG, etc. Today I am going to show a very simple example for reporting how many buys and sells they are trading on each symbol.

First, we need an Orders table that all of trades are written to.  Very simple design, like this:

CREATE TABLE dbo.Orders (
OrderID INT IDENTITY(1,1),
TraderID CHAR (12) NOT NULL,
Exchange CHAR (8) NOT NULL,
Symbol CHAR (32) NOT NULL,
Side CHAR (1) NOT NULL,
Quantity BIGINT NOT NULL ,
Price DECIMAL(18, 8) NOT NULL ,
OrderDate DATETIME NOT NULL 
) ON YourDB_Data
GO

I should note, MUCH better practices would be a numeric identifier for Exchange, Symbol and even Side. But... then I'd have to do all kinds of JOINs to get the data back to you meaningfully. For this example, we can ignore the performance impediments of character strings vs integers.  ;-)

For the insert into Orders, I am only going to use a small chunk of orders by only one trader, John Doe.

-- load some orders
SET IDENTITY_INSERT Orders ON
INSERT dbo.Orders (OrderID,TraderID,Exchange,Symbol,Side,Quantity,Price,OrderDate)
VALUES
(1,10,'NYSE','AAPL','B',55,12.45,'10/13/2012 09:30'),
(2,10,'NSDQ','YHOO','B',50,61.75,'10/13/2012 10:30'),
(3,10,'CME','AAPL','B',5,17.50,'10/13/2012 09:00'),
(4,10,'NYSE','DDM9','S',5,1.75,'10/13/2012 08:30'),
(5,10,'NSDQ','ABS','B',3,66.502,'10/13/2012 09:35'),
(61,10,'NYSE','BEAS','B',55,1.75,'10/13/2012 12:20'),
(7,10,'NSDQ','BEAS','S',100,1.025,'10/13/2012 12:55'),
(8,10,'CME','CAG','B',10,11.53,'10/13/2012 13:30'),
(9,10,'CSX','YHOO','S',10,17.705,'10/13/2012 16:55'), 
(10,10,'NYSE','YHOO','S',50,10.45,'10/13/2012 10:30'),
(11,10,'NSDQ','YHOO','S',55,60.75,'10/13/2012 11:30'),
(12,10,'CME','YHOO','S',5,19.50,'10/13/2012 10:00');
SET IDENTITY_INSERT Orders OFF

Ok. We've got some order data for trader John Doe. With the query below, you will return a count for how many orders he's traded, and how much quantity was for buys vs sells. Basically, counts and quantities for each trader, by symbol and side ('side' is trading speak for buy or sell).

  DECLARE 
      @OrderDate DATE = '10/13/2012',
@TraderID INT =  10

  -- collect the trade count (#) and Qty for each trader, by symbol
  SELECT 
CONVERT(VARCHAR(10),o.OrderDate,101)  [Date],
t.TraderName,
o.Symbol,
COUNT(*) [#Trades],
LTRIM(RTRIM(LEFT(CONVERT(CHAR(16),CAST(SUM(CASE WHEN o.Side = 'b'
          THEN o.Quantity ELSE 0 END) AS MONEY),1),13))) [BuyQty],
LTRIM(RTRIM(LEFT(CONVERT(CHAR(16),CAST(SUM(CASE WHEN o.Side = 's'
          THEN o.Quantity ELSE 0 END) AS MONEY),1),13))) [SellQty]
  FROM 
dbo.Orders o INNER JOIN dbo.Traders t
         ON o.TraderID = t.TraderID
  WHERE 
CONVERT(VARCHAR(10),o.OrderDate,101) = @OrderDate
AND o.TraderID = @TraderID
  GROUP BY 
CONVERT(VARCHAR(10),o.OrderDate,101),
t.TraderName,
o.Symbol
  ORDER BY
CONVERT(VARCHAR(10),o.OrderDate,101),
o.Symbol

The results:

     OrderDate   Trader   Symbol   #Trades  BuyQty   SellQty
     10/13/2012  John Doe   AAPL     2      60        0
     10/13/2012  John Doe    ABS     1       3        0
     10/13/2012  John Doe   BEAS     2      55      100
     10/13/2012  John Doe    CAG     1      10        0
     10/13/2012  John Doe   DDM9     1       0        5
     10/13/2012  John Doe   YHOO     5      50      120

I added these two statements after the one above just to help me confirm that it's accurate. Looking at the raw and the agg data side by side makes it easier to validate:

    SELECT COUNT(*) FROM dbo.Orders WHERE TraderID = 10 AND Symbol = 'AAPL'
    SELECT * FROM dbo.Orders WHERE TraderID = 10 AND Symbol = 'ABS' AND Side = 'b'

Like I said, there are many different ways to report the data using SQL Server's aggregate functions. This is just one example. I'll try to come back soon with more. Until then, take a look at this, for more detail:


Calculate running totals in SQL Server

You want to show details for the individual orders traded (or transactions), but you also need to show the total orders traded by each trader, in the same result set. This means you need to calculate running totals. There are numerous ways to calculate running totals with tSQL, but you've got to be cautious, or your performance could be less than acceptable. In this post, I'm giving you just a quick example for calculating the running total by using a correlated sub query... and we're going to return it for each trader, by date.

-- first let's create a table for our traders
IF OBJECT_ID('tempdb..#traders') <> 0
DROP TABLE #traders;
CREATE TABLE #Traders (
    TraderID INT IDENTITY(1,1),
    TraderName VARCHAR(45)
 )
SET IDENTITY_INSERT #Traders ON
INSERT #Traders (TraderID,TraderName)
VALUES (10, 'John Doe'),
    (11, 'Jane Smith');
SET IDENTITY_INSERT #Traders OFF;

-- create our orders table 
CREATE TABLE #orders (
OrderID INT IDENTITY(1,1), 
OrderDate DATETIME, 
TraderID INT,
Quantity INT,
RunningTotal INT NULL )

-- populate #orders
SET IDENTITY_INSERT #orders ON
INSERT #orders (OrderID,OrderDate,TraderID,Quantity)
VALUES (1,'10/12/2014 09:00', 10, 100),
            (2, '10/12/2014 11:00', 10, 200),
           (3, '10/12/2014 12:00', 10, 300),
      (4, '10/12/2014 14:00', 11, 400),
           (5, '10/12/2014 14:30', 11, 500),
          (6,'10/13/2014 09:00', 10, 100),
          (7, '10/13/2014 11:00', 10, 90),
          (8, '10/13/2014 12:00', 11, 300),
          (9, '10/13/2014 14:00', 11, 4500),
        (10, '10/13/2014 14:30', 11, 500);

-- take a look at the orders data that you just loaded
SELECT * FROM #orders

   OrderID   OrderDate             TraderID Quantity RunningTotal
     1    2014-10-12 09:00:00.000   10       100       NULL
     2    2014-10-12 11:00:00.000   10       200       NULL
     3    2014-10-12 12:00:00.000   10       300       NULL
     4    2014-10-12 14:00:00.000   11       400       NULL 
     5    2014-10-12 14:30:00.000   11       500       NULL
     6    2014-10-13 09:00:00.000   10       100       NULL
   .............................
   ..................

Now we'll use a correlated subquery to bring it back out for each trader, and each order date.

   -- bring back the running total
   SELECT
          CONVERT(CHAR(10),o.OrderDate,101) [OrderDate],
          t.TraderName,
          o.Quantity,
         (
              SELECT SUM(Quantity) FROM #orders 
              WHERE OrderID <= O.OrderID 
              AND CONVERT(CHAR(10),OrderDate,101) = CONVERT(CHAR(10),o.OrderDate,101)
              AND TraderID = o.TraderID
         ) [Running Total] 
    FROM
          #orders o INNER JOIN #Traders t
          ON o.TraderID = t.TraderID
    ORDER BY
       OrderDate,
       t.TraderName


Here's your full result-set :

    OrderDate    TraderName   Quantity  RunningTotal
    10/12/2014 Jane Smith 400 400
    10/12/2014 Jane Smith 500 900
    10/12/2014 John Doe 100 100
    10/12/2014 John Doe 200 300
    10/12/2014 John Doe 300 600
    10/13/2014 Jane Smith 300 300
    10/13/2014 Jane Smith 4500 4800
    10/13/2014 Jane Smith 500 5300
    10/13/2014 John Doe 100 100
    10/13/2014 John Doe 90 190


That's it!  As I said, there are numerous ways to calculate running totals. There are new functions with the newer releases, such as the OVER clause that became available in v2005.  Here is a quick example using the OVER clause:

   -- using the OVER clause
   SELECT 
      OrderDate,
      Quantity,
      SUM(Quantity) OVER (ORDER BY o.OrderID) [RunningTotal]
   FROM 
      #orders o
   ORDER BY 
      o.OrderID;


Here is a little more information on the correlated subquery:
 http://technet.microsoft.com/en-us/library/ms187638(v=sql.105).aspx

And take a look at this for more detail on the OVER clause:
  http://msdn.microsoft.com/en-us/library/ms189461(v=sql.105).aspx