Check if all rows are the same - sql

I have a select query that returns multiple rows, and I want to check if all rows are the same. So something like this:
anything_other_than(123) in (select id from foo)
So, if select id from foo returns 111,222,123,333 the statement above is false, and if select id from foo returns 123,123,123 it's true. How can I achieve this?

A simple solution is to use the = ALL operator:
SELECT 123 = ALL (SELECT id FROM foo);
This solution also stop scanning the result as soon as the first non-matching value is found.

Another option is to use EXISTS with a where condition:
select not exists (select *
from the_table
where id <> 123);

Run this:
select count(distinct id) = 1 and count(*) > 1 from foo;
count(distinct id) will return 1 if all the rows are the same
and count(*) will return the total number of rows.
If this returns true then you have more than 1 rows and all the rows are the same.

You can use something like this -
select x, IF(x > 1, "FALSE", "TRUE") from
(SELECT count(distinct(A.id)) as x FROM foo as A) as B;
Do refer this https://www.w3schools.com/sql/func_mysql_if.asp

Related

Reduce duplication in postgres plpgsql function with CTE

In a SQL function I can return a boolean if I do
with myquery as (delete from mytable where id = 'value1' returning 1)
select exists (select * from another_function('value2') where (select count(*) from myquery) > 0);
But in a plpgsql function it doesn't work and gives error query has no destination for result data.
In this function I want to execute another_function if any rows were actually deleted from mytable. The problem is I'm repeating the entire select exists part, because I'm using that in multiple functions.
Is it possible to move more of that logic into another_function? So that I can do something like this?
with myquery as (delete from mytable where id = 'value1' returning 1)
select * from another_function('value2', myquery)
How can I pass the CTE into a function so I don't need to repeat the select exists and where (select count(*) from myquery) > 0) every time I want to call another_function?
I would expect an auxiliary function to take an argument, such as the id being returned from the delete. It would then look like:
with d as (
delete from mytable
where id = 'value1'
returning id
)
select another_function('value2', d.id)
from d;
This operates one value at a time, but that is typically what one would want. If you wanted all ids passed in at once, you could use an array:
with d as (
delete from mytable
where id = 'value1'
returning id
)
select another_function('value2', array_agg(d.id))
from d;

select specific records using IN

I need to select records that has ID = 10,23,30 so I wrote this SQL
Select * from mytable where position(id in '10,23,30') > 0
But the problem I get additional records where ID = 1 and 2
Any ideas how to select only what I need ?
No need for position, just do IN:
Select * from mytable
where id in (10,23,30)
Use IN operator:
Select * from mytable where id in (10,23,30)

Multiple Columns in an "in" statement

I am using DB 2 and i am trying to write a query which checks multiple columns against a given set of values.Like field a, field b and field c against values x,y,z,f. One way that i can think for is writing same condition 3 times with or i.e. field a in ('x','y','z','f') or field b in .... and so on . Please let me know if there is some other efficient and easy way to accomplish this. I am looking for a query like if any of the condition is true return yes else no . Please suggest !
This may or may not work on as400:
create table a (a int not null, b int not null);
insert into a (a,b) values (1,1),(1,3),(2,3),(0,23);
select a.*
from a
where a in (1,2) or b in (1,2);
A B
----------- -----------
1 1
1 3
2 3
Rewriting as a join:
select a.*
from a
join ( values (1),(2) ) b (x)
on b.x in (a.a, a.b);
A B
----------- -----------
1 1
1 3
2 3
Assuming the column data types are the same, Create a subquery joining all the columns you want to search with your IN into one column with a union
SELECT *
FROM (
SELECT
YOUR_TABLE_PRIMARY_KEY
,A AS Col
FROM YOUR_TABLE
UNION ALL
SELECT
YOUR_TABLE_PRIMARY_KEY
,B AS Col
FROM YOUR_TABLE
UNION ALL
SELECT
YOUR_TABLE_PRIMARY_KEY
,C AS Col
FROM YOUR_TABLE
) AS SQ
WHERE
SQ.Col IN ('x','y','z','f')
Make sure to include the table key so you know which row the data refers to
You can create a regular expression that describe the set of characters and use it with xquery
Assuming you're on a supported version of the OS (tested on 7.1 TR6), this should work...
with sel (val) as (values ('x'),('y'),('f'))
select * from mytbl
where flda in (select val from sel)
or fldb in (select val from sel)
or fldc in (select val from sel)
Expanding on the above since your OP asked for "condition is true return yes else no"
Assuming you've got the key to a row to check, would 'yes' or the empty set be good enough? somekey is the key for the row you want to check.
with sel (val) as (values ('x'),('y'),('f'))
select 'yes' from mytbl
where thekey = somekey
and ( flda in (select val from sel)
or fldb in (select val from sel)
or fldc in (select val from sel)
)
It's actually rather difficult to return a value when you don't have a matching row. Here's one way. Note I've switch to 1=yes, 0=no..
with sel (val) as (values ('x'),('y'),('f'))
select 1 from mytbl
where thekey = somekey
and ( flda in (select val from sel)
or fldb in (select val from sel)
or fldc in (select val from sel)
)
UNION ALL
select 0
from sysibm.sysdummy1
order by 1 desc
fetch first row only

