Is there any function for finding the multiple particular values stored in array type column? - sql

I am looking for a function which can help me to query multiple input values on a particular column which stored as an array
Already tried using like function to search in a string
select *
from express_dwh.kengic_bag_seal_ad_json
where Sorter_id='KENGIC_1' and ad >='2019-08-21-0' and
wbns LIKE '%3008127238325%' OR wbns LIKE '%3008127259896%' OR wbns LIKE '%3008127263750%'
Error running query:
SYNTAX_ERROR: line 3:56: Left side of LIKE expression must evaluate to a varchar (actual: array(varchar))

You might be looking for the “overlaps” operator &&:
wbns && ARRAY[3008127238325,3008127259896,3008127263750]
Depending on the data type, you may need a cast like
wbns && ARRAY[3008127238325,3008127259896,3008127263750]::numeric[]

Related

How can I use an SQL aggregate function on data I directly input at the command line (e.g. AVG(1, 2, 3))?

How can I enter multiple values into an aggregate function using just data I enter at the command line? Say, in Postgres, I run the following.
SELECT AVG(2);
I'll get the correct answer, but I can't find a way to enter multiple values, such as below, without getting an error.
SELECT AVG(1,NULL,2,3);
I've tried wrapping the numbers in various brackets but to no effect. What's the syntax I'm missing?
EDIT: Additionally, is there a way to include NULLs in the input?
AVG() is an aggregate that operates over multiple rows. So you need to convert your comma separated list to one row per value to be able to use an aggregate like avg(). This could be done using e.g. string_to_table
select avg(num::numeric)
from string_to_table('1,2,3', ',') as x(num)
If you want to include a NULL value, you could add it to the list and convert it to null before casting it to a numeric value:
select avg(nullif(num, 'null')::numeric)
from string_to_table('1,2,3,4,null', ',') as x(num)

How to get value string with regexp in bigquery

Hi i have string in BigQuery column like this
cancellation_amount: 602000
after_cancellation_transaction_amount: 144500
refund_time: '2022-07-31T06:05:55.215203Z'
cancellation_amount: 144500
after_cancellation_transaction_amount: 0
refund_time: '2022-08-01T01:22:45.94919Z'
i already using this logic to get cancellation_amount
regexp_extract(file,r'.*cancellation_amount:\s*([^\n\r]*)')
but the output only amount 602000, i need the output 602000 and 144500 become different column
Appreciate for helping
If your lines in the input (which will eventually become columns) are fixed you can use multiple regexp_extracts to get all the values.
SELECT
regexp_extract(file,r'cancellation_amount:\s*([^\n\r]*)') as cancellation_amount
regexp_extract(file,r'. after_cancellation_transaction_amount:\s*([^\n\r]*)') as after_cancellation_transaction_amount
FROM table_name
One issue I found with your regex expression is that .*cancellation_amount won't match after_cancellation_transaction_amount.
There is also a function called regexp_extract_all which returns all the matches as an array which you can later explode into columns, but if you have finite values separating them out in different columns would be a easier.

Postgresql ERROR: operator does not exist: date ~~ unknown

When I do this query, I have no problems:
SELECT a.value, b.label AS campo, 'date' AS tipo
FROM contenido.field_value_textarea a
JOIN estructura.field b ON a.field=b.id
WHERE a.value LIKE '%aaa%'
contenido.field_value_textarea is character varying(2000)
But if I try to select from:
contenido.field_value_fecha which type is date I got this error message:
ERROR: operator does not exist: date ~~ unknown
What I'm trying to do is searching between different tables, each query select FROM it's table. Some tables use text values, textarea values, integer values, and it works, but when the value is date all fails. What can I do?
EDIT: By the way, my date values are like this: 2009-05-01
The ~~ operator is actually the LIKE operator.
You are trying to use an expression that looks like:
contenido.field_value_fecha.value LIKE '%aaaa%'
That is, you're trying to compare a date with a string (which, without the adequate context, is considered to be of type 'unknown'), and decide if the date looks like something.
If you actually want to do such a comparison, you need to convert the date to a string, which can be done by means of:
contenido.field_value_fecha.value::text LIKE '%aaaa%'
or (using standard SQL):
CAST(contenido.field_value_fecha.value AS text) LIKE '%aaaa%'
This will be syntactically correct... Whether it is meaningful or not, is a different part of the story.

