To retrieve all rows from a PostgreSQL table where the stp_extra JSON column contains the kmalopolskie key within the schedule_metadata sub-object of shared_metadata, you can use the following SQL query:
SELECT *
FROM your_table
WHERE stp_extra -> 'shared_metadata' -> 'schedule_metadata' ? 'kmalopolskie';
Explanation
stp_extra: This is the JSON column in your table.
->: This operator extracts a JSON object or array element by key or index.
?: This operator checks whether the JSON object contains the specified key.
Step-by-step breakdown:
stp_extra -> 'shared_metadata': Extracts the shared_metadata object from the JSON.
-> 'schedule_metadata': Extracts the schedule_metadata object from shared_metadata.
? 'kmalopolskie': Checks if the schedule_metadata object contains the kmalopolskie key.
This ensures that only rows with a valid kmalopolskie key in the specified location are returned.
Notes
- This query assumes that the
stp_extra column is of type json (not jsonb). If it were jsonb, the same syntax would still work.
- If the
shared_metadata or schedule_metadata keys are missing, the result of -> would be NULL, and the ? operator would return false as expected.
- If you want to check for the presence of a key and its value, you could use
@> or #>>, but for just checking the existence of the key, ? is the most appropriate.
Example
Given the JSON:
{
"shared_metadata": {
"status": "ForReview",
"schedule_metadata": {
"pl_rail_map": {
"fullcode": "PLK80416",
"position": {
"x": 19.947803,
"y": 50.0686131
}
},
"kmalopolskie": {
"fullcode": "80416",
"position": {
"x": 19.9475035,
"y": 50.0683947
}
},
"pkp_intercity": {
"fullcode": "80416",
"position": null
}
}
}
}
The query would return this row because kmalopolskie exists in schedule_metadata.
If a row had a missing or different structure, it would not match.