cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Using conditional value on create statement

ri8ika
Graph Voyager

How to use conditional value something like?

CREATE (n: Nodename {
  myprop: somevalue IS NULL THEN 'abc' ELSE somevalue
})

The preceding code throws me an error:

Invalid input 'T': expected whitespace, comment, "=~", IN, STARTS, ENDS, CONTAINS, IS, '^', '*', '/', '%', '+', '-', '=', '~', "<>", "!=", '<', '>', "<=", ">=", AND, XOR, OR, ',' or '}'

I also tried like:

somevalue if somevalue else 'abc'
1 ACCEPTED SOLUTION

You want to use CASE statements here. These are used for exactly this, different expressions depending on conditionals (they can't be used for conditional Cypher execution, that's a different thing).

... // assume someValue is an integer in scope
CREATE
  (n:Node)
SET 
  n.myprop = CASE somevalue WHEN 0 THEN 'abc' WHEN 5 THEN 'abc6' END 
```

From the linked docs you can also see that it supports ELSE for a fallback, as well as a slightly more complex version where multiple separate boolean conditionals can be evaluated instead of just doing a single conditional evaluation like above.

View solution in original post

4 REPLIES 4

Probably best to use the coalesce function. This will return the first non-null value in a list of values provided.

CREATE
  (n:Node)
SET 
  n.myprop = coalesce(somevalue, 'abc')

You may also look in this post what I'm trying to do for several days but not able to achieve what I wanted.

ri8ika
Graph Voyager

Can we achieve something like this?

Let's say somevalue is 0:

Then it should be just 'abc'.

When somevalue is 5:
Then it should be 'abc6':

This doesn't work in this case:
coalesce('abc'+somevalue+1,'abc') // I know it's not the way

Any idea?

You want to use CASE statements here. These are used for exactly this, different expressions depending on conditionals (they can't be used for conditional Cypher execution, that's a different thing).

... // assume someValue is an integer in scope
CREATE
  (n:Node)
SET 
  n.myprop = CASE somevalue WHEN 0 THEN 'abc' WHEN 5 THEN 'abc6' END 
```

From the linked docs you can also see that it supports ELSE for a fallback, as well as a slightly more complex version where multiple separate boolean conditionals can be evaluated instead of just doing a single conditional evaluation like above.