How to create a filter that does the SQL equivalent of WHERE ... IN for SQLite.Swift - swift

I would like to filter results for the same column with multiple values
example in sql:
SELECT * FROM myTable WHERE status = 1 AND current_condition = ("New", "Working")
this will return all rows from myTable where the status is 1 and the current_condition is "New" OR "Working"
how do I do this in SQLite.swift?

You can use raw SQL in Swift. So you can use the string you posted.
Raw SQL
Using Filters
I use Filters, gives me more insight.

Related

Use postgresql query results to form another query

I am trying to select from one table using the select result from another table. I can run this in two queries but would like to optimize it into just one.
First query.. Select ids where matching other id
select id from lookuptable where paid = '547'
This results in something like this
6316352
6316353
6318409
6318410
6320468
6320469
6320470
6322526
6322527
6324586
6324587
6326648
I would like to then use this result to make another selection. I can do it manually like below. Note, there could be many rows with these values so I've been using a IN statement
select * from "othertable" where id in (6316352,6316353,6318409,6318410,6320468,6320469,6320470,6322526,6322527,6324586,6324587,6326648);
select
ot.*
from
"othertable" as ot
join
lookuptable as lt
on
ot.id = lt.id
where
lt.paid = '547'
The IN operator supports not just value lists but also subqueries, so you can literally write
select * from "othertable" where id in (select id from lookuptable where paid = '547');

How to apply order_by to a subquery with LIMIT in SQLAlchemy?

I have a large table and I need to limit my first query (subquery) and then apply ORDER BY to the result, something like this:
SELECT * FROM (
SELECT * FROM logs
LIMIT 10
) as tb
ORDER BY tb.date_time
In SQLAlchemy, this doesn't work:
session.query(Log).limit(10).order_by(Log.date_time)
because of this error:
sqlalchemy.exc.InvalidRequestError: Query.order_by() being called on a Query which already has LIMIT or OFFSET applied. Call order_by() before limit() or offset() are applied.
I tried the following ones and they didn't work as well:
sq = session.query(Log).limit(10).subquery().order_by(Log.received_time)
sq = session.query(Log).limit(10).subquery()
res = session.query(Log).order_by(sq.received_time)
How can I convert the above SQL script to SQLAlchemy syntax?

Convert rows into Column in Postgress Error

Hello I have created a view, but want to pivot it.
OUTPUT before pivoting:
expected output:
my full query:
SELECT *
FROM CROSSTAB(
'SELECT DISTINCT GROUP_DEST::TEXT,DEST::TEXT,TIER::TEXT,RATE::TEXT FROM VBB_TIER ORDER BY 1,2')
AS CT(ROW_NAME TEXT, TIER_1 TEXT, TIER_2 TEXT )
I getting this error and unable to resolve:
ERROR: invalid source data SQL statement
DETAIL: The provided SQL must return 3 columns: rowid, category, and values.
SQL state: 22023
Using filtered aggregation is typically a lot easier than the somewhat convoluted crosstab() function:
select group_dest,
dest,
max(rate) filter (where tier in ('0-100', ('0-150')) as tier_1,
max(rate) filter (where tier in ('101-200', '151-350') as tier_2
from vbb_tier
group by group_dest, dest;

how to retrieve the column values which are aggregated(like count) using groupby column

I want to display the contents of the aggregated columns that is part of group by sql statement.
Example:
SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
WHERE Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName
In the above example the output gives me count as one of the result, whereas i need the aggregated orders.orderID actual values even. So say if one result count shows me 2. I need to know what are those two values which have been grouped. This result should be as another column in the same table.
try this with GROUP_CONCAT
SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders , array_agg(Orders.OrderID) as which_are_those FROM Orders
WHERE Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName
array_agg returns an array, but you can CAST that to text and edit as needed (see clarifications, below).
Prior to version 8.4, you have to define it yourself prior to use:
CREATE AGGREGATE array_agg (anyelement)
(
sfunc = array_append,
stype = anyarray,
initcond = '{}'
);
or simply this:
SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders , string_agg(Orders.OrderID, ',') as which_are_those FROM Orders
WHERE Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName

Manipulate & use the results of UPDATE .... RETURNING

Here is a simple PostgreSQL update returning some data:
UPDATE table set num = num + 1
WHERE condition = true
RETURNING table.id, table.num
Is there a way to further use the returned results, as if they came from a select statement? Something like this:
INSERT into stats
(id, completed)
SELECT c.id, TRUE
FROM
(
UPDATE table set num = num + 1
WHERE condition = true
RETURNING table.id, table.num
) c
where c.num > 5
Or do I have to save the returned results into my application, then create a new query out of the returned results?
As of version 9.1, you can use an UPDATE ... RETURNING in a "Common Table Expression" ("CTE"), which for most purposes can be thought of as a named sub-query.
So for your purposes, you could use something like this:
WITH update_result AS
(
UPDATE table set num = num + 1
WHERE condition = true
RETURNING table.id, table.num
)
INSERT into stats
(id, completed)
SELECT c.id, TRUE
FROM update_result as c
WHERE c.num > 5
If you're using a version of Postgres below 9.1, then I think you will have to grab the result into a variable in some procedural code - either your application, or a database function (probably written in PL/pgSQL).
That syntax won't work (unfortunately! that would be convenient).
Either you update and then create another query, or you do everything in a stored procedure where you can safely store and handle query resuts, so that you just have one single database call from your application.