{"id":25,"date":"2020-06-19T22:06:50","date_gmt":"2020-06-19T22:06:50","guid":{"rendered":"https:\/\/www.transcendentsoftware.com\/blog\/?p=25"},"modified":"2020-07-16T14:29:07","modified_gmt":"2020-07-16T14:29:07","slug":"sql-query-divide-by-zero-alternative","status":"publish","type":"post","link":"https:\/\/transcendentsoftware.com\/blog\/sql-query-divide-by-zero-alternative\/","title":{"rendered":"SQL Query Divide By Zero Alternative"},"content":{"rendered":"\n<p>We&#8217;ve all been there. In a haste to write a quick SQL query that turns into a production query we take one value as a numerator and another as a denominator and put that division slash between them and move on. It works great, except only to find when we show the results off in production to our stakeholders the query crashes with a message like this:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"234\" height=\"18\" src=\"https:\/\/www.transcendentsoftware.com\/blog\/wp-content\/uploads\/2020\/06\/image-7.png\" alt=\"\" class=\"wp-image-27\"\/><\/figure>\n\n\n\n<p>We then scramble to figure out where and why, all the while the stakeholder gets impatient while their super smart person looks like a fool. The sweat starts to bead up, the nervous chuckles ensue. Rapid typing and scrolling, executing the query over and over again fixing every little possible problem. Right? Then you utter, &#8220;It worked when I tested it.&#8221;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">A hasty SQL solution<\/h2>\n\n\n\n<p>Since we&#8217;ve all been there, we know how easy it is to fix the query to not divide by zero. We have all used <strong>IF ~~~<\/strong> <strong>THEN<\/strong>, <strong>CASE WHEN ~~~ THEN<\/strong>, <strong>ISNULL<\/strong>, <strong>IFNULL<\/strong>,<strong> NULLIF <\/strong>or whatever function for whatever <a href=\"https:\/\/en.wikipedia.org\/wiki\/Relational_database#RDBMS\" target=\"_blank\" aria-label=\"undefined (opens in a new tab)\" rel=\"noreferrer noopener\">RDBMS (Relational Database Management System)<\/a> is our flavor of choice or any combination of these functions as well. To get the math close enough, we have probably just slapped some parenthesis around the denominator and added .00000001 to it just to get the query to return a value close enough. <\/p>\n\n\n\n<p>Don&#8217;t laugh! You did it, I know you did.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">A better SQL solution<\/h2>\n\n\n\n<p>Well, many years ago it occurred to me to quit getting caught with my pants down and just build a function to handle this for those embarrassing moments. That little <a href=\"https:\/\/en.wikipedia.org\/wiki\/User-defined_function\" target=\"_blank\" aria-label=\"undefined (opens in a new tab)\" rel=\"noreferrer noopener\">UDF (User-Defined Function)<\/a> has come in quite handy over the years. I typically work with SQL Server, but there are many ways to write this across any RDBMS. Here is the Transact-SQL:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CREATE FUNCTION &#91;dbo].&#91;SafeDivide]\n(\n\t@Numerator FLOAT,\n\t@Denominator FLOAT,\n\t@IfDivideByZeroDefault FLOAT\n)\nRETURNS FLOAT\nAS\nBEGIN\n\tRETURN (\n\t\tCASE WHEN @Denominator = 0 THEN \n\t\t\t@IfDivideByZeroDefault\n\t\tELSE \n\t\t\t@Numerator \/ @Denominator\n\t\tEND\n\t)\nEND<\/code><\/pre>\n\n\n\n<p>That&#8217;s it! That simple little function has saved me time and embarrassment over the years. Here is how you use it:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"332\" height=\"277\" src=\"https:\/\/www.transcendentsoftware.com\/blog\/wp-content\/uploads\/2020\/06\/image-10.png\" alt=\"\" class=\"wp-image-30\" srcset=\"https:\/\/transcendentsoftware.com\/blog\/wp-content\/uploads\/2020\/06\/image-10.png 332w, https:\/\/transcendentsoftware.com\/blog\/wp-content\/uploads\/2020\/06\/image-10-300x250.png 300w\" sizes=\"auto, (max-width: 332px) 100vw, 332px\" \/><\/figure>\n\n\n\n<p>You&#8217;ll see the first query returns the division result as it is dividing 100 by 2, which is 50. The second query is dividing 100 by 0, which is not possible, so it uses the default value of 777 as the result. Typically for the default value I choose 0, but there are some cases you might want to use 1 or 100 if you are working with percents. It just depends on the use case.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">A happy SQL ending<\/h2>\n\n\n\n<p>As you can see, this simple UDF will save a lot of slow starts to meetings with stakeholders when your awesome query backfires with production data or the first time they ask you to change the date range outside the one you tested with. <\/p>\n\n\n\n<p>I hope it helps you as much as it has me over the years and cuts down on your monthly antiperspirant bill. Happy coding!<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<p>We use SQL all the time when we develop software solutions. Read about our <a aria-label=\"undefined (opens in a new tab)\" href=\"https:\/\/transcendentsoftware.com\/Services\/SoftwareDevelopment\" target=\"_blank\" rel=\"noreferrer noopener\">Software Development service<\/a> and read a <a aria-label=\"undefined (opens in a new tab)\" href=\"https:\/\/transcendentsoftware.com\/Resources\/SoftwareDevelopment\" target=\"_blank\" rel=\"noreferrer noopener\">case study<\/a> about how we were able to help a small business with our services.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We&#8217;ve all been there. In a haste to write a quick SQL query that turns into a production query we take one value as a numerator and another as a denominator and put that division slash between them and move on. It works great, except only to find when we show the results off in [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":26,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[21,5,6,18,19,10,17,20],"tags":[],"class_list":["post-25","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-azure-sql","category-databases","category-mysql","category-oracle","category-rdms","category-software-development","category-sql-server","category-transact-sql"],"jetpack_publicize_connections":[],"_links":{"self":[{"href":"https:\/\/transcendentsoftware.com\/blog\/wp-json\/wp\/v2\/posts\/25","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/transcendentsoftware.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/transcendentsoftware.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/transcendentsoftware.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/transcendentsoftware.com\/blog\/wp-json\/wp\/v2\/comments?post=25"}],"version-history":[{"count":0,"href":"https:\/\/transcendentsoftware.com\/blog\/wp-json\/wp\/v2\/posts\/25\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/transcendentsoftware.com\/blog\/wp-json\/wp\/v2\/media\/26"}],"wp:attachment":[{"href":"https:\/\/transcendentsoftware.com\/blog\/wp-json\/wp\/v2\/media?parent=25"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/transcendentsoftware.com\/blog\/wp-json\/wp\/v2\/categories?post=25"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/transcendentsoftware.com\/blog\/wp-json\/wp\/v2\/tags?post=25"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}