SlideShare a Scribd company logo
IBM Cloud1IBM Digital Technical Engagement
Update onWorking with NoSQL InYour
RDBMS
Using Db2 Json Functions
By George Baklarz
IBM DTE Team
ibm.com/demos/collection/db2-database
IBM Cloud2IBM Digital Technical Engagement
Please note
 IBM’s statements regarding its plans, directions, and intent are subject to change
or withdrawal without notice and at IBM’s sole discretion.
 Information regarding potential future products is intended to outline our general
product direction and it should not be relied on in making a purchasing decision.
 The information mentioned regarding potential future products is not a commitment,
promise, or legal obligation to deliver any material, code or functionality. Information about
potential future products may not be incorporated into any contract.
 The development, release, and timing of any future features or functionality described for
our products remains at our sole discretion.
 Performance is based on measurements and projections using standard IBM benchmarks in
a controlled environment. The actual throughput or performance that any user will
experience will vary depending upon many factors, including considerations such as the
amount of multiprogramming in the user’s job stream, the I/O configuration, the storage
configuration, and the workload processed. Therefore, no assurance can be given that an
individual user will achieve results similar to those stated here.
IBM Cloud3
RDBMS vs NoSQL
3
<?xml version="1.0" encoding="UTF-16" ?>
<Instrument>
<Id>I100</Id>
<ProductType>VarianceSwap</ProductType>
<ProductCurrency>GBP</ProductCurrency>
<Quantity>10000.50</Quantity>
<ExpiryDate>2018-03-31</ExpiryDate>
<StrikePrice>75.35</StrikePrice>
<ObservationSchedule>
</Observation date="2018-01-01" time="AM">
</Observation date="2018-02-01" time="AM">
</Observation date="2018-03-01" time="AM">
</Observation date="2018-03-31" time="PM">
</ObservationSchedule>
</Instrument>
{
"Id":"I100",
"ProductType":"VarianceSwap",
"ProductCurrency":"GBP",
"Quantity":["10000.50"],
"ExpiryDate":"2018-03-31",
"StrikePrice":"75.35",
"ObservationSchedule":[
{"ObservationDate" : "2018-01-01","ObservationTime" : "AM"},
{"ObservationDate" : "2018-02-01","ObservationTime" : "AM"},
{"ObservationDate" : "2018-03-01","ObservationTime" : "AM"},
{"ObservationDate" : "2018-03-31","ObservationTime" : "PM"}
]
}
ID PRODUCT_TYPE PRODUCT_CURRENCY QUANTITY EXPIRY_DATE STRIKE_PRICE
I100 VarianceSwap GBP 10000.50 2018-03-31 75.35
ID OBSERVATION_DATE OBSERVATION_TIME
I100 2018-01-01 AM
I100 2018-02-01 AM
I100 2018-03-01 AM
I100 2018-03-31 PM
XML
JSON
Relational
IBM Cloud4
RDBMS vs NoSQL
4
<?xml version="1.0" encoding="UTF-16" ?>
<Instrument>
<Id>I100</Id>
<ProductType>VarianceSwap</ProductType>
<ProductCurrency>GBP</ProductCurrency>
<Quantity>10000.50</Quantity>
<Quantities>
<Quantity>10000.50</Quantity>
<Quantity>50000.00</Quantity>
<Quantities>
<ExpiryDate>2018-03-31</ExpiryDate>
<StrikePrice>75.35</StrikePrice>
<ObservationSchedule>
</Observation date="2018-01-01" time="AM">
</Observation date="2018-02-01" time="AM">
</Observation date="2018-03-01" time="AM">
</Observation date="2018-03-31" time="PM">
</ObservationSchedule>
</Instrument>
{
"Id":"I100",
"ProductType":"VarianceSwap",
"ProductCurrency":"GBP",
"Quantity":["10000.50","50000.00"],
"ExpiryDate":"2018-03-31",
"StrikePrice":"75.35",
"ObservationSchedule":[
{"ObservationDate" : "2018-01-01","ObservationTime" : "AM"},
{"ObservationDate" : "2018-02-01","ObservationTime" : "AM"},
{"ObservationDate" : "2018-03-01","ObservationTime" : "AM"},
{"ObservationDate" : "2018-03-31","ObservationTime" : "PM"}
]
}
ID PRODUCT_TYPE PRODUCT_CURRENCY QUANTITY EXPIRY_DATE STRIKE_PRICE
I100 VarianceSwap GBP 10000.50 2018-03-31 75.35
ID OBSERVATION_DATE OBSERVATION_TIME
I100 2018-01-01 AM
I100 2018-02-01 AM
I100 2018-03-01 AM
I100 2018-03-31 PM
ID QUANTITY
I100 10000.50
I100 50000.00
XML
JSON
Relational
IBM Cloud5
Publishing Functions Comments
JSON_ARRAY Creates JSON array from input key value pairs
JSON_OBJECT Creates JSON object from input key value pairs
Retrieval Functions Comments
JSON_QUERY Extract a JSON object from a JSON object
JSON_VALUE Extract an SQL scalar value from a JSON object
JSON_EXISTS Determines whether or not a value exists in a document
JSON_TABLE Creates relational output from a JSON object
Conversion Function Comments
BSON_TO_JSON Convert BSON formatted document into JSON strings
JSON_TO_BSON Convert JSON strings into a BSON document format
New ISO JSON SQL Functions
Lot's of New Capabilities! Take JSON Hands on Lab: ibm.com/demos/collection/db2-database
IBM Cloud6
Storage
 You choose the format: JSON or BSON
 There is no "native" JSON data type and one is not specified by the standard
 You choose the table organization: row or column (where supported)
 You choose the column data type:
• By default, Db2 will assume character data types are JSON and binary ones are BSON
 Try to "inline" the columns if possible to provide better performance
CREATE TABLE T1 (C1 VARCHAR(300))
CREATE TABLE T1 (C1 BLOB(512) INLINE LENGTH 512)
 Complimentary (but optional) conversion functions are provided to move between JSON and
