- Advanced SQL
-
Overview
- Indexing for Performance Optimization
- Transactions and ACID Properties
- Triggers and Event Scheduling in SQL
- Window Functions and Ranking
- Pivoting Data in SQL
- JSON and XML Data Handling
- Recursive Queries in SQL
- Performance Tuning and Query Optimization
- Role-Based Access Control in Databases
- Handling Large Datasets in SQL
JSON and XML Data Handling
Add to BookmarkIntroduction
Modern databases often need to store, query, and manipulate semi-structured data formats like JSON (JavaScript Object Notation) and XML (Extensible Markup Language). These formats allow flexibility in handling nested and hierarchical data. SQL databases provide built-in functions to store and work with JSON and XML efficiently.
This tutorial explores how different databases handle JSON and XML, including storage, querying, and transformation.
Why Use JSON and XML in SQL?
JSON:
- Lightweight and widely used in APIs.
- Stores nested data without needing multiple relational tables.
- Easier integration with web applications.
XML:
- Useful for structured data exchange in enterprise applications.
- Supports metadata and complex hierarchies.
- Commonly used in legacy systems and document-based storage.
Working with JSON in SQL
1. Storing JSON Data
Most modern relational databases support JSON as a native data type.
MySQL (JSON Data Type)
CREATE TABLE orders (
id INT PRIMARY KEY AUTO_INCREMENT,
customer_name VARCHAR(100),
order_details JSON
);
Here, order_details
can store nested JSON objects like:
{
"product": "Laptop",
"price": 1200,
"quantity": 2
}
PostgreSQL (JSON and JSONB Data Types)
CREATE TABLE products (
id SERIAL PRIMARY KEY,
details JSONB
);
- JSON: Stores data as a plain text string.
- JSONB: Stores data in a binary format, making queries faster.
2. Querying JSON Data
Databases provide functions to extract values from JSON fields.
Extracting JSON Values (MySQL)
SELECT customer_name, order_details->>'$.product' AS product
FROM orders;
order_details->>'$.product'
extracts the value of"product"
from the JSON object.
PostgreSQL JSON Functions
SELECT details->>'name' AS product_name FROM products;
Filtering with JSON Fields
SELECT * FROM orders WHERE order_details->>'$.price' > 1000;
3. Updating JSON Data
You can modify JSON objects inside SQL tables.
Updating a JSON Field in MySQL
UPDATE orders
SET order_details = JSON_SET(order_details, '$.price', 1400)
WHERE id = 1;
Updating a JSONB Field in PostgreSQL
UPDATE products
SET details = jsonb_set(details, '{price}', '1400')
WHERE id = 1;
Working with XML in SQL
1. Storing XML Data
SQL databases allow XML storage using the XML
data type.
SQL Server Example
CREATE TABLE employees (
id INT PRIMARY KEY,
employee_data XML
);
Example XML data:
<Employee>
<Name>John Doe</Name>
<Department>HR</Department>
</Employee>
MySQL XML Storage (TEXT Format)
CREATE TABLE documents (
id INT PRIMARY KEY,
data TEXT
);
XML is stored as a TEXT
field in MySQL.
2. Querying XML Data
Extracting Data from XML (SQL Server)
SELECT employee_data.value('/Employee/Name[1]', 'VARCHAR(100)') AS EmployeeName
FROM employees;
Extracting Data in MySQL (Using XPath)
SELECT ExtractValue(data, '/Employee/Department') AS Department FROM documents;
3. Updating XML Data
Modifying XML in SQL Server
UPDATE employees
SET employee_data.modify('replace value of (/Employee/Department/text())[1] with "IT"')
WHERE id = 1;
Updating XML in MySQL
UPDATE documents
SET data = REPLACE(data, '<Department>HR</Department>', '<Department>IT</Department>')
WHERE id = 1;
JSON vs. XML in SQL: A Comparison
Feature | JSON | XML |
---|---|---|
Readability | More human-readable | Verbose and complex |
Storage Efficiency | Compact | Larger size |
Query Performance | Fast with JSONB (PostgreSQL) | Slower due to hierarchy |
Use Case | APIs, logs, configurations | Document storage, enterprise apps |
Conclusion
- JSON is preferred for lightweight and flexible data exchange, especially for modern web applications.
- XML is useful for hierarchical data storage in enterprise applications.
- SQL databases provide built-in functions for querying and modifying both JSON and XML.
Choosing between JSON and XML depends on the application’s needs and database capabilities.
Prepare for Interview
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
Random Blogs
- 5 Ways Use Jupyter Notebook Online Free of Cost
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Python Challenging Programming Exercises Part 1
- Time Series Analysis on Air Passenger Data
- Create Virtual Host for Nginx on Ubuntu (For Yii2 Basic & Advanced Templates)
- Datasets for Speech Recognition Analysis
- Convert RBG Image to Gray Scale Image Using CV2
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- Exploratory Data Analysis On Iris Dataset
- Google’s Core Update in May 2020: What You Need to Know
- The Ultimate Guide to Machine Learning (ML) for Beginners
- Deep Learning (DL): The Core of Modern AI
- Top 15 Recommended SEO Tools
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
- What is YII? and How to Install it?
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset