Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between #> and ->> operator in PostgreSQL?

We can access any JSON element in PostgreSQL 9.3 using the -> and ->> operators. Seems to me that the #> along with #>> only provide a shorter form of writing the JSON path. Or is there a bigger picture behind the #> operator? Does it serve a special purpose/provide any advantage over the arrow notation? Which one is the preffered method of writing paths?

It all comes to the question: why should I use the #> and #>> operator over the -> and ->>?

The docs are a bit enigmatic about this.

Both queries below give the same result:

=> select '{"a":[1,2,3],"b":[4,5,6]}'::json#>'{a,2}';
 ?column? 
----------
 3

=> select '{"a":[1,2,3],"b":[4,5,6]}'::json->'a'->>2;
 ?column? 
----------
 3
like image 596
Maciej Sz Avatar asked Jan 20 '14 21:01

Maciej Sz


1 Answers

Consider nesting.

{
  "a" : {
    "b" : {
      "c" : 1,
      "d" : 2
    }
  }
}

Imagine that you have a json document, and you don't know in advance how it will be nested. If you knew you needed a three level path, you could write:

SELECT '{
  "a" : {
    "b" : {
      "c" : 1,
      "d" : 2
    }
  }
}'::json -> 'a' -> 'b' -> 'c';

but what if you want to write a query that doesn't know that in advance? That's where the path-based operators are useful; the path can be supplied along with the document, and there's no longer any assumption about the document structure in the query.

SELECT '{
  "a" : {
    "b" : {
      "c" : 1,
      "d" : 2
    }
  }
}'::json #>> ARRAY['a','b','c']
like image 99
Craig Ringer Avatar answered Oct 13 '22 05:10

Craig Ringer