BSON if so desired although you can also use other products to do this
SYSIBM.BSON_TO_JSON
SYSIBM.JSON_TO_BSON
IBM Cloud7
JSON Document Structure
 JSON documents have an inherent structure to them
 Many of the JSON functions provided with Db2 need a method to navigate through a
document to retrieve the object or item that the user wants
 To illustrate how a JSON path expression points to a particular object, one of the
records of the customer document is shown:
{
"customerid": 100000,
"identity":
{
"firstname": "Jacob", "lastname": "Hines", "birthdate": "1982-09-18"
},
"contact":
{
"street": "Main Street North",
"city": "Amherst", "state": "OH", "zipcode": "44001",
"email": "Ja.Hines@yahii.com",
"phone": "813-689-8309"
},
"payment":
{
"card_type": "MCCD", "card_no": "4742-3005-2829-9227"
},
"purchases":
[
{
"tx_date": "2018-02-14",
"tx_no": 157972,
"product_id": 1860,
"product": "Ugliest Snow Blower",
"quantity": 1,
"item_cost": 51.86
}, ... additional purchases ...
]
}
Document
customerid identity
firstname
lastname
birthdate
contact
street
city
state
zipcode
email
phone
payment
card_type
card_no
purchases*
tx_date
tx_no
product_id
product
quantity
item_cost
IBM Cloud8
JSON Path Expression
 Every JSON path expression begins with a dollar sign ($) to represent the root or top of
the document structure
 To traverse down the document, the dot/period (.) is used to move down one level
 The asterisk (*) represents all values that are found in the object
 The dollar sign and period are reserved characters for the purposes of path expressions
 The LAX and STRICT modifiers are used to control the matching behavior of the JSON
path evaluation
IBM Cloud9
JSON Path Examples
 To retrieve the value associated with the identity key, the path expression would be:
$.identity
 The value referred to in this last example is the entire JSON object
{
"firstname": "Jacob",
"lastname" : "Hines",
"birthdate": "1982-09-18"
}
 To refer to the birthdate, then we would append the internal key name
$.identity.birthdate
➡️ "1982-09-18"
 To reference the first element of an array, you would append an array specifier [ ]
$.purchases[0].product
➡️ "Ugliest Snow Blower" Take JSON Hands on Lab: ibm.com/demos/collection/db2-database
IBM Cloud10
JSON Conversion Functions
 If you decide to store the data in binary format, you must use the JSON_TO_BSON
function to convert the JSON into the proper format
 You also have the option of using an external BSON library to convert the string and
insert the value directly into the column (i.e. Db2 is not involved in the conversion)
 Documents are checked for validity (proper JSON) when using the
JSON_TO_BSON function
 Documents that are stored as character strings are NOT checked for validity until it is
used in a JSON function
IBM Cloud11
JSON_EXISTS: Checking for Key-Value Pairs
 JSON_EXISTS allows you to check whether or not a valid JSON key exists within a
document for the provided search path
 Example
VALUES JSON_EXISTS(customer, '$.identity.middlename')
➡️ False
 The ON ERROR clause of the JSON_EXISTS function determines what value should be
returned when an error occurs
IBM Cloud12
JSON_EXISTS: Examples
c = {
"empno":"000070",
"firstnme":"EVA",
"midinit":"D",
"lastname":"PULASKI",
"workdept":"D21",
"phoneno":[7831,1422,4567],
"hiredate":"09/30/2005",
"job":"MANAGER",
"edlevel":16,
"sex":"F",
"birthdate":"05/26/2003",
"pay":
{
"salary":96170.00,
"bonus":700.00,
"comm":2893.00
}
}
JSON_EXISTS(c,'$.empno')
➡️ true
JSON_EXISTS(c,'$.phoneno[0]')
➡️ true
JSON_EXISTS(c,'$.middleinit')
➡️ false
JSON_EXISTS(c,'$.pay')
➡️ true
JSON_EXISTS(c,'$.phoneno[999]' TRUE ON ERROR)
➡️ true
Take JSON Hands on Lab: ibm.com/demos/collection/db2-database
IBM Cloud13
JSON_VALUE: Retrieving Individual Values
 The JSON_VALUE function is used to retrieve a single value from a JSON document in
the form of a "native" SQL data type
 This function implicitly converts the returning value from its original JSON format to the
identified Db2 data type
 Since it is a scalar function, JSON_VALUE can only return a single value and will return
an error if there are multiple values found
IBM Cloud14
JSON_VALUE: Examples
c = {
"empno":"000070",
"firstnme":"EVA",
"midinit":"D",
"lastname":"PULASKI",
"workdept":"D21",
"phoneno":[7831,1422,4567],
"hiredate":"09/30/2005",
"job":"MANAGER",
"edlevel":16,
"sex":"F",
"birthdate":"05/26/2003",
"pay":
{
"salary":96170.00,
"bonus":700.00,
"comm":2893.00
}
}
JSON_VALUE(c,'$.empno')
➡️ '000070'
JSON_VALUE(c,'$.empno' RETURNING INT)
➡️ 70
JSON_VALUE(c,'$.middle' DEFAULT '?' ON EMPTY)
➡️ '?'
JSON_VALUE(c,'strict $.middle' DEFAULT '?' ON EMPTY)
➡️ null
JSON_VALUE(c,'$.phoneno[999]' DEFAULT 0 ON EMPTY)
➡️SQL0440N No authorized routine named "CLOB" of type
"FUNCTION" having compatible arguments was found.
SQLSTATE=42884 SQLCODE=-440
Take JSON Hands on Lab: ibm.com/demos/collection/db2-database
IBM Cloud15
JSON_QUERY: Retrieving Objects and Arrays
 JSON_VALUE is limited to retrieving atomic or individual values from within a document
 In order to extract native JSON values, which can include complex ones such as multiple
array values or entire JSON objects, you must use the JSON_QUERY function
 The json-expression, and json-path-expression are identical to the JSON_VALUE
