Author: way0utwest

  • Computed Columns and Divide by Zero

    Edit: This was a poor example of using the divide by zero handling. I was trying to alter something I’d done in the past and this didn’t work well. I will rewrite this soon with a better example.

    I have a few posts on computer columns, the basics of computed columns, using CASE in a computed column, and UDFs in computed columns, but there was another use that someone pointed out to me recently: catching divide by zero errors.

    Suppose you have a column that is determining a percentage of profit for some sales. I’ll create a table and include some values:

    CREATE TABLE MySales
    ( salesid int , Product VARCHAR(20) , Cost numeric(10,4) , Price numeric(10,4) , profit AS (price - cost)/ cost
    ) GO INSERT MySales SELECT 1, 'Bike', 150.45, 180.99
    INSERT MySales SELECT 1, 'Shoes', 23.55, 45.99
    INSERT MySales SELECT 1, 'Soda', 0.25, .99

    If I look at the values in the table, I get back these items:

    /*------------------------
    SELECT Product
    , Cost
    , Profit
     FROM MySales
    ------------------------*/
    Product              Cost                                    Profit
    -------------------- --------------------------------------- ---------------------------------------
    Bike                 150.4500                                0.202991026919242
    Shoes                23.5500                                 0.952866242038216
    Soda                 0.2500                                  2.960000000000000

    Things work great, and everything seems to be fine. However, what if we get some free products that we can sell, say something we made out of scraps, or were given to us as a gift with essentially no cost?

    INSERT MySales SELECT 1, 'Keychain', 0, .75

    It works. However if I select data:

    SELECT Product
    , Cost
    , Profit
     FROM MySales

    I get this:

    Product              Cost                                    Profit
    -------------------- --------------------------------------- ---------------------------------------
    Bike                 150.4500                                0.202991026919242
    Shoes                23.5500                                 0.952866242038216
    Soda                 0.2500                                  2.960000000000000
    Msg 8134, Level 16, State 1, Line 2
    Divide by zero error encountered.

    The computation occurs on query, and it doesn’t work well.

    However we can fix this with a function in our computed column. There are a couple choices here. I can use ISNULL and a CASE to build a formula, I could use COALESCE, or I could use NULLIF.

    NULLIF returns null if two values are equal. If a NULL is acceptable in my table, I could use that. I could end up with:

    CREATE TABLE MySales
    ( salesid int , Product VARCHAR(20) , Cost numeric(10,4) , Price numeric(10,4) , profit AS (price - cost) / NULLIF(cost ,0) ) GO INSERT MySales SELECT 1, 'Bike', 150.45, 180.99
    INSERT MySales SELECT 1, 'Shoes', 23.55, 45.99
    INSERT MySales SELECT 1, 'Soda', 0.25, .99
    INSERT MySales SELECT 1, 'Keychain', 0, .75
    GO SELECT Product
    , Profit
     FROM MySales

    and get back:

    Product              Profit

    ——————– —————————————

    Bike                 0.202991026919242

    Shoes                0.952866242038216

    Soda                 2.960000000000000

    Keychain             NULL

    NULL is a good marker here, but your application needs to handle this and let the user know there is an issue.

    You could use COALESCE, which returns the first non-null value. I could see any of these as being a valid formula:

    , profit AS (price - cost) / COALESCE(cost ,0) 

    which uses “0” profit margin as a marker, or even something like:

    , profit AS (price - cost) / COALESCE(cost , 999)

    which uses 999. Lots of times we’ve used a large, nonsense number as a marker that lets someone know there is a strange value here.

    If we converted this to a varchar, it’s possible that we could even use words in there, but I wouldn’t recommend that as downstream uses of this column might involve other calculations.

    That’s a short look at how a computed column can solve an easy, common issue: divide by zero.

    Credit to Atif Shehzad, whose article I found while researching this.

  • T-SQL Tuesday Topics – Febuary 2012

    Updated again.

    I was looking for a static list of all the T-SQL Tuesday topics and couldn’t find one. The domain moves around to the current hosting blog, so when it was my turn to host it, I made a list just so I could reference what was out there.

    After a few more months, I decided to update my list with the latest topics. That will give me the chance to plan for my own future hosting of the party if Adam will have me again.

    I’ll keep updating, mainly so I can keep track. And since I’ve got #027, look for a new topic soon.

  • Insider Security Threats

    Monitoring is the key to really good security.

    Are you worried about internal users at your company compromising your data security? I’d hope that you are at least a little worried, after all, we find out regularly that people we thought we knew acted in a surprising manner, or did something inappropriate that we hadn’t expected. It’s not always malicious or intentional, but even when it’s accidental, our security gets compromised and we receive some of the blame.

    Security is a hard process to implement, especially over time. Too much security implies too little trust, and as humans, we want to trust each other. As we work together, and build trust, we tend to let security lapse a bit. As organizations grow, evolve, and change people around, we introduce security loopholes from mis-configurations, poor architectural foundations, or simple mistakes like failing to remove someone from a security role.

    This piece talks a bit about the internal security threats you face, while ranting a bit about the term “insider threat”. The threats you face from external attackers are different from those you face from internal employees. However in each case, there’s one thing that’s important for getting close to a secure environment: monitoring.

    We can’t determine every type of attack vector, protect every system or database completely, but we can monitor for issues and be prepared to react when a problem occurs. The auditing capabilities of SQL Server have grown tremendously with the eventing enhancements to the platform, and I urge you to spend some time learning about Extended Events, which give you even more of an insight into what is happening on your server.

    Steve Jones


    The Voice of the DBA Podcasts

    We are having some technical issues with our hosting provider and are working to get the podcasts back online soon. Our apologies for the delays.

  • Going Solo

    If you want to go into consulting, read this book.

    This editorial was originally published on Mar 20, 2007. It is being republished as Steve Jones is on vacation. 

    Are you ready to leave the corporate world and become a consultant? It’s a tempting thought and probably one that everyone in corporate America considers at one time or another. Especially those of us in technology who have skills that can easily be used to help some other company.

    Here are 10 reasons not to go into business for yourself, which is an interesting list. It’s from someone who evangelizes the benefits, joys, and methods of escaping the corporate cubicle. If you’re seriously considering becoming a consultant, starting your own business, or going out in any way on your own, I’d recommend her site as a place to learn some things.

    Coming from someone that helped start this site and has worked for it for 3 years this might sound funny. I don’t really like being in business for myself. I know, I’ve been successful, had a good life, let you all know about large parts of it, but the truth is I didn’t love working for myself. If not for Andy and Brian supporting me, I’m not sure I’d have done it.

    Working for yourself, even when you’re successful, isn’t this easy, amazing job. It’s a hassle and it’s hard to worry about the different parts of a business. I’m a writer and a techie. As much as I pay attention to marketing, sales, and other groups, I don’t want to do their jobs. I have an opinion and am happy to express it, but I don’t want to get more involved than that.

    I’m not really advocating one way or the other that you should or shouldn’t start a business or stay in a cubicle. Rather I want to caution you that it’s not as easy as tuning queries. The marketing, accounting, and collections will be as much as the job as the T-SQL.

    Read about other’s experiences, think hard about it, and consider all the parts of the job that you’ll need to do. There’s always more than you think and remember that just as with a new job in corporate America.

    The grass is not always greener.