Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to parse this sql

Tags:

sql

mysql

I'm trying to understand what this SQL (from a MySQL installation) actually does:

IF(coalesce(a.entity_id, 0) != 0, 0, 1)

While I understand what the coalesce does I don't understand how the IF statement is modifying it.

like image 224
phileas fogg Avatar asked Aug 26 '11 20:08

phileas fogg


People also ask

What does try PARSE do SQL?

The TRY_PARSE function converts a string value to the specified data type. Use TRY_PARSE only for converting a string to datetime or a numeric value. If the conversion fails, instead of returning an error, a NULL is returned.

What is PARSE SQL?

The parsing stage involves separating the pieces of a SQL statement into a data structure that other routines can process. The database parses a statement when instructed by the application, which means that only the application, and not the database itself, can reduce the number of parses.

Can you PARSE strings in SQL?

String parsing is a common task for data analysts and data engineers working with raw data. With the growth of unstructured qualitative data, parsing strings efficiently has become increasingly important for fast analysis.

What is command parser in SQL Server?

“CMD Parser” is the first component of Relational Engine to receive the Query data. The principal job of CMD Parser is to check the query for Syntactic and Semantic error. Finally, it generates a Query Tree.


2 Answers

I think:

coalesce(a.entity_id, 0) - return the first not null value,

if a.entity_id is not null you get 0 as a result of if, else 1.

a.entity_id = null => coalesce = 0 => if = 1

a.entity_id is not null => coalesce = a.entity_id => if = 0

like image 194
Andrej Ludinovskov Avatar answered Sep 22 '22 17:09

Andrej Ludinovskov


coalesce returns the first NON-null argument. So if a.entity_id is null, coalesce will return 0. the containing if() then checks if the argument is not zero, and returns 0 or 1.

basically it's a convoluted way of writing a.entity_id IS NULL.

like image 24
Marc B Avatar answered Sep 22 '22 17:09

Marc B