cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

What is the equivalent of "if exists()" in databricks sql?

reachrishav
New Contributor II

What is the equivalent of the below sql server syntax in databricks sql? there are cases where i need to execute a block of sql code on certain conditions. I know this can be achieved with spark.sql, but the problem with spark.sql()  is it does not provide the number of affected columns (insert/update/delete) after the execution of dml statement.

IF EXISTS(SELECT 1 FROM table WHERE col = value)

BEGIN

     DELETE FROM table WHERE col = value

END

ELSE

BEGIN

    <code to run in else>

END

 

1 REPLY 1

Kaniz_Fatma
Community Manager
Community Manager

Hi @reachrishav, In Databricks SQL, you can replicate SQL Server's conditional logic using `CASE` statements and `MERGE` operations. Since Databricks SQL doesn't support `IF EXISTS` directly, you can create a temporary view to check your condition and then use `MERGE` to perform the desired operations. Afterward, you can count the affected rows with a `SELECT` statement. This approach allows for conditional execution and tracking of affected rows without relying on SQL Server-specific syntax.

Does this help with your use case? If you have any more specific requirements or questions, feel free to ask!

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you wonโ€™t want to miss the chance to attend and share knowledge.

If there isnโ€™t a group near you, start one and help create a community that brings people together.

Request a New Group