{"id":711,"date":"2024-12-07T18:46:09","date_gmt":"2024-12-07T11:46:09","guid":{"rendered":"https:\/\/www.pgtutorial.com\/?page_id=711"},"modified":"2025-01-03T16:16:08","modified_gmt":"2025-01-03T09:16:08","slug":"postgresql-nullif","status":"publish","type":"page","link":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/","title":{"rendered":"PostgreSQL NULLIF Function"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the PostgreSQL <code>NULLIF<\/code> function to compare two expressions and return <code>NULL<\/code> if they are equal.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='getting-started-with-the-postgresql-nullif-function'>Getting started with the PostgreSQL NULLIF function <a href=\"#getting-started-with-the-postgresql-nullif-function\" class=\"anchor\" id=\"getting-started-with-the-postgresql-nullif-function\" title=\"Anchor for Getting started with the PostgreSQL NULLIF function\">#<\/a><\/h2>\n\n\n\n<p>In PostgreSQL, the <code>NULLIF<\/code> function compares two expressions and returns <code><a href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-not-null\/\">NULL<\/a><\/code> if they are equal. Otherwise, it returns the result of the first expression.<\/p>\n\n\n\n<p>Here&#8217;s the syntax of the <code>NULLIF<\/code> function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\">NULLIF(expression1, expression2)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>If <code>expression1<\/code> equals <code>expression2<\/code>, the function returns <code>NULL<\/code>. Otherwise, it returns <code>expression1<\/code>.<\/p>\n\n\n\n<p>Note that the <code>NULLIF<\/code> function compares the results of two expressions using the equal operator (<code>=<\/code>). This means that the results of both expressions must be comparable. In other words, they must have a compatible data type for comparison.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='basic-postgresql-nullif-function-examples'>Basic PostgreSQL NULLIF function examples <a href=\"#basic-postgresql-nullif-function-examples\" class=\"anchor\" id=\"basic-postgresql-nullif-function-examples\" title=\"Anchor for Basic PostgreSQL NULLIF function examples\">#<\/a><\/h2>\n\n\n\n<p>The following example returns <code>NULL<\/code> because both values are equal:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span> NULLIF(<span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">0<\/span>) result;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=nullif&amp;q=U0VMRUNUIE5VTExJRigwLCAwKSByZXN1bHQ7\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"> result\n--------\n   <span class=\"hljs-keyword\">NULL<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The following example returns 1 because 1 is not equal to 0:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span> NULLIF(<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">0<\/span>) result;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=nullif&amp;q=U0VMRUNUIE5VTExJRigxLCAwKSByZXN1bHQ7\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\"> result\n--------\n      1<\/code><\/span><\/pre>\n\n\n<p>The following example always returns <code>NULL<\/code> because <code>NULL<\/code> is not equal to <code>NULL<\/code>.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span> NULLIF(<span class=\"hljs-keyword\">NULL<\/span>, <span class=\"hljs-keyword\">NULL<\/span>) result;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=nullif&amp;q=U0VMRUNUIE5VTExJRihOVUxMLCBOVUxMKSByZXN1bHQ7\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"> result\n--------\n <span class=\"hljs-keyword\">NULL<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The following example returns when comparing a string &#8216;1&#8217; with the number 1:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span> NULLIF(<span class=\"hljs-string\">'1'<\/span> , <span class=\"hljs-number\">1<\/span>) result;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=nullif&amp;q=U0VMRUNUIE5VTExJRignMScsIDEpOw%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"> result\n--------\n   <span class=\"hljs-keyword\">NULL<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>It returns the same result as you compare the &#8216;1&#8217; and 1 using the equal operator:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">SELECT<\/span> <span class=\"hljs-string\">'1'<\/span> = <span class=\"hljs-number\">1<\/span> result;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=nullif&amp;q=U0VMRUNUICcxJyA9IDEgcmVzdWx0Ow%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\"> result\n--------\n t<\/code><\/span><\/pre>\n\n\n<p>The &#8216;1&#8217; is equal 1, so the &#8216;1&#8217;= 1 returns <code>true<\/code>. The <code>NULLIF('1', 1)<\/code> returns <code>NULL<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='using-postgresql-nullif-function-to-replace-a-value-with-null'>Using PostgreSQL NULLIF function to replace a value with NULL <a href=\"#using-postgresql-nullif-function-to-replace-a-value-with-null\" class=\"anchor\" id=\"using-postgresql-nullif-function-to-replace-a-value-with-null\" title=\"Anchor for Using PostgreSQL NULLIF function to replace a value with NULL\">#<\/a><\/h2>\n\n\n\n<p>The <code>NULLIF<\/code> function can help replace a value with <code>NULL<\/code>, especially for data cleansing.<\/p>\n\n\n\n<p>In the application, users may enter an empty string (<code>''<\/code>) or <code>N\/A <\/code>into a column into a nullable column.<\/p>\n\n\n\n<p>To fix this issue, you need to validate the data at the application layer and clean up data at the database level; you can use the <code>NULLIF<\/code> function to replace these invalid values with <code>NULL<\/code>.<\/p>\n\n\n\n<p>Suppose you have the following <code>contacts<\/code> table that store contact id, name, phone and email:<\/p>\n\n\n\n<details class=\"wp-block-details is-layout-flow wp-block-details-is-layout-flow\"><summary>SQL Script for creating the contact table and insert data into the table<\/summary><pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">CREATE<\/span> <span class=\"hljs-keyword\">TABLE<\/span> contacts(\n    contact_id <span class=\"hljs-type\">INT<\/span> <span class=\"hljs-keyword\">GENERATED<\/span> <span class=\"hljs-keyword\">ALWAYS<\/span> <span class=\"hljs-keyword\">AS<\/span> <span class=\"hljs-keyword\">IDENTITY<\/span> <span class=\"hljs-keyword\">PRIMARY KEY<\/span>,\n    <span class=\"hljs-type\">name<\/span> <span class=\"hljs-type\">VARCHAR<\/span>(<span class=\"hljs-number\">255<\/span>) <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-keyword\">NULL<\/span>,\n    phone <span class=\"hljs-type\">VARCHAR<\/span>(<span class=\"hljs-number\">25<\/span>),\n    email <span class=\"hljs-type\">VARCHAR<\/span>(<span class=\"hljs-number\">255<\/span>)\n);\n<span class=\"hljs-keyword\">INSERT<\/span> <span class=\"hljs-keyword\">INTO<\/span> contacts (<span class=\"hljs-type\">name<\/span>, phone, email) \n<span class=\"hljs-keyword\">VALUES<\/span>\n(<span class=\"hljs-string\">'Alice Johnson'<\/span>, <span class=\"hljs-string\">'N\/A'<\/span>, <span class=\"hljs-string\">''<\/span>),\n(<span class=\"hljs-string\">'Bob Smith'<\/span>, <span class=\"hljs-string\">'123-456-789'<\/span>, <span class=\"hljs-string\">'bob.smith@pgtutorial.com'<\/span>),\n(<span class=\"hljs-string\">'Carol White'<\/span>, <span class=\"hljs-string\">'123-456-788'<\/span>, <span class=\"hljs-string\">'carol.white@pgtutorial.com'<\/span>),\n(<span class=\"hljs-string\">'David Brown'<\/span>, <span class=\"hljs-string\">'123-456-787'<\/span>, <span class=\"hljs-string\">'david.brown@pgtutorial.com'<\/span> ),\n(<span class=\"hljs-string\">'Eve Black'<\/span>, <span class=\"hljs-string\">'123-456-786'<\/span>, <span class=\"hljs-string\">''<\/span>)\n<span class=\"hljs-keyword\">RETURNING<\/span> *;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre><\/details>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>contact_id<\/th><th>name<\/th><th>phone<\/th><th>email<\/th><\/tr><\/thead><tbody><tr><td>1<\/td><td>Alice Johnson<\/td><td>&#8216;N\/A&#8217;<\/td><td>&nbsp;&#8221;<\/td><\/tr><tr><td>2<\/td><td>Bob Smith<\/td><td>123-456-789<\/td><td>bob.smith@pgtutorial.com<\/td><\/tr><tr><td>3<\/td><td>Carol White<\/td><td>123-456-788<\/td><td>carol.white@pgtutorial.com<\/td><\/tr><tr><td>4<\/td><td>David Brown<\/td><td>123-456-787<\/td><td>david.brown@pgtutorial.com<\/td><\/tr><tr><td>5<\/td><td>Eve Black<\/td><td>123-456-786<\/td><td>&nbsp;&#8221;<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>We can use an <code>UPDATE<\/code> statement and <code>NULLIF<\/code> function to update the invalid values in the phone and email columns as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">UPDATE<\/span> contacts\n<span class=\"hljs-keyword\">SET<\/span>\n  phone = NULLIF(phone, <span class=\"hljs-string\">'N\/A'<\/span>),\n  email = NULLIF(email, <span class=\"hljs-string\">''<\/span>) \n<span class=\"hljs-keyword\">RETURNING<\/span> *;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?db=nullif&amp;q=VVBEQVRFIGNvbnRhY3RzIFNFVCBwaG9uZSA9IE5VTExJRihwaG9uZSwgJ04vQScpLCBlbWFpbCA9IE5VTExJRihlbWFpbCwgJycpIFJFVFVSTklORyAqOw%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"> contact_id |     name      |    phone    |           email\n------------+---------------+-------------+----------------------------\n          <span class=\"hljs-number\">1<\/span> | Alice Johnson | <span class=\"hljs-keyword\">NULL<\/span>        | <span class=\"hljs-keyword\">NULL<\/span>\n          <span class=\"hljs-number\">2<\/span> | Bob Smith     | <span class=\"hljs-number\">123<\/span><span class=\"hljs-number\">-456<\/span><span class=\"hljs-number\">-789<\/span> | bob.smith@pgtutorial.com\n          <span class=\"hljs-number\">3<\/span> | Carol White   | <span class=\"hljs-number\">123<\/span><span class=\"hljs-number\">-456<\/span><span class=\"hljs-number\">-788<\/span> | carol.white@pgtutorial.com\n          <span class=\"hljs-number\">4<\/span> | David Brown   | <span class=\"hljs-number\">123<\/span><span class=\"hljs-number\">-456<\/span><span class=\"hljs-number\">-787<\/span> | david.brown@pgtutorial.com\n          <span class=\"hljs-number\">5<\/span> | Eve Black     | <span class=\"hljs-number\">123<\/span><span class=\"hljs-number\">-456<\/span><span class=\"hljs-number\">-786<\/span> | <span class=\"hljs-keyword\">NULL<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='preventing-the-division-by-zero-error'>Preventing the division by zero error <a href=\"#preventing-the-division-by-zero-error\" class=\"anchor\" id=\"preventing-the-division-by-zero-error\" title=\"Anchor for Preventing the division by zero error\">#<\/a><\/h2>\n\n\n\n<p>The following statement retrieves the safety stock from the <code>products<\/code> table joins it with inventory quantity from the <code>inventories<\/code> table, and calculates the stock cover ratio:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">WITH<\/span>\n  stocks <span class=\"hljs-keyword\">AS<\/span> (\n    <span class=\"hljs-keyword\">SELECT<\/span>\n      product_name,\n      safety_stock,\n      SUM(quantity) inventory_qty\n    <span class=\"hljs-keyword\">FROM<\/span>\n      products\n      <span class=\"hljs-keyword\">INNER<\/span> <span class=\"hljs-keyword\">JOIN<\/span> inventories <span class=\"hljs-keyword\">USING<\/span> (product_id)\n    <span class=\"hljs-keyword\">GROUP<\/span> <span class=\"hljs-keyword\">BY<\/span>\n      product_name,\n      safety_stock\n  )\n<span class=\"hljs-keyword\">SELECT<\/span>\n  product_name,\n  inventory_qty \/ safety_stock stock_coverage\n<span class=\"hljs-keyword\">FROM<\/span>\n  stocks\n<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span>\n  product_name;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?q=V0lUSCBzdG9ja3MgQVMgKCBTRUxFQ1QgcHJvZHVjdF9uYW1lLCBzYWZldHlfc3RvY2ssIFNVTShxdWFudGl0eSkgaW52ZW50b3J5X3F0eSBGUk9NIHByb2R1Y3RzIElOTkVSIEpPSU4gaW52ZW50b3JpZXMgVVNJTkcgKHByb2R1Y3RfaWQpIEdST1VQIEJZIHByb2R1Y3RfbmFtZSwgc2FmZXR5X3N0b2NrICkgU0VMRUNUIHByb2R1Y3RfbmFtZSwgaW52ZW50b3J5X3F0eSAvIHNhZmV0eV9zdG9jayBzdG9ja19jb3ZlcmFnZSBGUk9NIHN0b2NrcyBPUkRFUiBCWSBwcm9kdWN0X25hbWU7\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">division by zero<\/code><\/span><\/pre>\n\n\n<p>The output shows the division by zero error.<\/p>\n\n\n\n<p>The reason is that some products have safety stock 0. To prevent the division by zero error, you can use the <code>NULL<\/code>IF statement to return <code>NULL<\/code> if the safety stock is zero:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"PostgreSQL SQL dialect and PL\/pgSQL\" data-shcb-language-slug=\"pgsql\"><span><code class=\"hljs language-pgsql\"><span class=\"hljs-keyword\">WITH<\/span>\n  stocks <span class=\"hljs-keyword\">AS<\/span> (\n    <span class=\"hljs-keyword\">SELECT<\/span>\n      product_name,\n      NULLIF(safety_stock, <span class=\"hljs-number\">0<\/span>) safety_stock,\n      SUM(quantity) inventory_qty\n    <span class=\"hljs-keyword\">FROM<\/span>\n      products\n      <span class=\"hljs-keyword\">INNER<\/span> <span class=\"hljs-keyword\">JOIN<\/span> inventories <span class=\"hljs-keyword\">USING<\/span> (product_id)\n    <span class=\"hljs-keyword\">GROUP<\/span> <span class=\"hljs-keyword\">BY<\/span>\n      product_name,\n      safety_stock\n  )\n<span class=\"hljs-keyword\">SELECT<\/span>\n  product_name,\n  inventory_qty,\n  safety_stock,\n  inventory_qty \/ safety_stock stock_coverage\n<span class=\"hljs-keyword\">FROM<\/span>\n  stocks\n<span class=\"hljs-keyword\">ORDER<\/span> <span class=\"hljs-keyword\">BY<\/span>\n  product_name;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PostgreSQL SQL dialect and PL\/pgSQL<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">pgsql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pgtutorial.com\/playground\/?q=V0lUSCBzdG9ja3MgQVMgKCBTRUxFQ1QgcHJvZHVjdF9uYW1lLCBOVUxMSUYoc2FmZXR5X3N0b2NrLCAwKSBzYWZldHlfc3RvY2ssIFNVTShxdWFudGl0eSkgaW52ZW50b3J5X3F0eSBGUk9NIHByb2R1Y3RzIElOTkVSIEpPSU4gaW52ZW50b3JpZXMgVVNJTkcgKHByb2R1Y3RfaWQpIEdST1VQIEJZIHByb2R1Y3RfbmFtZSwgc2FmZXR5X3N0b2NrICkgU0VMRUNUIHByb2R1Y3RfbmFtZSwgaW52ZW50b3J5X3F0eSwgc2FmZXR5X3N0b2NrLCBpbnZlbnRvcnlfcXR5IC8gc2FmZXR5X3N0b2NrIHN0b2NrX2NvdmVyYWdlIEZST00gc3RvY2tzIE9SREVSIEJZIHByb2R1Y3RfbmFtZTs%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Partial Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">        product_name        | inventory_qty | safety_stock | stock_coverage\n----------------------------+---------------+--------------+----------------\n Apple AirPods Pro 3        |           180 |           45 |              4\n Apple iMac 24\"             |           320 |         NULL |           NULL\n Apple iPad Pro 12.9        |           170 |           15 |             11\n Apple iPhone 15            |           150 |           20 |              7\n Apple iPhone 15 Pro Max    |           140 |           50 |              2\n Apple Watch Series 9       |           200 |           20 |             10\n Bose SoundLink Max         |           270 |         NULL |           NULL\n...<\/code><\/span><\/pre>\n\n\n<p>In this example, if the safety stock is 0, the <code>NULLIF<\/code> statement returns <code>NULL<\/code>; otherwise, it returns the safety stock. Dividing an inventory by <code>NULL<\/code> will result in <code>NULL<\/code> instead of an error.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the PostgreSQL <code>NULLIF<\/code> function to return <code>NULL<\/code> if two arguments are equal or the first argument otherwise.<\/li>\n\n\n\n<li>Use the <code>NULLIF<\/code> function to replace a value with <code>NULL<\/code> or prevent division by zero by replacing 0 with <code>NULL<\/code>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='quiz'>Quiz <a href=\"#quiz\" class=\"anchor\" id=\"quiz\" title=\"Anchor for Quiz\">#<\/a><\/h2>\n\n\n\n<iframe loading=\"lazy\"\n  name=\"quiz\"\n  src=\"\/quiz\/?quiz=nullif\"\n  height=\"700\"\n  width=\"600\"\n  class=\"iframe\"\n><\/iframe>\n\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"711\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL NULLIF Function\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"711\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/\"\n\t\t\t\tdata-post-title=\"PostgreSQL NULLIF Function\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn how to use the PostgreSQL NULLIF function to compare two expressions and return NULL if they are equal.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":13,"menu_order":63,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-711","page","type-page","status-publish","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>PostgreSQL NULLIF Function<\/title>\n<meta name=\"description\" content=\"In this tutorial, you&#039;ll learn how to use the PostgreSQL NULLIF function to compare two expressions and return NULL if they are equal.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"PostgreSQL NULLIF Function\" \/>\n<meta property=\"og:description\" content=\"In this tutorial, you&#039;ll learn how to use the PostgreSQL NULLIF function to compare two expressions and return NULL if they are equal.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/\" \/>\n<meta property=\"og:site_name\" content=\"PostgreSQL Tutorial\" \/>\n<meta property=\"article:modified_time\" content=\"2025-01-03T09:16:08+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-nullif\\\/\",\"url\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-nullif\\\/\",\"name\":\"PostgreSQL NULLIF Function\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/#website\"},\"datePublished\":\"2024-12-07T11:46:09+00:00\",\"dateModified\":\"2025-01-03T09:16:08+00:00\",\"description\":\"In this tutorial, you'll learn how to use the PostgreSQL NULLIF function to compare two expressions and return NULL if they are equal.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-nullif\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-nullif\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/postgresql-tutorial\\\/postgresql-nullif\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.pgtutorial.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"PostgreSQL Tutorial\",\"item\":\"https:\\\/\\\/www.pgtutorial.com\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"PostgreSQL NULLIF Function\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.pgtutorial.com\\\/#website\",\"url\":\"https:\\\/\\\/www.pgtutorial.com\\\/\",\"name\":\"PostgreSQL Tutorial\",\"description\":\"Learn PostgreSQL from Scratch\",\"alternateName\":\"PostgreSQL\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.pgtutorial.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"PostgreSQL NULLIF Function","description":"In this tutorial, you'll learn how to use the PostgreSQL NULLIF function to compare two expressions and return NULL if they are equal.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/","og_locale":"en_US","og_type":"article","og_title":"PostgreSQL NULLIF Function","og_description":"In this tutorial, you'll learn how to use the PostgreSQL NULLIF function to compare two expressions and return NULL if they are equal.","og_url":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/","og_site_name":"PostgreSQL Tutorial","article_modified_time":"2025-01-03T09:16:08+00:00","twitter_card":"summary_large_image","twitter_misc":{"Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/","url":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/","name":"PostgreSQL NULLIF Function","isPartOf":{"@id":"https:\/\/www.pgtutorial.com\/#website"},"datePublished":"2024-12-07T11:46:09+00:00","dateModified":"2025-01-03T09:16:08+00:00","description":"In this tutorial, you'll learn how to use the PostgreSQL NULLIF function to compare two expressions and return NULL if they are equal.","breadcrumb":{"@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.pgtutorial.com\/postgresql-tutorial\/postgresql-nullif\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pgtutorial.com\/"},{"@type":"ListItem","position":2,"name":"PostgreSQL Tutorial","item":"https:\/\/www.pgtutorial.com\/"},{"@type":"ListItem","position":3,"name":"PostgreSQL NULLIF Function"}]},{"@type":"WebSite","@id":"https:\/\/www.pgtutorial.com\/#website","url":"https:\/\/www.pgtutorial.com\/","name":"PostgreSQL Tutorial","description":"Learn PostgreSQL from Scratch","alternateName":"PostgreSQL","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.pgtutorial.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/711","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/comments?post=711"}],"version-history":[{"count":10,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/711\/revisions"}],"predecessor-version":[{"id":1418,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/711\/revisions\/1418"}],"up":[{"embeddable":true,"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/pages\/13"}],"wp:attachment":[{"href":"https:\/\/www.pgtutorial.com\/wp-json\/wp\/v2\/media?parent=711"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}