So I have a list of values that is returned from a subquery and would like to select all values from another table that match the values of that subquery. Is there a particular way that's best to go about this?
So far I've tried:
select * from table where tableid = select * from table1 where tableid like '%this%'
select * from table where tableid in(select tableid
from table1
where tableid like '%this%')
select * from table where tableid IN
(select tableid from table1 where tableid like '%this%')
A sub-query needs to return what you are asking for. Additionally, if there's more than 1 result, you need IN rather than =
This will work
select * from table where tableid in
(select tableid from table1 where tableid like '%this%')
= works when subquery returns 1 record only
in works when subquery returns 1 or more than one record only
I am reading a SQL Server book right now, and it highlights doing this using the EXISTS statement in the WHERE clause for speed and efficiency purposes. Here's a potential solution.
SELECT
*
FROM
tableName AS t
WHERE
EXISTS(
SELECT
1
FROM
table1 AS s --as in subtable or something like that
WHERE
t.tableid = s.tableid
AND
s.tableid like '%this%'
)
Related
How can I write WHERE cluase so it returns rows that meet the criteria, if there are no such records it should return all records from a table?
Using UNION ALL:
select t.* from table t where condition
union all
select t.* from table t cross join (select count(*) cnt from table where condition) c
where c.cnt=0
Or (much more efficiently):
select col1, col2, ... colN
from
(
select t.*, sum(case when condition then 1 else 0 end) over() cnt from table
) s
where condition or s.cnt=0
Replace condition with your WHERE condition
One method you could consider in t-sql is to use ##rowcount to determine if you need to return all rows.
The benefit of doing so is you get two separate execution plans, one only optimised for your first exists criteria and would be beneficial if the majority of results are where the exists condition is met.
select <columns>
from <table>
where <condition>
if ##rowcount=0
begin
select <columns>
from <table>
end
One way would be:
SELECT *
FROM Person
WHERE
Name = 'John'
OR NOT EXISTS(SELECT null FROM Person WHERE Name = 'John')
I don't like it, for all those good reasons mentioned in the comments. If I was handed this requirement as part of a system I was creating I'd probably examine the need for the requirement; selecting all rows from a table is seldom useful if it's the sort of table that you query with a criteria: "Dear user, we couldn't find your person named John so here are the other 4.27 billion users in the system, pagination size 100"
that satisfies me enough:
WHERE (
ISNULL(#variable, '') = ''
OR #variable = [Column]
)
Not exactly what I described above but it returns all the records if condition is not met. However in that case condition would be assigning a value to variable.
1st method
Where ( ISNULL(#Param,'')='' OR ColumnName = #Param)
2nd way
WHERE ( ColumnName =CASE WHEN #Param IS NULL THEN ColumnName
ELSE #Param
END)
3rd way
WHERE (#Param ='' OR #Param =ColumnName)
I would recommend a CTE with not exists:
with cte as (
select t.*
from t
where . . .
)
select *
from cte
union all
select *
from t
where not exists (select 1 from cte);
Does Big Query support operations like "REPLACE INSERT" or something related to that?
If I run a query like this twice:
INSERT INTO table(column1) VALUES(1)
It'll create a duplicated row, is it possible to insert a row only if a column with the same value does not exist?
Thanks!
Below should make it
#standardSQL
INSERT INTO yourTable(column1)
SELECT value FROM (SELECT 1 AS value)
LEFT JOIN yourTable
ON column1 = value
WHERE column1 IS NULL
Does this work for you?
INSERT INTO table(column1)
WITH s AS (SELECT 1 src)
SELECT src FROM s WHERE NOT EXISTS (
SELECT * FROM table t WHERE t.column1 = s.src
)
I have two queries, query1 and query2. What I would like to do is, if returned rows of query1 is empty, return query2 instead. Is that possible using basic SQL query alone? They have same returning columns btw, but different table sources.
eg:
query1:
SELECT name, message
FROM table1
query2:
SELECT name, message
FROM table 2
If query1 is empty, return name, message from query2.
This will select from table1 if not empty, otherwise select from table2:
SELECT * FROM table1
WHERE EXISTS (select * from table1)
UNION ALL
SELECT * FROM table2
WHERE NOT EXISTS (select * from table1)
This checks if table1 has no rows:
EXISTS (SELECT * FROM TABLE)
Found an answer here: https://stackoverflow.com/a/25122516/3747493
Basically:
SELECT *
FROM table1
UNION ALL
SELECT *
FROM table2
WHERE (SELECT COUNT(*) FROM table1) = 0
Thanks guys!
I have a sql statement SELECT * FROM table1 WHERE ....; SELECT * FROM table2 WHERE ....
What I want is to get the results from the first select statement if it returns results, but if it doesn't, I want to ignore it and just get the results from the second select statement. Is there a way I can do this just using SQL?
I'm getting this returned to me as a datatable, using a dataadapter to fill the datatable from the above SQL statement. I can't change that part, or switch to filling a dataset (for reasons I won't get into, but it just can't be changed).
Assuming both queries return the same number and type of columns, one way to do this would be:
select * from table1 where ... /* query 1 conditions */
union all
select * from table2 where ... /* query 2 conditions */
and not exists
(select 1 from table1 where ... /* query 1 conditions */)
A couple options. You can check the count first:
If (select count(*) from table1 where...) > 0
begin
select * from table1 where...
end
else
begin
select * from table2 where...
end;
if both result sets are identical in structure, you can save the count check (and thus improve performance) by using a temp table:
create table #temp (col1 int, col2 varchar(10), ...);
insert #temp
select * from table1 where...;
if ##rowcount = 0
begin
insert #temp
select * from table2 where...
end;
select * from #temp;
I don't know it may sound weird... but here is my situation... I have to select rows from two tables (Table1) and (Table2)
Select * from Table1 Where <SomeCondition>
Select * from Table2 Where <SomeCondition>
But my constraint is If Table1 / Table2 return 0(zero) Rows... I should not return any results at all.
That ie... If 1st select returns say 10 rows and the 2nd select returns 0 (zero) rows, I should call back the first select also...
Is the Temp tables the only solution, or do we have any other alternative.
Thanks in advance for your response...
Raja
One approach is to do an IF EXISTS first:
IF EXISTS(SELECT * FROM Table1 WHERE....) AND EXISTS(SELECT * FROM Table2 WHERE....)
BEGIN
-- Now do your SELECT on each, as both return results
END
EXISTS should give good performance, as it will stop as soon as it does find a matching record.
Without more details of your specific queries, here is an option. As long as your queries aren't too complex aren't very intensive, this should work:
Select * from Table1 Where <SomeCondition>
where exists( Select null from Table2 Where <SomeCondition> );
Select null from Table2 Where <SomeCondition>
where exists ( Select null from Table1 Where <SomeCondition> );
This will only select rows in each statement if the other statement will also return any number of rows greater than zero.
An obvious but not-so-performant solution will be to count number of rows first (not sure about the syntax):
if not exists(select id from Table1 where ...) or not exists(select id from Table1 where ...)
return
Select * from Table1 Where <SomeCondition>
Select * from Table2 Where <SomeCondition>
If you can use stored procedures you can use ##rowcount to check if the second query returned any results:
create proc pTest
as
Select * from Table1 Where <SomeCondition>
Select * from Table2 Where <SomeCondition>
if ##rowcount = 0 return
go