Can I loop over the results of an SQL query to use each value in another query all at once in SQL Developer? - plsql

What I want to achieve (if it is possible from SQL Developer) is that when I execute the script it do the following:
Run a SELECT statement that will return a list of IDs. Approx 270 records.
I need to use each of those IDs individually in another SELECT statement (in the WHERE clause) which will return some records. A few of this could result in over 17,000 records and some can be one.
Then each result from the second SELECT I want it to be exported to an excel or csv file into a folder at my pc.
I have both 'Select' ready but I don't know how to loop over the results of the first to grab each ID and use it in the second one. Also I don't know how to export automatically from the code.

You can use GROUP BY clause.
read more here:
http://docs.oracle.com/javadb/10.6.2.1/ref/rrefsqlj32654.html

If the first SELECT returns you IDs only, and that's all you need for your second SELECT, just use IN clause providing your first SELECT query for the second one.
Example:
-- Your second select
SELECT
col1
,col2
,col3
,col4
FROM
second_table
WHERE
some_foreign_id IN (
-- Your first select
SELECT
id
FROM
first_table
WHERE
some_conditions...
)

In my opinion don't use PLSQL for this. In PLSQL the only way you can get an output of this by using a REFCURSOR (unless you dont use UTIL File package to do it). A simple SELECT WITH JOIN condition will suffice your requirement.
Test illustration
SELECT A.* FROM TABLE_A A, TABLE_B
WHERE A.COMMON_COLUMN = B.COMMON_COLUMN;
Hope this helped you in same way

Related

PLSQL: How to update and Insert together when match found between source and target table

I have a source and a target table. I need to make update and insert together in final table with following conditions:
1) When SourceTable.ProductName = TargetTable.ProductName and SourceTable.Amount = TargetTable.Amount Then
Update TargetTable set TargetTable.ValidFrom = sysdate
Also i need to insert like this,
Insert Into TargetTable(ProductName,Amount,ValidFrom,Version) Values(TargetTable.ProductName,TargetTable.Amount, sysdate, TargetTable.Version + 1)
This is to maintain version.
2) When there is no match then i need to insert directly like this,
Insert Into TargetTable(ProductName,Amount,ValidFrom,Version) Values(SourceTable.ProductName,SourceTable.Amount, sysdate,1)
As of now i am thinking of capturing these matching records in a Cursor and perform Update and Insert together in cursor loop. But i am willing to avoid loops a i have approx 10 millions of matching records.
We also have Merge statement, but I believe Merge do not support Update and Insert together in single "WHEN MATCHED" Clause. Please correct me if i am wrong?
Kindly suggest the best way to achieve this behavior.

Create temporary table

I'm coming from SQL Server enviroment where you can declare a temp table with #table, but as I've read you can't do this in oracle.
I want get a value for 500.000 hardcoded id's from a table, but as the IN clause has a limit of 1000 I need to find another way. Is the best way to create a temporary table and insert the hardcoded values and then join the other table which contains the values I need ?
My client (toad) has autocommit set to off and I dont want to commit anything, I want it to be session-based so when I close the database client I want the temporary table do disappear. Is the code below the right way to do in oracle?
CREATE GLOBAL TEMPORARY TABLE Test(HardcodedId number(10))
ON COMMIT DELETE ROWS;
I've also tried to use inner join and in the join select the hardcoded values from dual, but this creates a column for each value and i'm not able to use a reference to join with. Is it possible to insert all values into a single column in dual?
You can use some thing like this (500 union all)
select * from (
select '1' from dual
union all
select '2' from dual
...) q
Then you can join this with other tables.
For your situation, I would use a GTT (global temporary table) - which you have already researched by the looks.
The advantage of a GTT is that it's a permanent object (so no need to constantly create and drop it) and the data "stored" in it is on a session basis.

SQLite: JOIN back INTO left table?

If I have this statement,
SELECT table1.*, table2_1.`values` AS val_1
FROM table1 JOIN table2_1
ON table1.row_names=table2_1.row_names
I would actually like this the result joined back into table1. Any inclusion of a join statement after SELECT and before FROM gives me an error.
Why can I not save the results to a table, and is it possible to save it back to one of the original tables?
Because you do it the wrong way. SELECT statement will not modify you data no matter how much you want it. If you want to modify data, you need to use UPDATE statement.

Keep first and remove dupliciate rows only using sqlite

Maybe i should do this in C# but i have more then one row with linkId X. I would like to remove it but i am unsure how. In code i could just use a foreach from 0 to n and remove any found rows with a greater (or !=) id but thats in code. Is there a less difficult way of doing it using sqlite?
Assuming the table's name is tableName and there is a primary key field named id, the following sql would do it. I think the following SQL query is general enough and should be able to be executed under any database engine.
delete from tableName
where id not in (
select min(id) from tableName
group by linkId
)

How to get the number of rows of the selected result from sqlite3?

I want to get the number of selected rows as well as the selected data. At the present I have to use two sql statements:
one is
select * from XXX where XXX;
the other is
select count(*) from XXX where XXX;
Can it be realised with a single sql string?
I've checked the source code of sqlite3, and I found the function of sqlite3_changes(). But the function is only useful when the database is changed (after insert, delete or update).
Can anyone help me with this problem? Thank you very much!
SQL can't mix single-row (counting) and multi-row results (selecting data from your tables). This is a common problem with returning huge amounts of data. Here are some tips how to handle this:
Read the first N rows and tell the user "more than N rows available". Not very precise but often good enough. If you keep the cursor open, you can fetch more data when the user hits the bottom of the view (Google Reader does this)
Instead of selecting the data directly, first copy it into a temporary table. The INSERT statement will return the number of rows copied. Later, you can use the data in the temporary table to display the data. You can add a "row number" to this temporary table to make paging more simple.
Fetch the data in a background thread. This allows the user to use your application while the data grid or table fills with more data.
try this way
select (select count() from XXX) as count, *
from XXX;
select (select COUNT(0)
from xxx t1
where t1.b <= t2.b
) as 'Row Number', b from xxx t2 ORDER BY b;
just try this.
You could combine them into a single statement:
select count(*), * from XXX where XXX
or
select count(*) as MYCOUNT, * from XXX where XXX
To get the number of unique titles, you need to pass the DISTINCT clause to the COUNT function as the following statement:
SELECT
COUNT(DISTINCT column_name)
FROM
'table_name';
Source: http://www.sqlitetutorial.net/sqlite-count-function/
For those who are still looking for another method, the more elegant one I found to get the total of row was to use a CTE.
this ensure that the count is only calculated once :
WITH cnt(total) as (SELECT COUNT(*) from xxx) select * from xxx,cnt
the only drawback is if a WHERE clause is needed, it should be applied in both main query and CTE query.
In the first comment, Alttag said that there is no issue to run 2 queries. I don't agree with that unless both are part of a unique transaction. If not, the source table can be altered between the 2 queries by any INSERT or DELETE from another thread/process. In such case, the count value might be wrong.
Once you already have the select * from XXX results, you can just find the array length in your program right?
If you use sqlite3_get_table instead of prepare/step/finalize you will get all the results at once in an array ("result table"), including the numbers and names of columns, and the number of rows. Then you should free the result with sqlite3_free_table
int rows_count = 0;
while (sqlite3_step(stmt) == SQLITE_ROW)
{
rows_count++;
}
// The rows_count is available for use
sqlite3_reset(stmt); // reset the stmt for use it again
while (sqlite3_step(stmt) == SQLITE_ROW)
{
// your code in the query result
}

Resources