Reference: https://www.postgresql.org/docs/current/functions-json.html
I'm looking through this and I'm not seeing what I am looking for, but what I want to do is this. I have a Java application that generates an object:
{"first":"Joe","last":"Doe"}
I want to query the database to find json objects with these fields. These fields are NOT static (I could have n fields and they can all be different).
select op.*
from bw.people p
where p.object_as_json = '{"first":"Joe","last":"Doe"}' -- this clearly doesn't work
Update
object_as_json is now a jsonb data type
One entry in person table, has
object_as_json ='{"first":"Joe","last":"Doe","middle":"S","DOB":"1940-01-01"}'
My queries were (neither of these returned anything):
select *
from bw.people
where object_in_json = '{"last":"Doe","first":"Joe"}'
select *
from bw.people
where object_in_json = '{"first":"Joe","last":"Doe","middle":"S","DOB":"1940-01-01"}'
If you used jsonb, you could write
WHERE object_in_json #> '{"last":"Doe","first":"Joe"}`
With json you'll have to write
WHERE object_in_json ->> 'last' = 'Doe'
AND object_in_json ->> 'first' = 'John'
Related
So I have a table
Node_Mapping(location_id:UUID, node_ids: jsonb)
The corresponding POJO for this is
class NodeMapping{
UUID locationId;
Set<String> nodeIds;
}
Example data in table is
UUID1 : ['uuid100', 'uuid101']
UUID2 : ['uuid103', 'uuid101']
So I want to make a query like, find out all the locationIds which contains 'uuid101'.
Please help me to form the query.
You can use the contains operator ?
select *
from node_mapping
where node_ids ? 'uuid100';
This assumes that in reality the column stores a valid JSON array, e.g. ["uuid100", "uuid101"] but not an invalid JSON like UUID1 : ['uuid100', 'uuid101']
In Oracle, Datatype is vArchar and we have some ID's stored in format 0000123. From source we are getting ID as 123 or 1234 with preceding 0. In some cases data is stored simply as 123.
In SQL Query i can simply use
Select * from Table where ID = 123 (It wil fetch even if 000123 id is present)
Is there way to achieve it using Named Query through hibernate as currently in oracle, it is String against Varchar and when searching 123 does not return correct results.?
The query translates automatically to the following:
Select * from Table where TO_NUMBER(ID) = 123
so you can use that instead.
You can also use:
SELECT * from Table where LTRIM(ID,'0') = LTRIM(123,'0')
if there are non numerical values in the ID column.
If you are getting an error while applying Radagast81's answer then try to convert the number to varchar using to_char() as following:
SELECT
*
FROM
EMPS
WHERE
LTRIM(EMP_NAME, '0') = TO_CHAR(LTRIM(123, '0'));
You can also use LPAD to achieve the same:
SELECT
*
FROM
EMPS
WHERE
EMP_NAME = LPAD(123, LENGTH(EMP_NAME), '0'));
Cheers!!
If you can assign a default number which does not exists in table, you can use it. see the example below:
Select * from Table where TO_NUMBER(ID DEFAULT -999999999999 ON CONVERSION ERROR ) = 123
I am retrieving data from database using jdbc. In my code I am using 3-4 tables to get data. But sometimes if table is not present in database my code gives exception. How to handle this situation. I want my code to continue working for other tables even if one table is not present. Please help.
I have wrote a code like this
sql="select * from table"
now Result set and all.
If table is not present in database it give exception that no such table. I want to handle it. In this code I cannot take tables which are already present in advance . I want to check here itself if table is there or not.
Please do not mark it as a duplicate question. The link you shared doesnot give me required answer as in that question they are executing queries in database not through JDBC code
For Sybase ASE the easiest/quickest method would consist of querying the sysobjects table in the database where you expect the (user-defined) table to reside:
select 1 from sysobjects where name = 'table-name' and type = 'U'
if a record is returned => table exists
if no record is returned => table does not exist
How you use the (above) query is up to you ...
return a 0/1-row result set to your client
assign a value to a #variable
place in a if [not] exists(...) construct
use in a case statement
If you know for a fact that there won't be any other object types (eg, proc, trigger, view, UDF) in the database with the name in question then you could also use the object_id() function, eg:
select object_id('table-name')
if you receive a number => the object exists
if you receive a NULL => the object does not exist
While object_id() will obtain an object's id from the sysobjects table, it does not check for the object type, eg, the (above) query will return a number if there's a stored proc named 'table-name'.
As with the select/sysobjects query, how you use the function call in your code is up to you (eg, result set, populate #variable, if [not] exists() construct, case statement).
So, addressing the additional details provided in the comments ...
Assuming you're submitting a single batch that needs to determine table existence prior to running the desired query(s):
-- if table exists, run query(s); obviously if table does not exist then query(s) is not run
if exists(select 1 from sysobjects where name = 'table-name' and type = 'U')
begin
execute("select * from table-name")
end
execute() is required to keep the optimizer from generating an error that the table does not exist, ie, the query is not parsed/compiled unless the execute() is actually invoked
If your application can be written to use multiple batches, something like the following should also work:
# application specific code; I don't work with java but the gist of the operation would be ...
run-query-in-db("select 1 from sysobjects where name = 'table-name' and type = 'U'")
if-query-returns-a-row
then
run-query-in-db("select * from table-name")
fi
This is the way of checking if the table exists and drop it:
IF EXISTS (
SELECT 1
FROM sysobjects
WHERE name = 'a_table'
AND type = 'U'
)
DROP TABLE a_table
GO
And this is how to check if a table exists and create it.
IF NOT EXISTS (
SELECT 1
FROM sysobjects
WHERE name = 'a_table'
AND type = 'U'
)
EXECUTE("CREATE TABLE a_table (
col1 int not null,
col2 int null
)")
GO
(They are different because in table-drop a temporary table gets created, so if you try to create a new one you will get an exception that it already exists)
Before running the query which has some risk in table not existing, run the following sql query and check if the number of results is >= 1. if it is >= 1 then you are safe to execute the normal query. otherwise, do something to handle this situation.
SELECT count(*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'your_db_name') AND (TABLE_NAME = 'name_of_table')
I am no expert in Sybase but take a look at this,
exec sp_tables '%', '%', 'master', "'TABLE'"
Sybase Admin
Currently, I have a query that I run in my java code that displays just a simple grid output of columns with the corresponding data for those specific fields. I am reading 2 tables that all have the same column names. I need to add just 1 column to that grid, but the field name resides on a different table. How would I add this to my existing query?
This is my current query that I execute in the Java:
SELECT TRNSP_EQP_EIN, TRNSP_EQP_ID, PRE_EQP_ID, EQP_GRP, AAR_CT_C,
AAR_MCHDSG_C,BLD_D, REBLD_D
FROM EQ.TE_TRNSP_EQPACTV A
WHERE TRNSP_EQP_ID = ‘BNSF0000000123’
UNION
SELECT TRNSP_EQP_EIN, TRNSP_EQP_ID, PRE_EQP_ID, EQP_GRP, AAR_CT_C,
AAR_MCHDSG_C,BLD_D, REBLD_D
FROM EQ.TE_TRNSP_EQPHIST A
WHERE A.TRNSP_EQP_ID = ‘ABC0123’
ORDER BY TRNSP_EQP_EFF_TS
WITH UR
Below is the information that I am trying to add to the grid to the existing SQL.
Table: EQ.TE_LOCO_EQP
Field: DEL_RSN_CD
You need to provide us with the full field list of EQ.TE_LOCO_EQP to answer this question in full, yet I think you'll be able to manage with what I have provided you below. Replace what is in the square brackets ([]) with the field relevant for the join.
I agree with #Snowman in that you could easily research this one.
SELECT
*
FROM
(
SELECT
TRNSP_EQP_EIN
,TRNSP_EQP_ID
,PRE_EQP_ID
,EQP_GRP
,AAR_CT_C
,AAR_MCHDSG_C
,BLD_D
,REBLD_D
FROM
EQ.TE_TRNSP_EQPACTV A
WHERE
TRNSP_EQP_ID = ‘BNSF0000000123’
UNION
SELECT
TRNSP_EQP_EIN
,TRNSP_EQP_ID
,PRE_EQP_ID
,EQP_GRP
,AAR_CT_C
,AAR_MCHDSG_C
,BLD_D
,REBLD_D
FROM
EQ.TE_TRNSP_EQPHIST B
WHERE
A.TRNSP_EQP_ID = ‘ABC0123’
ORDER BY
TRNSP_EQP_EFF_TS
WITH UR /* No idea what this is? */
) X
LEFT JOIN
EQ.TE_LOCO_EQP Y
ON
X.[PRIMARY_KEY] = Y.[EQUIVELANT_FOREIGN_KEY]
I am using play framework for the first time and I need to link objects of the same type. In order to do so I have added a self referencing many to many relationship like this:
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="journal_predecessor", joinColumns={#JoinColumn(name="journal_id")}, inverseJoinColumns={#JoinColumn(name="predecessor_id")})
public List<Journal> journalPredecessor = new ArrayList<Journal>();
I obtain the table journal_predecessor which contains the two columns: journal_id and predecessor_id, both being FKs pointing to the primary key of the table journal.
My question is how can I query this table using raw queries if I am using H2 in-memory database. thanks!
Actually it was very easy. I just needed to create an instance of SqlQuery to create a raw query:
SqlQuery rawQuery = Ebean.createSqlQuery("SELECT journal_id from journal_predecessor where journal_id=" + successorId + " AND predecessor_id=" + predecessorId);
And because i just needed to check weather a row exists or not, I find the size of the set of the results returned by the query:
Set<SqlRow> sqlRow = rawQuery.findSet();
int rowExists = sqlRow.size();