function
 Two additional clauses are added for dealing with objects:
 Wrapper clause for dealing with arrays
 Quotes clause for handling character string output
IBM Cloud16
JSON_QUERY: Examples
c = {
"empno":"000070",
"firstnme":"EVA",
"midinit":"D",
"lastname":"PULASKI",
"workdept":"D21",
"phoneno":[7831,1422,4567],
"hiredate":"09/30/2005",
"job":"MANAGER",
"edlevel":16,
"sex":"F",
"birthdate":"05/26/2003",
"pay":
{
"salary":96170.00,
"bonus":700.00,
"comm":2893.00
}
}
JSON_QUERY(c,'$.pay')
➡️ {
'salary': 96170.0,
'bonus': 700.0,
'comm': 2893.0
}
JSON_QUERY(c,'$.pay.bonus')
➡️ '700.0'
JSON_QUERY(c,'$.phoneno[0]')
➡️ 7831
JSON_QUERY(c,'$.phoneno[0]'
WITH CONDITIONAL WRAPPER)
➡️ [7831]
JSON_QUERY(c,'$.phoneno[*]' WITH CONDITIONAL WRAPPER)
➡️ [7831,1422,4567]
IBM Cloud17
JSON_TABLE: Retrieving Documents as a Table
 JSON_VALUE and JSON_OBJECT can be used individually to retrieve all of the values
within a JSON document, but an easier method exists with the JSON_TABLE function
 This function does not yet implement all of the ISO JSON_TABLE function definition but
it can help simplify retrieval of multiple object in a document
 The JSON_TABLE function has two ways of publishing column values
 Regular column expressions mimic the JSON_VALUE function
 Formatted column expressions use features from the JSON_QUERY function
IBM Cloud18
JSON_TABLE: Column Expressions
 The body of the JSON_TABLE function includes the list of columns that you want
created
 Each of these formats uses the same column name, data type and path definitions
 The column can be defined in one of two ways:
 A column name derived from a JSON path expression and a data type
"forward.primary.last_name" VARCHAR(20)
 A SQL column name with a data type and a JSON path expression
NAME VARCHAR(20) FORMAT JSON PATH "$.forward.primary.last_name"
 The first method can be a convenient short cut when your JSON document has most of
the data at the root ($.) level
 The column names can become extremely long if you have multi-level objects
Regular Column Expression Formatted Column Expression
IBM Cloud19
JSON_TABLE: Examples
book =
{
"authors":
[
{"first":"Paul", "last":"Bird"},
{"first":"George","last":"Baklarz"}
],
"foreword":
{
"primary":
{"first":"Thomas","last":"Hronis"}
},
"formats":
{
"hardcover": 19.99,
"paperback": 9.99,
"ebook" : 1.99,
"pdf" : 1.99
}
}
SELECT T.* FROM
JSON_TABLE(:book, 'strict $'
COLUMNS( "authors[0].first" VARCHAR(20),
"authors[0].last" VARCHAR(20))
ERROR ON ERROR) AS T
authors[0].first authors[0].last
---------------- ---------------
Paul Bird
SELECT T.* FROM
JSON_TABLE(:book, 'strict $'
COLUMNS(
FIRST_NAME VARCHAR(20) PATH '$.authors[1].first',
LAST_NAME VARCHAR(20) PATH '$.authors[1].last'
)
ERROR ON ERROR) AS T
FIRST_NAME LAST_NAME
------------------- --------------------
George Baklarz
IBM Cloud20
JSON_OBJECT: Publishing Objects
 The JSON_OBJECT function will generate a JSON object by creating key:value pairs
 Objects can be created at at multiple levels by nesting the JSON_OBJECT function
 The key:value pairs are generated using the following syntax:
IBM Cloud21
JSON_ARRAY: Publishing Arrays
 In order to create arrays, we must use the JSON_ARRAY function
 There are two forms of the JSON_ARRAY function
 The first version is similar to the JSON_OBJECT function where you supply a list of values to
create an array
 The second form of the JSON_ARRAY function uses the results of a SQL select statement to build
the array values
IBM Cloud22
JSON_ARRAY: Creating an Array with Values
 The first form of the JSON_ARRAY function requires a list of values to create an array
 There is no key associated with a JSON array, so you only need to supply the list of values that
you want published
VALUES JSON_ARRAY( 1523, 902, 'Thomas', 7777)
Result: [1523,902,"Thomas",7777]
JSON array elements do not need to have the same data type
Array values can contain other objects
VALUES JSON_ARRAY(1523, 902,
JSON_OBJECT( KEY 'lastname' VALUE 'Bird') FORMAT JSON,
7777)
Result: [1523,902,{"lastname":"Bird"},7777]
 While the JSON_ARRAY function can be used by itself, it does not create a proper
JSON document
 The output from this function is meant to be used as part of a JSON_OBJECT structure
IBM Cloud23
JSON_ARRAY: Creating an Array with an SQL Statement
 The second form of the JSON_ARRAY function uses the results of a SQL select
statement to build the array values
 Only one SELECT statement can be used in the body of the function
VALUES JSON_OBJECT(KEY 'departments'
VALUE JSON_ARRAY(SELECT DEPTNO FROM DEPARTMENT WHERE DEPTNAME LIKE 'B%')
FORMAT JSON)
Result: {"departments":["F22","G22","H22","I22","J22"]}
 If you do need to create an array from multiple sources, you should look at using a
SELECT statement with UNION to create one list of items
IBM Cloud24
Performance: Using Indexes
 Leveraging Db2's index on expression capability allows us to create indexes on JSON
documents to allow faster access
 Example: Searching for an employee number will result in a scan against the table if no
indexes are defined:
SELECT JSON_VALUE(EMP_DATA, '$.lastname' RETURNING CHAR(20)) AS LASTNAME FROM JSON_EMP
WHERE JSON_VALUE(EMP_DATA, '$.empno' RETURNING CHAR(6)) = '000010'
 Creating the following index will greatly improve performance of this query
