Query nested arrays in PostgreSQL JSON data

The following is an example showing how to query multiple nested arrays in JSON data in a PostgreSQL database.

Given

CREATE TABLE sample_json (
  id serial PRIMARY KEY,
  name varchar(64),
  json_data json
);


INSERT INTO sample_json (name, json_data)
VALUES
	(
	'NA',
	'
	{
	    "location": "US",
	    "topLevelArray": [
	        {
	            "id": 1,
	            "secondLevelArray": [
	                {
	                    "key": "someKey",
	                    "operator": "=",
	                    "value": 10
	                },
	                {
	                    "key": "foo",
	                    "operator": ">=",
	                    "value": 5
	                },
	                {
	                    "key": "someOtherKey",
	                    "operator": ">",
	                    "value": 647
	                }
	            ]
	        },
	        {
	            "id": 
Continue reading “Query nested arrays in PostgreSQL JSON data”

Query for Finding the nth Element in a PostgreSQL JSONB Array that Matches a Specified Value

The following is a sample query that you can use to search for rows that have the nth element in a JSONB array that match a specific value.

Given

CREATE TABLE sample_jsonb (
  id serial PRIMARY KEY,
  name varchar(64),
  json_data jsonb
);

INSERT INTO sample_jsonb(name, json_data)
VALUES
  ('foo',
  '{
  "key": "val1",
  "arr": ["homer", "bart", "barney"]
  }'),
  ('bar',
  '{
  "key": "val2",
  "arr": ["marge", "lisa", "maggie"]
  }'),
  ('baz',
  '{
  "key": "val2",
  "arr": ["bart", "milhouse", "nelson"]
  }')
;

We now have two records → Continue reading “Query for Finding the nth Element in a PostgreSQL JSONB Array that Matches a Specified Value”

Query for Finding an Element in a PostgreSQL JSONB Array

The following is a sample query that you can use to search for rows that have an element in a JSONB array.

Given

CREATE TABLE sample_jsonb (
  id serial PRIMARY KEY,
  name varchar(64),
  json_data jsonb
);

INSERT INTO sample_jsonb(name, json_data)
VALUES
  ('foo',
  '{
  "key": "val1",
  "arr": ["homer", "bart", "barney"]
  }'),
  ('bar',
  '{
  "key": "val2",
  "arr": ["marge", "lisa", "maggie"]
  }')
;

select count(*) from sample_jsonb where json_data-'arr' ? 'marge';
Continue reading “Query for Finding an Element in a PostgreSQL JSONB Array”

PostgreSQL Query to Find Tables With Name LIKE

Sometimes you are working with a PostgreSQL database with A LOT of tables and looking for tables that contain a sub-string in their name. Following is a query that you can run that will return all of the tables that have the string in their name:

SELECT
  table_schema,
  table_name
FROM
  information_schema.tables
WHERE
      table_name LIKE '%<string%'
  AND table_schema not in ('information_schema', 'pg_catalog')
  AND table_type = 'BASE TABLE'
ORDER BY
  table_name, table_schema
;
Continue reading “PostgreSQL Query to Find Tables With Name LIKE”

Solution for MySQL ERROR 1396 (HY000): Operation CREATE USER failed for

This indicates that the user already exists, or did exist but that all of the data for that user has not been deleted.

As the mysql root user:

REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'user'@'hostname';
DROP USER 'user'@'hostname'

Then re-try creating the user.→ Continue reading “Solution for MySQL ERROR 1396 (HY000): Operation CREATE USER failed for”

Backspace, Delete, and/or Return Key Stops Working in Oracle SQL Developer

So, I fire up SQL Developer to run some queries against a QC server and for some reason, I am no longer able to use the backspace, delete, or return keys to edit .sql files opened in the program.

I tried opening a new .sql file, and restarting SQL Developer.  I then tried restarting Windows.  None of those worked.

After a bit of searching I found a forum posting that indicated by going to Tools/Preferences/Accelerators and clicking the “Load Preset…” → Continue reading “Backspace, Delete, and/or Return Key Stops Working in Oracle SQL Developer”

Unable to Set the Path To java.exe When Running Oracle SQL Developer Under Windows 7

I was trying to run Oracle SQL Developer for the first time on a new machine.  When firing it up, it presented me with a dialog box asking me to “Enter the full pathname for the java.exe file”.

OK, no problem.  So I find the path to the java.exe binary that was just installed with the SDK.  Hit submit . . . and nothing happens.  It blanks out the text field and the dialog box stares back at me.

I → Continue reading “Unable to Set the Path To java.exe When Running Oracle SQL Developer Under Windows 7”

Executing Dynamically Generated SQL Queries in a Shell Script and Saving the Output to a Variable

If you would like to, in a shell script, dynamically generate SQL queries for MySQL and save the output of those queries to a variable that you can then use in the script, here is an example:

#!/bin/bash

for i in `cat tables_list.txt`
do

   # Build the query
   QUERY="SELECT count(*) FROM ${i}"

   # Run the query from the command-line and save the
   # output into the $ROW_COUNT variable
   ROW_COUNT=$(echo $QUERY | mysql -u${USER_NAME} -p${PASSWORD} -h ${HOST} -P ${PORT} --skip-column-names ${DBASE})

   
Continue reading “Executing Dynamically Generated SQL Queries in a Shell Script and Saving the Output to a Variable”

Figuring out MySQL ERROR 1005 (HY000) Can’t create table (errno: 150)

So I’m dumping a database on a remote server to pull down to my local box to do some development.  When loading the mysqldump file I encountered the error:

ERROR 1005 (HY000) at line 8680: Can't create table 'database.table' (errno: 150)

After doing some searching online it seems that is one of the notoriously cryptic MySQL error messages that is woefully overloaded.

I did manage to fix the error (which ended up being a foreign key reference from another table → Continue reading “Figuring out MySQL ERROR 1005 (HY000) Can’t create table (errno: 150)”

Executing MySQL Queries and Commands from the Command Line to a Remote Server

Following are a couple of ways to execute SQL on a remote MySQL server via the shell.

Executing SQL directly from the command line:

$ mysql -u uid -p -h remote.host database -e ‘SQL query here;’

Executing SQL from a file on the local host on the remote server:

$ mysql -u uid -p -h remote.host database < file.sql

You can also connect to the remote mysql server and from the command line execute SQL from files on the local → Continue reading “Executing MySQL Queries and Commands from the Command Line to a Remote Server”