乐闻世界logo
搜索文章和话题

What is the difference between `->>` and `->` in Postgres SQL?

1个答案

1

In PostgreSQL, both ->> and -> are operators used for handling JSON data types. Their main difference lies in the type of data they return.

  1. -> Operator:

    • The -> operator is used to access elements within a JSON object, returning data of the JSON type.
    • For example, suppose we have a JSON column named data containing the following JSON object: \"{\"name\": \"John\", \"age\": 30}\".
    • If we execute the query SELECT data->'name' FROM table_name;, the result will be a JSON string: 'John'.
  2. ->> Operator:

    • The ->> operator is also used to access elements of a JSON object, but it returns text data.
    • Using the same example, if we execute the query SELECT data->>'name' FROM table_name;, the result will be a plain text string: 'John', not JSON.

Therefore, the key difference is in the return type: -> returns JSON, while ->> returns text. This means that when using ->>, you directly obtain the standard SQL data type without further processing of JSON data.

Application Scenario Example:

Suppose we need to directly compare or process names in the query results; using ->> is more convenient:

sql
SELECT * FROM employees WHERE data->>'name' = 'John';
2024年8月9日 02:28 回复

你的答案