CREATE INDEX IX_JSON
ON JSON_EMP (JSON_VALUE(EMP_DATA, '$.empno' RETURNING CHAR(6));
versus
Statements Executed in 30 second interval
IBM Cloud25
Maintenance: SYSTOOLS.JSON_UPDATE
 The ISO JSON standard does not currently provide an update function
 It is left up to the application developer to retrieve the entire document and update it
externally and then re-insert (or update) the JSON document in the database
 The JSON_UPDATE function is part of the SYSTOOLS schema and allows for in-place
updating of a document
 It requires the user or application be granted EXECUTE privilege on the function
 Must explicitly qualify any reference to the function with the SYSTOOLS schema
 The syntax of the JSON_UPDATE function is:
JSON_UPDATE(document, '{$set : {field:value}}')
'{$unset: {field:null}}'
 The arguments are:
 document – BSON document
 operation ($set or $unset)
 key – The key we are looking for
IBM Cloud26IBM Digital Technical Engagement
Thank You !
Seem more on Db2 @
IBM.COM/Demos/collection/db2-database
Take JSON Hands on Lab:
ibm.com/demos/collection/db2-database

More Related Content

What's hot (20)

PPTX
Rdbms vs. no sql
Amar Jagdale
 
PDF
Delta lake - des data lake fiables a grande échelle
françois de Buttet
 
PDF
Using PostgreSQL for Data Privacy
Mason Sharp
 
PDF
Db2 performance tuning for dummies
Angel Dueñas Neyra
 
DOCX
MySQL_SQL_Tunning_v0.1.3.docx
NeoClova
 
PPT
An Hour of DB2 Tips
Craig Mullins
 
PPTX
Azure redis cache
Shahriar Hossain
 
PDF
Using all of the high availability options in MariaDB
MariaDB plc
 
PPTX
Apache Phoenix and HBase: Past, Present and Future of SQL over HBase
DataWorks Summit/Hadoop Summit
 
PPTX
MySQL8.0_performance_schema.pptx
NeoClova
 
PDF
InnoDB Internal
mysqlops
 
PDF
Mastering PostgreSQL Administration
EDB
 
PPTX
Getting started with postgresql
botsplash.com
 
PPTX
Oracle flashback
Cambodia
 
PPTX
Mongodb backup
Dharshan Rangegowda
 
PPT
2 db2 instance creation
Ravikumar Nandigam
 
PDF
Backup and recovery in oracle
sadegh salehi
 
PDF
Introduction to SQL Server Security
Jason Strate
 
PDF
Druid
Dori Waldman
 
PPT
Oracle Architecture
Neeraj Singh
 
Rdbms vs. no sql
Amar Jagdale
 
Delta lake - des data lake fiables a grande échelle
françois de Buttet
 
Using PostgreSQL for Data Privacy
Mason Sharp
 
Db2 performance tuning for dummies
Angel Dueñas Neyra
 
MySQL_SQL_Tunning_v0.1.3.docx
NeoClova
 
An Hour of DB2 Tips
Craig Mullins
 
Azure redis cache
Shahriar Hossain
 
Using all of the high availability options in MariaDB
MariaDB plc
 
Apache Phoenix and HBase: Past, Present and Future of SQL over HBase
DataWorks Summit/Hadoop Summit
 
MySQL8.0_performance_schema.pptx
NeoClova
 
InnoDB Internal
mysqlops
 
Mastering PostgreSQL Administration
EDB
 
Getting started with postgresql
botsplash.com
 
Oracle flashback
Cambodia
 
Mongodb backup
Dharshan Rangegowda
 
2 db2 instance creation
Ravikumar Nandigam
 
Backup and recovery in oracle
sadegh salehi
 
Introduction to SQL Server Security
Jason Strate
 
Oracle Architecture
Neeraj Singh
 

Similar to IBM Db2 JSON 11.5 (20)

PDF
JSON Support in DB2 for z/OS
Jane Man
 
PPT
Using JSON/BSON types in your hybrid application environment
Ajay Gupte
 
PDF
UKOUG Tech14 - Getting Started With JSON in the Database
Marco Gralike
 
PPTX
What's new in DB2 for i - IBM i 7.3 TR1 and IBM i 7.2 TR5 - final.pptx
CesarDuarteMoreno
 
PPTX
Starting with JSON Path Expressions in Oracle 12.1.0.2
Marco Gralike
 
PPTX
Power JSON with PostgreSQL
EDB
 
PPTX
Oracle Database - JSON and the In-Memory Database
Marco Gralike
 
PPTX
Sql Server 2016 and JSON
Greg McMurray
 
PPTX
BGOUG15: JSON support in MySQL 5.7
Georgi Kodinov
 
PPTX
Querying NoSQL with SQL: HAVING Your JSON Cake and SELECTing it too
All Things Open
 
PPTX
Querying NoSQL with SQL - MIGANG - July 2017
Matthew Groves
 
PPTX
Everything That Is Really Useful in Oracle Database 12c for Application Devel...
Lucas Jellema
 
PDF
No sql way_in_pg
Vibhor Kumar
 
PPT
The NoSQL Way in Postgres
EDB
 
PDF
JSON Support in MariaDB: News, non-news and the bigger picture
Sergey Petrunya
 
PDF
Postgrtesql as a NoSQL Document Store - The JSON/JSONB data type
Jumping Bean
 
PDF
There is Javascript in my SQL
PGConf APAC
 
PPTX
JSON-SQLServer2016.pptx dgsdgdsgdsgdsgsdgdsgdsg
zmulani8
 
PDF
NoSQL Best Practices for PostgreSQL / Дмитрий Долгов (Mindojo)
Ontico
 
PDF
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
Ryan B Harvey, CSDP, CSM
 
JSON Support in DB2 for z/OS
Jane Man
 
Using JSON/BSON types in your hybrid application environment
Ajay Gupte
 
UKOUG Tech14 - Getting Started With JSON in the Database
Marco Gralike
 
What's new in DB2 for i - IBM i 7.3 TR1 and IBM i 7.2 TR5 - final.pptx
CesarDuarteMoreno
 
Starting with JSON Path Expressions in Oracle 12.1.0.2
Marco Gralike
 
Power JSON with PostgreSQL
EDB
 
Oracle Database - JSON and the In-Memory Database
Marco Gralike
 
Sql Server 2016 and JSON
Greg McMurray
 
BGOUG15: JSON support in MySQL 5.7
Georgi Kodinov
 
Querying NoSQL with SQL: HAVING Your JSON Cake and SELECTing it too
All Things Open
 
Querying NoSQL with SQL - MIGANG - July 2017
Matthew Groves
 
Everything That Is Really Useful in Oracle Database 12c for Application Devel...
Lucas Jellema
 
No sql way_in_pg
Vibhor Kumar
 
The NoSQL Way in Postgres
EDB
 
JSON Support in MariaDB: News, non-news and the bigger picture
Sergey Petrunya
 
Postgrtesql as a NoSQL Document Store - The JSON/JSONB data type
Jumping Bean
 
There is Javascript in my SQL
PGConf APAC
 
JSON-SQLServer2016.pptx dgsdgdsgdsgdsgsdgdsgdsg
zmulani8
 
NoSQL Best Practices for PostgreSQL / Дмитрий Долгов (Mindojo)
Ontico
 
JSON Processing in the Database using PostgreSQL 9.4 :: Data Wranglers DC :: ...
Ryan B Harvey, CSDP, CSM
 
Ad

Recently uploaded (20)

PPTX
ER_Model_Relationship_in_DBMS_Presentation.pptx
dharaadhvaryu1992
 
PDF
apidays Helsinki & North 2025 - How (not) to run a Graphql Stewardship Group,...
apidays
 
PPTX
apidays Singapore 2025 - The Quest for the Greenest LLM , Jean Philippe Ehre...
apidays
 
PDF
apidays Helsinki & North 2025 - REST in Peace? Hunting the Dominant Design fo...
apidays
 
PDF
What does good look like - CRAP Brighton 8 July 2025
Jan Kierzyk
 
PDF
Data Chunking Strategies for RAG in 2025.pdf
Tamanna
 
PPTX
AI Presentation Tool Pitch Deck Presentation.pptx
ShyamPanthavoor1
 
PPTX
apidays Munich 2025 - Building an AWS Serverless Application with Terraform, ...
apidays
 
PPTX
SlideEgg_501298-Agentic AI.pptx agentic ai
530BYManoj
 
PDF
Copia de Strategic Roadmap Infographics by Slidesgo.pptx (1).pdf
ssuserd4c6911
 
PPTX
apidays Helsinki & North 2025 - API access control strategies beyond JWT bear...
apidays
 
PPT
AI Future trends and opportunities_oct7v1.ppt
SHIKHAKMEHTA
 
PPTX
Numbers of a nation: how we estimate population statistics | Accessible slides
Office for National Statistics
 
PPTX
apidays Helsinki & North 2025 - Agentic AI: A Friend or Foe?, Merja Kajava (A...
apidays
 
PDF
AUDITABILITY & COMPLIANCE OF AI SYSTEMS IN HEALTHCARE
GAHI Youssef
 
PDF
Product Management in HealthTech (Case Studies from SnappDoctor)
Hamed Shams
 
PPTX
ER_Model_with_Diagrams_Presentation.pptx
dharaadhvaryu1992
 
PDF
Merits and Demerits of DBMS over File System & 3-Tier Architecture in DBMS
MD RIZWAN MOLLA
 
PPT
Growth of Public Expendituuure_55423.ppt
NavyaDeora
 
PDF
Context Engineering for AI Agents, approaches, memories.pdf
Tamanna
 
ER_Model_Relationship_in_DBMS_Presentation.pptx
dharaadhvaryu1992
 
apidays Helsinki & North 2025 - How (not) to run a Graphql Stewardship Group,...
apidays
 
apidays Singapore 2025 - The Quest for the Greenest LLM , Jean Philippe Ehre...
apidays
 
apidays Helsinki & North 2025 - REST in Peace? Hunting the Dominant Design fo...
apidays
 
What does good look like - CRAP Brighton 8 July 2025
Jan Kierzyk
 
Data Chunking Strategies for RAG in 2025.pdf
Tamanna
 
AI Presentation Tool Pitch Deck Presentation.pptx
ShyamPanthavoor1
 
apidays Munich 2025 - Building an AWS Serverless Application with Terraform, ...
apidays
 
SlideEgg_501298-Agentic AI.pptx agentic ai
530BYManoj
 
Copia de Strategic Roadmap Infographics by Slidesgo.pptx (1).pdf
ssuserd4c6911
 
apidays Helsinki & North 2025 - API access control strategies beyond JWT bear...
apidays
 
AI Future trends and opportunities_oct7v1.ppt
SHIKHAKMEHTA
 
Numbers of a nation: how we estimate population statistics | Accessible slides
Office for National Statistics
 
apidays Helsinki & North 2025 - Agentic AI: A Friend or Foe?, Merja Kajava (A...
apidays
 
AUDITABILITY & COMPLIANCE OF AI SYSTEMS IN HEALTHCARE
GAHI Youssef
 
Product Management in HealthTech (Case Studies from SnappDoctor)
Hamed Shams
 
ER_Model_with_Diagrams_Presentation.pptx
dharaadhvaryu1992
 
Merits and Demerits of DBMS over File System & 3-Tier Architecture in DBMS
MD RIZWAN MOLLA
 
Growth of Public Expendituuure_55423.ppt
NavyaDeora
 
Context Engineering for AI Agents, approaches, memories.pdf
Tamanna
 
Ad

IBM Db2 JSON 11.5

  • 1. IBM Cloud1IBM Digital Technical Engagement Update onWorking with NoSQL InYour RDBMS Using Db2 Json Functions By George Baklarz IBM DTE Team ibm.com/demos/collection/db2-database
  • 2. IBM Cloud2IBM Digital Technical Engagement Please note  IBM’s statements regarding its plans, directions, and intent are subject to change or withdrawal without notice and at IBM’s sole discretion.  Information regarding potential future products is intended to outline our general product direction and it should not be relied on in making a purchasing decision.  The information mentioned regarding potential future products is not a commitment, promise, or legal obligation to deliver any material, code or functionality. Information about potential future products may not be incorporated into any contract.  The development, release, and timing of any future features or functionality described for our products remains at our sole discretion.  Performance is based on measurements and projections using standard IBM benchmarks in a controlled environment. The actual throughput or performance that any user will experience will vary depending upon many factors, including considerations such as the amount of multiprogramming in the user’s job stream, the I/O configuration, the storage configuration, and the workload processed. Therefore, no assurance can be given that an individual user will achieve results similar to those stated here.
  • 3. IBM Cloud3 RDBMS vs NoSQL 3 <?xml version="1.0" encoding="UTF-16" ?> <Instrument> <Id>I100</Id> <ProductType>VarianceSwap</ProductType> <ProductCurrency>GBP</ProductCurrency> <Quantity>10000.50</Quantity> <ExpiryDate>2018-03-31</ExpiryDate> <StrikePrice>75.35</StrikePrice> <ObservationSchedule> </Observation date="2018-01-01" time="AM"> </Observation date="2018-02-01" time="AM"> </Observation date="2018-03-01" time="AM"> </Observation date="2018-03-31" time="PM"> </ObservationSchedule> </Instrument> { "Id":"I100", "ProductType":"VarianceSwap", "ProductCurrency":"GBP", "Quantity":["10000.50"], "ExpiryDate":"2018-03-31", "StrikePrice":"75.35", "ObservationSchedule":[ {"ObservationDate" : "2018-01-01","ObservationTime" : "AM"}, {"ObservationDate" : "2018-02-01","ObservationTime" : "AM"}, {"ObservationDate" : "2018-03-01","ObservationTime" : "AM"}, {"ObservationDate" : "2018-03-31","ObservationTime" : "PM"} ] } ID PRODUCT_TYPE PRODUCT_CURRENCY QUANTITY EXPIRY_DATE STRIKE_PRICE I100 VarianceSwap GBP 10000.50 2018-03-31 75.35 ID OBSERVATION_DATE OBSERVATION_TIME I100 2018-01-01 AM I100 2018-02-01 AM I100 2018-03-01 AM I100 2018-03-31 PM XML JSON Relational
  • 4. IBM Cloud4 RDBMS vs NoSQL 4 <?xml version="1.0" encoding="UTF-16" ?> <Instrument> <Id>I100</Id> <ProductType>VarianceSwap</ProductType> <ProductCurrency>GBP</ProductCurrency> <Quantity>10000.50</Quantity> <Quantities> <Quantity>10000.50</Quantity> <Quantity>50000.00</Quantity> <Quantities> <ExpiryDate>2018-03-31</ExpiryDate> <StrikePrice>75.35</StrikePrice> <ObservationSchedule> </Observation date="2018-01-01" time="AM"> </Observation date="2018-02-01" time="AM"> </Observation date="2018-03-01" time="AM"> </Observation date="2018-03-31" time="PM"> </ObservationSchedule> </Instrument> { "Id":"I100", "ProductType":"VarianceSwap", "ProductCurrency":"GBP", "Quantity":["10000.50","50000.00"], "ExpiryDate":"2018-03-31", "StrikePrice":"75.35", "ObservationSchedule":[ {"ObservationDate" : "2018-01-01","ObservationTime" : "AM"}, {"ObservationDate" : "2018-02-01","ObservationTime" : "AM"}, {"ObservationDate" : "2018-03-01","ObservationTime" : "AM"}, {"ObservationDate" : "2018-03-31","ObservationTime" : "PM"} ] } ID PRODUCT_TYPE PRODUCT_CURRENCY QUANTITY EXPIRY_DATE STRIKE_PRICE I100 VarianceSwap GBP 10000.50 2018-03-31 75.35 ID OBSERVATION_DATE OBSERVATION_TIME I100 2018-01-01 AM I100 2018-02-01 AM I100 2018-03-01 AM I100 2018-03-31 PM ID QUANTITY I100 10000.50 I100 50000.00 XML JSON Relational
  • 5. IBM Cloud5 Publishing Functions Comments JSON_ARRAY Creates JSON array from input key value pairs JSON_OBJECT Creates JSON object from input key value pairs Retrieval Functions Comments JSON_QUERY Extract a JSON object from a JSON object JSON_VALUE Extract an SQL scalar value from a JSON object JSON_EXISTS Determines whether or not a value exists in a document JSON_TABLE Creates relational output from a JSON object Conversion Function Comments BSON_TO_JSON Convert BSON formatted document into JSON strings JSON_TO_BSON Convert JSON strings into a BSON document format New ISO JSON SQL Functions Lot's of New Capabilities! Take JSON Hands on Lab: ibm.com/demos/collection/db2-database
  • 6. IBM Cloud6 Storage  You choose the format: JSON or BSON  There is no "native" JSON data type and one is not specified by the standard  You choose the table organization: row or column (where supported)  You choose the column data type: • By default, Db2 will assume character data types are JSON and binary ones are BSON  Try to "inline" the columns if possible to provide better performance CREATE TABLE T1 (C1 VARCHAR(300)) CREATE TABLE T1 (C1 BLOB(512) INLINE LENGTH 512)  Complimentary (but optional) conversion functions are provided to move between JSON and BSON if so desired although you can also use other products to do this SYSIBM.BSON_TO_JSON SYSIBM.JSON_TO_BSON
  • 7. IBM Cloud7 JSON Document Structure  JSON documents have an inherent structure to them  Many of the JSON functions provided with Db2 need a method to navigate through a document to retrieve the object or item that the user wants  To illustrate how a JSON path expression points to a particular object, one of the records of the customer document is shown: { "customerid": 100000, "identity": { "firstname": "Jacob", "lastname": "Hines", "birthdate": "1982-09-18" }, "contact": { "street": "Main Street North", "city": "Amherst", "state": "OH", "zipcode": "44001", "email": "[email protected]", "phone": "813-689-8309" }, "payment": { "card_type": "MCCD", "card_no": "4742-3005-2829-9227" }, "purchases": [ { "tx_date": "2018-02-14", "tx_no": 157972, "product_id": 1860, "product": "Ugliest Snow Blower", "quantity": 1, "item_cost": 51.86 }, ... additional purchases ... ] } Document customerid identity firstname lastname birthdate contact street city state zipcode email phone payment card_type card_no purchases* tx_date tx_no product_id product quantity item_cost
  • 8. IBM Cloud8 JSON Path Expression  Every JSON path expression begins with a dollar sign ($) to represent the root or top of the document structure  To traverse down the document, the dot/period (.) is used to move down one level  The asterisk (*) represents all values that are found in the object  The dollar sign and period are reserved characters for the purposes of path expressions  The LAX and STRICT modifiers are used to control the matching behavior of the JSON path evaluation
  • 9. IBM Cloud9 JSON Path Examples  To retrieve the value associated with the identity key, the path expression would be: $.identity  The value referred to in this last example is the entire JSON object { "firstname": "Jacob", "lastname" : "Hines", "birthdate": "1982-09-18" }  To refer to the birthdate, then we would append the internal key name $.identity.birthdate ➡️ "1982-09-18"  To reference the first element of an array, you would append an array specifier [ ] $.purchases[0].product ➡️ "Ugliest Snow Blower" Take JSON Hands on Lab: ibm.com/demos/collection/db2-database
  • 10. IBM Cloud10 JSON Conversion Functions  If you decide to store the data in binary format, you must use the JSON_TO_BSON function to convert the JSON into the proper format  You also have the option of using an external BSON library to convert the string and insert the value directly into the column (i.e. Db2 is not involved in the conversion)  Documents are checked for validity (proper JSON) when using the JSON_TO_BSON function  Documents that are stored as character strings are NOT checked for validity until it is used in a JSON function
  • 11. IBM Cloud11 JSON_EXISTS: Checking for Key-Value Pairs  JSON_EXISTS allows you to check whether or not a valid JSON key exists within a document for the provided search path  Example VALUES JSON_EXISTS(customer, '$.identity.middlename') ➡️ False  The ON ERROR clause of the JSON_EXISTS function determines what value should be returned when an error occurs
  • 12. IBM Cloud12 JSON_EXISTS: Examples c = { "empno":"000070", "firstnme":"EVA", "midinit":"D", "lastname":"PULASKI", "workdept":"D21", "phoneno":[7831,1422,4567], "hiredate":"09/30/2005", "job":"MANAGER", "edlevel":16, "sex":"F", "birthdate":"05/26/2003", "pay": { "salary":96170.00, "bonus":700.00, "comm":2893.00 } } JSON_EXISTS(c,'$.empno') ➡️ true JSON_EXISTS(c,'$.phoneno[0]') ➡️ true JSON_EXISTS(c,'$.middleinit') ➡️ false JSON_EXISTS(c,'$.pay') ➡️ true JSON_EXISTS(c,'$.phoneno[999]' TRUE ON ERROR) ➡️ true Take JSON Hands on Lab: ibm.com/demos/collection/db2-database
  • 13. IBM Cloud13 JSON_VALUE: Retrieving Individual Values  The JSON_VALUE function is used to retrieve a single value from a JSON document in the form of a "native" SQL data type  This function implicitly converts the returning value from its original JSON format to the identified Db2 data type  Since it is a scalar function, JSON_VALUE can only return a single value and will return an error if there are multiple values found
  • 14. IBM Cloud14 JSON_VALUE: Examples c = { "empno":"000070", "firstnme":"EVA", "midinit":"D", "lastname":"PULASKI", "workdept":"D21", "phoneno":[7831,1422,4567], "hiredate":"09/30/2005", "job":"MANAGER", "edlevel":16, "sex":"F", "birthdate":"05/26/2003", "pay": { "salary":96170.00, "bonus":700.00, "comm":2893.00 } } JSON_VALUE(c,'$.empno') ➡️ '000070' JSON_VALUE(c,'$.empno' RETURNING INT) ➡️ 70 JSON_VALUE(c,'$.middle' DEFAULT '?' ON EMPTY) ➡️ '?' JSON_VALUE(c,'strict $.middle' DEFAULT '?' ON EMPTY) ➡️ null JSON_VALUE(c,'$.phoneno[999]' DEFAULT 0 ON EMPTY) ➡️SQL0440N No authorized routine named "CLOB" of type "FUNCTION" having compatible arguments was found. SQLSTATE=42884 SQLCODE=-440 Take JSON Hands on Lab: ibm.com/demos/collection/db2-database
  • 15. IBM Cloud15 JSON_QUERY: Retrieving Objects and Arrays  JSON_VALUE is limited to retrieving atomic or individual values from within a document  In order to extract native JSON values, which can include complex ones such as multiple array values or entire JSON objects, you must use the JSON_QUERY function  The json-expression, and json-path-expression are identical to the JSON_VALUE function  Two additional clauses are added for dealing with objects:  Wrapper clause for dealing with arrays  Quotes clause for handling character string output
  • 16. IBM Cloud16 JSON_QUERY: Examples c = { "empno":"000070", "firstnme":"EVA", "midinit":"D", "lastname":"PULASKI", "workdept":"D21", "phoneno":[7831,1422,4567], "hiredate":"09/30/2005", "job":"MANAGER", "edlevel":16, "sex":"F", "birthdate":"05/26/2003", "pay": { "salary":96170.00, "bonus":700.00, "comm":2893.00 } } JSON_QUERY(c,'$.pay') ➡️ { 'salary': 96170.0, 'bonus': 700.0, 'comm': 2893.0 } JSON_QUERY(c,'$.pay.bonus') ➡️ '700.0' JSON_QUERY(c,'$.phoneno[0]') ➡️ 7831 JSON_QUERY(c,'$.phoneno[0]' WITH CONDITIONAL WRAPPER) ➡️ [7831] JSON_QUERY(c,'$.phoneno[*]' WITH CONDITIONAL WRAPPER) ➡️ [7831,1422,4567]
  • 17. IBM Cloud17 JSON_TABLE: Retrieving Documents as a Table  JSON_VALUE and JSON_OBJECT can be used individually to retrieve all of the values within a JSON document, but an easier method exists with the JSON_TABLE function  This function does not yet implement all of the ISO JSON_TABLE function definition but it can help simplify retrieval of multiple object in a document  The JSON_TABLE function has two ways of publishing column values  Regular column expressions mimic the JSON_VALUE function  Formatted column expressions use features from the JSON_QUERY function
  • 18. IBM Cloud18 JSON_TABLE: Column Expressions  The body of the JSON_TABLE function includes the list of columns that you want created  Each of these formats uses the same column name, data type and path definitions  The column can be defined in one of two ways:  A column name derived from a JSON path expression and a data type "forward.primary.last_name" VARCHAR(20)  A SQL column name with a data type and a JSON path expression NAME VARCHAR(20) FORMAT JSON PATH "$.forward.primary.last_name"  The first method can be a convenient short cut when your JSON document has most of the data at the root ($.) level  The column names can become extremely long if you have multi-level objects Regular Column Expression Formatted Column Expression
  • 19. IBM Cloud19 JSON_TABLE: Examples book = { "authors": [ {"first":"Paul", "last":"Bird"}, {"first":"George","last":"Baklarz"} ], "foreword": { "primary": {"first":"Thomas","last":"Hronis"} }, "formats": { "hardcover": 19.99, "paperback": 9.99, "ebook" : 1.99, "pdf" : 1.99 } } SELECT T.* FROM JSON_TABLE(:book, 'strict $' COLUMNS( "authors[0].first" VARCHAR(20), "authors[0].last" VARCHAR(20)) ERROR ON ERROR) AS T authors[0].first authors[0].last ---------------- --------------- Paul Bird SELECT T.* FROM JSON_TABLE(:book, 'strict $' COLUMNS( FIRST_NAME VARCHAR(20) PATH '$.authors[1].first', LAST_NAME VARCHAR(20) PATH '$.authors[1].last' ) ERROR ON ERROR) AS T FIRST_NAME LAST_NAME ------------------- -------------------- George Baklarz
  • 20. IBM Cloud20 JSON_OBJECT: Publishing Objects  The JSON_OBJECT function will generate a JSON object by creating key:value pairs  Objects can be created at at multiple levels by nesting the JSON_OBJECT function  The key:value pairs are generated using the following syntax:
  • 21. IBM Cloud21 JSON_ARRAY: Publishing Arrays  In order to create arrays, we must use the JSON_ARRAY function  There are two forms of the JSON_ARRAY function  The first version is similar to the JSON_OBJECT function where you supply a list of values to create an array  The second form of the JSON_ARRAY function uses the results of a SQL select statement to build the array values
  • 22. IBM Cloud22 JSON_ARRAY: Creating an Array with Values  The first form of the JSON_ARRAY function requires a list of values to create an array  There is no key associated with a JSON array, so you only need to supply the list of values that you want published VALUES JSON_ARRAY( 1523, 902, 'Thomas', 7777) Result: [1523,902,"Thomas",7777] JSON array elements do not need to have the same data type Array values can contain other objects VALUES JSON_ARRAY(1523, 902, JSON_OBJECT( KEY 'lastname' VALUE 'Bird') FORMAT JSON, 7777) Result: [1523,902,{"lastname":"Bird"},7777]  While the JSON_ARRAY function can be used by itself, it does not create a proper JSON document  The output from this function is meant to be used as part of a JSON_OBJECT structure
  • 23. IBM Cloud23 JSON_ARRAY: Creating an Array with an SQL Statement  The second form of the JSON_ARRAY function uses the results of a SQL select statement to build the array values  Only one SELECT statement can be used in the body of the function VALUES JSON_OBJECT(KEY 'departments' VALUE JSON_ARRAY(SELECT DEPTNO FROM DEPARTMENT WHERE DEPTNAME LIKE 'B%') FORMAT JSON) Result: {"departments":["F22","G22","H22","I22","J22"]}  If you do need to create an array from multiple sources, you should look at using a SELECT statement with UNION to create one list of items
  • 24. IBM Cloud24 Performance: Using Indexes  Leveraging Db2's index on expression capability allows us to create indexes on JSON documents to allow faster access  Example: Searching for an employee number will result in a scan against the table if no indexes are defined: SELECT JSON_VALUE(EMP_DATA, '$.lastname' RETURNING CHAR(20)) AS LASTNAME FROM JSON_EMP WHERE JSON_VALUE(EMP_DATA, '$.empno' RETURNING CHAR(6)) = '000010'  Creating the following index will greatly improve performance of this query CREATE INDEX IX_JSON ON JSON_EMP (JSON_VALUE(EMP_DATA, '$.empno' RETURNING CHAR(6)); versus Statements Executed in 30 second interval
  • 25. IBM Cloud25 Maintenance: SYSTOOLS.JSON_UPDATE  The ISO JSON standard does not currently provide an update function  It is left up to the application developer to retrieve the entire document and update it externally and then re-insert (or update) the JSON document in the database  The JSON_UPDATE function is part of the SYSTOOLS schema and allows for in-place updating of a document  It requires the user or application be granted EXECUTE privilege on the function  Must explicitly qualify any reference to the function with the SYSTOOLS schema  The syntax of the JSON_UPDATE function is: JSON_UPDATE(document, '{$set : {field:value}}') '{$unset: {field:null}}'  The arguments are:  document – BSON document  operation ($set or $unset)  key – The key we are looking for
  • 26. IBM Cloud26IBM Digital Technical Engagement Thank You ! Seem more on Db2 @ IBM.COM/Demos/collection/db2-database Take JSON Hands on Lab: ibm.com/demos/collection/db2-database