- 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
- JavaScript Interview Questions for 5+ Years Experience
- JavaScript Interview Questions for 2–5 Years Experience
- JavaScript Interview Questions for 1–2 Years Experience
- JavaScript Interview Questions for 0–1 Year Experience
- JavaScript Interview Questions For Fresher
- SQL Interview Questions for 5+ Years Experience
- 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
Random Blogs
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- Exploratory Data Analysis On Iris Dataset
- What to Do When Your MySQL Table Grows Too Wide
- How to Start Your Career as a DevOps Engineer
- Ideas for Content of Every niche on Reader’s Demand during COVID-19
- Navigating AI Careers in 2025: Data Science, Machine Learning, Deep Learning, and More
- String Operations in Python
- Internet of Things (IoT) & AI – Smart Devices and AI Working Together
- Store Data Into CSV File Using Python Tkinter GUI Library
- Best Platform to Learn Digital Marketing in Free
- Mastering Python in 2025: A Complete Roadmap for Beginners
- Top 10 Knowledge for Machine Learning & Data Science Students
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- The Beginner’s Guide to Normalization and Denormalization in Databases
- 15 Amazing Keyword Research Tools You Should Explore
Datasets for Machine Learning
- Awesome-ChatGPT-Prompts
- 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