return a default record from a sql query

I have a sql query that I run against a sql server database eg.
SELECT * FROM MyTable WHERE Id = 2
This may return a number of records or may return none. If it returns none, I would like to alter my sql query to return a default record, is this possible and if so, how? If records are returned, the default record should not be returned. I cannot update the data so will need to alter the sql query for this.
Another way (you would get an empty initial rowset returned);
SELECT * FROM MyTable WHERE Id = 2
IF (##ROWCOUNT = 0)
SELECT ...
SELECT TOP 1 * FROM (
SELECT ID,1 as Flag FROM MyTable WHERE Id = 2
UNION ALL
SELECT 1,2
) qry
ORDER BY qry.Flag ASC
You can have a look to this post. It is similar to what you are asking
Return a value if no rows are found SQL
I hope that it can guide you to the correct path.
if not exists (SELECT top 1 * FROM mytable WHERE id = 2)
select * from mytable where id= 'whatever_the_default_id_is'
else
select * from mytable where id = 2
If you have to return whole rows of data (and not just a single column) and you have to create a single SQL query then do this:
Left join actual table to defaults single-row table
select
coalesce(a.col1, d.col1) as col1,
coalesce(a.col2, d.col2) as col2,
...
from (
-- your defaults record
select
default1 as col1,
default2 as col2,
...) as d
left join actual as a
on ((1 = 1) /* or any actual table "where" conditions */)
The query need to return the same number of fields, so you shouldn't do a SELECT * FROM but a SELECT value FROM if you want to return a default value.
With that in mind
SELECT value FROM MyTable WHERE Id = 2
UNION
SELECT CASE (SELECT count(*) FROM MyTable WHERE Id = 2)
WHEN 0 THEN 'defaultvalue'
END

Determine existence of results in jet SQL?

In Jet, I want to test if certain conditions return any results.
I want a query which returns exactly one record: "true" if there are any results, "false" otherwise.
This works in MS SQL:
SELECT
CASE
WHEN EXISTS(SELECT * FROM foo WHERE <some condition>)
THEN 1
ELSE 0
END;
This is what I have tried in Jet:
SELECT IIF(EXISTS(SELECT * FROM foo WHERE <some condition>), 0, 1);
which gives me the error:
Reserved error (-3025); there is no message for this error.
Any ideas?
NOTE
I don't want to select "true" multiple times by tacking on a FROM clause at the end, because it could be slow (if the FROM table had many records) or undefined (if the table had 0 records).
How about:
SELECT TOP 1 IIF(EXISTS(
SELECT * FROM foo
WHERE <some condition>), 0, 1) As f1
FROM foo
Perhaps more clearly:
SELECT TOP 1 IIF(EXISTS(
SELECT * FROM foo
WHERE <some condition>), 0, 1) As F1
FROM MSysObjects
You might be able to use a count
SELECT DISTINCT IIF((SELECT COUNT(*) AS Result FROM [Data Set]), 1, 0) FROM [Data Set];
Most EXISTS queries can be re-written as a left join:
SELECT
CASE
WHEN foo.col is NULL
THEN 0
ELSE 1
END;
... LEFT JOIN foo on <where condition>