Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1kzKyL-0004DY-AF for pgsql-general@arkaria.postgresql.org; Tue, 12 Jan 2021 14:48:37 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1kzKyK-0007WD-98 for pgsql-general@arkaria.postgresql.org; Tue, 12 Jan 2021 14:48:36 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1kzKyK-0007W6-20 for pgsql-general@lists.postgresql.org; Tue, 12 Jan 2021 14:48:36 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1kzKyF-0004Pe-GJ for pgsql-general@postgresql.org; Tue, 12 Jan 2021 14:48:35 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 10CEmR4J1126921; Tue, 12 Jan 2021 09:48:27 -0500 From: Tom Lane To: "Joel Jacobson" cc: pgsql-general@postgresql.org Subject: Re: CASE WHEN idiomatic for functions with side-effect? In-reply-to: <6aab85ba-a97c-4394-ab80-6077bb14be2b@www.fastmail.com> References: <6aab85ba-a97c-4394-ab80-6077bb14be2b@www.fastmail.com> Comments: In-reply-to "Joel Jacobson" message dated "Tue, 12 Jan 2021 12:13:47 +0400" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <1126919.1610462907.1@sss.pgh.pa.us> Date: Tue, 12 Jan 2021 09:48:27 -0500 Message-ID: <1126920.1610462907@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk "Joel Jacobson" writes: > Is it idiomatic and safe to use > SELECT > CASE boolean_expression WHEN TRUE THEN function_with_side_effects() END > in a query to ensure the function_with_side_effects() is only > execute if boolean_expression is true? As long as function_with_side_effects() is properly marked volatile, it's safe (whether it's idiomatic is in the eye of the beholder). The issue with the divide-by-zero example is that the division operator is marked immutable, so if the planner sees that it has constant arguments it will try to simplify-on-sight, even within a CASE expression. regards, tom lane