How to use ANY instead of IN in a WHERE clause?

I used to have a query like in Rails:
MyModel.where(id: ids)
Which generates sql query like:
SELECT "my_models".* FROM "my_models"
WHERE "my_models"."id" IN (1, 28, 7, 8, 12)
Now I want to change this to use ANY instead of IN. I created this:
MyModel.where("id = ANY(VALUES(#{ids.join '),('}))"
Now when I use empty array ids = [] I get the folowing error:
MyModel Load (53.0ms) SELECT "my_models".* FROM "my_models" WHERE (id = ANY(VALUES()))
ActiveRecord::JDBCError: org.postgresql.util.PSQLException: ERROR: syntax error at or near ")"
ActiveRecord::StatementInvalid: ActiveRecord::JDBCError: org.postgresql.util.PSQLException: ERROR: syntax error at or near ")"
Position: 75: SELECT "social_messages".* FROM "social_messages" WHERE (id = ANY(VALUES()))
from arjdbc/jdbc/RubyJdbcConnection.java:838:in `execute_query'
There are two variants of IN expressions:
expression IN (subquery)
expression IN (value [, ...])
Similarly, two variants with the ANY construct:
expression operator ANY (subquery)
expression operator ANY (array expression)
A subquery works for either technique, but for the second form of each, IN expects a list of values (as defined in standard SQL) while = ANY expects an array.
Which to use?
ANY is a later, more versatile addition, it can be combined with any binary operator returning a boolean value. IN burns down to a special case of ANY. In fact, its second form is rewritten internally:
IN is rewritten with = ANY
NOT IN is rewritten with <> ALL
Check the EXPLAIN output for any query to see for yourself. This proves two things:
IN can never be faster than = ANY.
= ANY is not going to be substantially faster.
The choice should be decided by what's easier to provide: a list of values or an array (possibly as array literal - a single value).
If the IDs you are going to pass come from within the DB anyway, it is much more efficient to select them directly (subquery) or integrate the source table into the query with a JOIN (like #mu commented).
To pass a long list of values from your client and get the best performance, use an array, unnest() and join, or provide it as table expression using VALUES (like #PinnyM commented). But note that a JOIN preserves possible duplicates in the provided array / set while IN or = ANY do not. More:
Optimizing a Postgres query with a large IN
In the presence of NULL values, NOT IN is often the wrong choice and NOT EXISTS would be right (and faster, too):
Select rows which are not present in other table
Syntax for = ANY
For the array expression Postgres accepts:
an array constructor (array is constructed from a list of values on the Postgres side) of the form: ARRAY[1,2,3]
or an array literal of the form '{1,2,3}'.
To avoid invalid type casts, you can cast explicitly:
ARRAY[1,2,3]::numeric[]
'{1,2,3}'::bigint[]
Related:
PostgreSQL: Issue with passing array to procedure
How to pass custom type array to Postgres function
Or you could create a Postgres function taking a VARIADIC parameter, which takes individual arguments and forms an array from them:
Passing multiple values in single parameter
How to pass the array from Ruby?
Assuming id to be integer:
MyModel.where('id = ANY(ARRAY[?]::int[])', ids.map { |i| i})
But I am just dabbling in Ruby. #mu provides detailed instructions in this related answer:
Sending array of values to a sql query in ruby?

how to use substr in SQL Server?

I have the following extract of a code used in SAS and wanted to write it in SQL Server to extract data.
substr(zipname,1,4) in("2000","9000","3000","1000");run;
How do I write this in SQL Server ?
I tried and got this error:
An expression of non-boolean type specified in a context where a
condition is expected
In sql server, there's no substr function (it's substring)
by the way, you need a complete query...
select blabla
from blibli
where substring(zipname, 1, 4) in ('2000', '9000', 3000', '1000')
assuming zipname is a varchar or something like that...
You need a table that you are getting the records from, and zipname would be a column in the table. The statement would be something like this:
select * from tablename where substring(zipname,1,4) in ('2000','9000','3000','1000')
Since you want the first x characters, you can also use the left() function.
where left(zipname, 4) in (values go here)
Bear in mind that your values have to be single quoted. Your question has double quotes.