SQLite check if a row exists - ruby

I'm trying to check if a specific ID exists in a table named "Products" in my sqlite database.
def existsCheck( db, id )
temp = db.execute( "select exists(
select 1
from Products
where promoID = ?
) ", [id] )
end
that's my current code but that returns an array which means I have to deal with conversion before I can use it as a boolean. Any ideas how I can change it so that it returns an int with the value 1?

There is no need to use a subquery:
def existsCheck( db, id )
db.execute( "select 1
from Products
where promoID = ?",
[id] ).length > 0
end
This returns a boolean result.

Change it to:
def existsCheck( db, id )
temp = db.execute( "select 1 where exists(
select 1
from Products
where promoID = ?
) ", [id] ).any?
end
SQL query returns 1 when condition is met or empty result set if it's not. Whole function returns boolean depending on result set.

Related

Oracle - Delete records with conditions

I would like to write SQL which deletes records based on a few conditions.
I have four records
In these records, ID is unique and can change. Name is used to delete the records.
1) A Name should have at least one OK type.
2) IF Name has an ID that doesn't contain DUMMY in its name, then delete all other records where ID contains DUMMY.
How can I do this in SQL?
Try this:
delete from tablename t
where t."id" like '%DUMMY%'
and t."name" = (
select "name" from tablename
where "name" = '?'
group by "name"
having sum(case when "type" = 'OK' then 1 else 0 end) > 0
and sum(case when "id" not like '%DUMMY%' then 1 else 0 end) > 0
)
The subquery after the IN clause returns the names that have at least 1 type = 'OK' and at least 1 id not containing 'DUMMY'.
Edit:
delete from tablename t
where
t."name" = '?'
and (
(t."id" like '%DUMMY%' and t."type" <> 'OK')
or (
t."type" = 'OK'
and exists (
select 1 from tablename
where "name" = t."name" and "type" = t."type" and "id" > t."id"
)
)
)

How to apply the results of a method to a SQL query? [duplicate]

I'm trying to check if a specific ID exists in a table named "Products" in my sqlite database.
def existsCheck( db, id )
temp = db.execute( "select exists(
select 1
from Products
where promoID = ?
) ", [id] )
end
that's my current code but that returns an array which means I have to deal with conversion before I can use it as a boolean. Any ideas how I can change it so that it returns an int with the value 1?
There is no need to use a subquery:
def existsCheck( db, id )
db.execute( "select 1
from Products
where promoID = ?",
[id] ).length > 0
end
This returns a boolean result.
Change it to:
def existsCheck( db, id )
temp = db.execute( "select 1 where exists(
select 1
from Products
where promoID = ?
) ", [id] ).any?
end
SQL query returns 1 when condition is met or empty result set if it's not. Whole function returns boolean depending on result set.

How to convert exists condition inside where clause in Linq

I want to add following where clause to Linq query. How subquery like below using linq
WHERE (Restaurants.[IsActive] = 1)
AND exists
(
select 1 from APIKeys
where ApiKey = 'on35e5xbt3m4cbcef4e4448t6wssg11o'
and (KeyType = 1
and fk_RestaurantsID = [t2].[RestaurantsID]
or KeyType = 2
and fk_RestaurantGroupID = RG.RestaurantGroupsID
and [t1].[fk_RestaurantsID] in
(SELECT RestaurantsID
FROM Restaurants
WHERE RestaurantGroupsID = RG.RestaurantGroupsID))
)
AND (0 = (COALESCE([t0].[fk_MembersID],0)))
AND (1 = [t0].[fk_BookingStatusID])
AND ([t0].[Email] = 'nike.s#gmail.com')
AND (([t0].[Phone] = '9999999990') OR ([t0].[MobilePhone] = '9999999990'))
Use Any() to produce subquery which translated to EXISTS. E.g. with AdventureWorks database sample:
from p in Products
where p.FinishedGoodsFlag &&
SalesOrderDetails.Any(od => od.ProductID == p.ProductID)
select new { p.ProductID, p.Name }
Will produce following query to database:
SELECT [t0].[ProductID], [t0].[Name]
FROM [Production].[Product] AS [t0]
WHERE ([t0].[FinishedGoodsFlag] = 1) AND (EXISTS(
SELECT NULL AS [EMPTY]
FROM [Sales].[SalesOrderDetail] AS [t1]
WHERE [t1].[ProductID] = [t0].[ProductID]
))

How to merge data from multiple rows into single column in new table?

How do I merge data from multiple rows in one table to a single column in a new table?
create table new_paragraphs
(
id NUMBER
paragraph CLOB
);
create table old_paragraphs
(
id
paragraph CLOB
);
merge into new_paragraphs a
using (select * from old_paragraphs) b
on (id = id)
when matched then
update set a.paragraph = a.paragraph || b.paragraph;
-- Results in error: unable to get a stable set of rows in the source tables
The above throws an exception.
It would work if id were a primary key in at least *old_paragraphs* (or if it were unique for each id found in *new_paragraph*)
Other than that, you want to use aliases in on (id = id) so that it reads on (a.id = b.id):
merge into new_paragraphs a
using (select * from old_paragraphs) b
on (a.id = b.id)
when matched then
update set a.paragraph = a.paragraph || b.paragraph;
Why are you doing a MERGE here? Why not a simple UPDATE (assuming ID is the primary key of both tables)
UPDATE new_paragraphs a
SET paragraph = (select a.paragraph || b.paragraph
from old_paragraphs b
where a.id = b.id)
WHERE EXISTS (SELECT 1
FROM old_paragraphs b
WHERE a.id = b.id)

How to get the last element by date of each "type" in LINQ or TSQL

Imagine to have a table defined as
CREATE TABLE [dbo].[Price](
[ID] [int] NOT NULL,
[StartDate] [datetime] NOT NULL,
[Price] [int] NOT NULL
)
where ID is the identifier of an action having a certain Price. This price can be updated if necessary by adding a new line with the same ID, different Price, and a more recent date.
So with a set of a data like
ID StartDate Price
1 01/01/2009 10
1 01/01/2010 20
2 01/01/2009 10
2 01/01/2010 20
How to obtain a set like the following?
1 01/01/2010 20
2 01/01/2010 20
In SQL, there are several ways to say it. Here's one that uses a subquery:
SELECT *
FROM Price p
WHERE NOT EXISTS (
SELECT *
FROM Price
WHERE ID = p.ID
AND StartDate > p.StartDate
)
This translates fairly trivially to LINQ:
var q = from p in ctx.Price
where !(from pp in ctx.Price
where pp.ID == p.ID
&& pp.StartDate > p.StartDate
select pp
).Any()
select p;
Or should I say, I think it does. I'm not in front VS right now, so I can't verify that this is correct, or that LINQ will be able to convert it to SQL.
Minor quibble: Don't use the name ID to store a non-unique value (the type, in this case). It's confusing.
Assuming ID & StartDate will be unique:
SELECT p.ID, p.StartDate, p.Price
FROM Price p
JOIN
(
SELECT ID, MAX(StartDate) AS LatestDate
FROM Price
GROUP BY ID
) p2 ON p.ID = p2.ID AND p.StartDate = p2.LatestDate
Since you tagged your question with LINQ to SQL, here is an LINQ query to express what you want:
from price in db.Prices
group price by price.Id into group
let maxDateInGroup = group.Max(g => g.StartDate)
let maxDatePrice = group.First(g => g.StartDate == maxDateInGroup)
select
{
Id = group.Key,
StartDate = maxDatePrice.StartDate,
Price = maxDatePrice.Price
};

Resources