Application monitoring that helps developers get it done.
Deploy apps to servers that you own and control.
The final topic I want to explore is how to use JSON columns for advanced analytical queries.
Let’s jump back into our playground, where we have our posts table with a metadata JSON column. After getting everything set up, I’ll insert a couple of posts so we have some data to work with.
If your table contains a JSON column, you might need to analyze the data to gain higher-level insights into what’s stored. In these cases, you’ll likely need to use table-value functions that SQLite provides for working with JSON data.
Let’s break down an example query that extracts and aggregates engagement data from the JSON column:
Post.connection.execute(<<~SQL)
SELECT
engagements.key AS metric,
SUM(CAST(engagements.value as INTEGER)) AS total_count,
AVG(CAST(engagements.value as INTEGER)) AS average_count,
COUNT(*) AS total_posts,
FROM posts,
json_each(posts.metadata, '$.engagement') AS engagements
GROUP BY engagements.key
ORDER BY total_count DESC;
SQL
This query:
The json_each function allows us to treat part of a JSON column like a regular table. This means we can select, group, and order JSON values just as we would with standard table data.
When we execute the query, we get useful engagement metrics:
Engagement Type | Total Posts | Total Engagements | Average Engagements |
---|---|---|---|
Clicks | 2 | 54 | 27 |
Shares | 2 | 13 | 6.5 |
Saves | 2 | 6 | 3 |
This aggregated data can be useful for:
While JSON columns offer great flexibility for read-heavy data, they are not ideal for frequent updates. If you need to modify JSON data often, it’s better to use a standard SQL table with structured columns.
That wraps up our introduction to Active Record with SQLite! Up next, we’ll build a full Rails 8 application using SQLite, applying everything we’ve learned to a real-world production-grade app.