U-SQL correlated subquery - azure-data-lake

Is it possible to execute some sort of a query in U-SQL where you have an inner subsquery referencing each row in the outer query?

U-SQL does not provide correlated subqueries. Best is to rewrite them into joins or semijoins as pointed out by Joel and Dragan.

SEMIJOIN is the U-SQL version of T-SQL "IN", and ANTISEMIJOIN is "NOT IN". Can you provide more details about your specific use case?

Related

Converting Postgre to Bigquery

I am having a trouble with a conversion from Postgre to Bigquery query.
Please, how could this query work on bigquery ? I need to subselect a table and bring the last register
(select g.fase__c
from operacoes.salesforce_gest_o_do_canal_c_full g
where g.n_de_indentifica_o_do_parceiro__c = a.n_de_indentifica_o_do_parceiro__c
order by g.data_do_credenciamento__c limit 1) as fase_jornada
from operacoes.salesforce_account_full
If I try to execute, Bigquery returns an error I should apply a join, If I apply the join, the order by doesn´t work
Thanks!
A correlated subquery (which is a subquery that references a table of an outer query), if executed "as is", would need to compute the subquery for each row of the results of the outer query, which would not be very efficient.
In order to optimize this, BigQuery first transforms (decorrelates) the query into one that is functionally equivalent to the correlated one but without any correlations between queries and subqueries. Different decorrelation processes are needed for different use cases and they can be quite complex and difficult to implement and properly test.
BigQuery is implementing decorrelation strategies to make a variety of correlated subqueries possible, however decorrelation for the LIMIT clause has not been implemented.
A workaround would be to use ARRAY_AGG instead of a subquery. In your case, I believe the following query would do the work:
SELECT
ARRAY_AGG(g.fase__c
ORDER BY g.data_do_credenciamento__c
LIMIT 1) AS fase_jornada
FROM
operacoes.salesforce_account_full a
JOIN
operacoes.salesforce_gest_o_do_canal_c_full g
ON
g.n_de_indentifica_o_do_parceiro__c = a.n_de_indentifica_o_do_parceiro__c
GROUP BY
g.n_de_indentifica_o_do_parceiro__c
Take into account that I have guessed some details since the whole context for the subquery was not provided, so you may need to make some changes to it.
Please let me know if anything was not clear!

SQL: Can or should correlated subqueries be used with all the subquery operators?

I am doing an SQL course and my teacher does not seem to have very clear if you can or should use correlated subqueries with the subquery operators like EXISTS, ALL, ANY, SOME, IN, etc... Or natural subqueries.
So in short can you use correlated subqueries with all of them or not or are you obligated to use it in some of them.
Btw I checked in W3S and Wikipedia and although they talk about correlated subqueries they don't say if there is any rule regarding the operators mentioned above.

Is there an "WITH" clause in BigQuery

I am a new user of bigquery. I used to use Postgresql and the WITH clause...
I have written multiple queries. Results of these queries need to be joined in order to create a single table (all results have a common key column).
Is there an equivalent of the WITH clause? I am reluctant to use sub-queries as my code will be hard to maintain.
BigQuery does support WITH clause in Standard SQL dialect. Documentation here: https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#with-clause
WITH doesn't come with BigQuery
How about using VIEWs?

subquery factoring questions

Please explain.
a) "subquery factoring" is used to replace a non-correlated subquery. What about correlated subquery? Is there any way to move a correlated sub-query to 'WITH' clause section?
b) are "subquery" "subquery factoring" executed exactly once?
c) "subquery" vs "subquery factoring" which one is better
Thank you.
You can use subquery factoring to replace a non-correlated subquery.
How on Earth do you propose doing so for a correlated subquery?
I don't understand part (b), can you rephrase?
Taking a guess at what you mean: a subquery in the WITH clause is typically executed only once before the main query is executed.
For large datasets, subquery factoring is obviously better since you're executing the subquery only once in most if not all cases. For smaller datasets the overhead of creating temporary tables may take longer than the actual query.
Apart from the performance concerns mentioned above, subquery factoring results in much cleaner and easer-to-maintain code.
By the term "subquery factoring" do you really mean refactoring using a subquery? Refactoring is the process of altering a routine to improve maintenance and readability without altering its result. There are times when one cannot refactor a subquery into a common table expression (into "WITH" clause). Further, there is no golden rule about always using a CTE or always using a subquery (or derived table). It depends on the data and the DBMS as to what approach will perform best.

Subqueries vs joins

I refactored a slow section of an application we inherited from another company to use an inner join instead of a subquery like:
WHERE id IN (SELECT id FROM ...)
The refactored query runs about 100x faster. (~50 seconds to ~0.3) I expected an improvement, but can anyone explain why it was so drastic? The columns used in the where clause were all indexed. Does SQL execute the query in the where clause once per row or something?
Update - Explain results:
The difference is in the second part of the "where id in ()" query -
2 DEPENDENT SUBQUERY submission_tags ref st_tag_id st_tag_id 4 const 2966 Using where
vs 1 indexed row with the join:
SIMPLE s eq_ref PRIMARY PRIMARY 4 newsladder_production.st.submission_id 1 Using index
A "correlated subquery" (i.e., one in which the where condition depends on values obtained from the rows of the containing query) will execute once for each row. A non-correlated subquery (one in which the where condition is independent of the containing query) will execute once at the beginning. The SQL engine makes this distinction automatically.
But, yeah, explain-plan will give you the dirty details.
You are running the subquery once for every row whereas the join happens on indexes.
Here's an example of how subqueries are evaluated in MySQL 6.0.
The new optimizer will convert this kind of subqueries into joins.
before the queries are run against the dataset they are put through a query optimizer, the optimizer attempts to organize the query in such a fashion that it can remove as many tuples (rows) from the result set as quickly as it can. Often when you use subqueries (especially bad ones) the tuples can't be pruned out of the result set until the outer query starts to run.
With out seeing the the query its hard to say what was so bad about the original, but my guess would be it was something that the optimizer just couldn't make much better. Running 'explain' will show you the optimizers method for retrieving the data.
Look at the query plan for each query.
Where in and Join can typically be implemented using the same execution plan, so typically there is zero speed-up from changing between them.
Optimizer didn't do a very good job. Usually they can be transformed without any difference and the optimizer can do this.
This question is somewhat general, so here's a general answer:
Basically, queries take longer when MySQL has tons of rows to sort through.
Do this:
Run an EXPLAIN on each of the queries (the JOIN'ed one, then the Subqueried one), and post the results here.
I think seeing the difference in MySQL's interpretation of those queries would be a learning experience for everyone.
The where subquery has to run 1 query for each returned row. The inner join just has to run 1 query.
Usually its the result of the optimizer not being able to figure out that the subquery can be executed as a join in which case it executes the subquery for each record in the table rather then join the table in the subquery against the table you are querying. Some of the more "enterprisey" database are better at this, but they still miss it sometimes.
With a subquery, you have to re-execute the 2nd SELECT for each result, and each execution typically returns 1 row.
With a join, the 2nd SELECT returns a lot more rows, but you only have to execute it once. The advantage is that now you can join on the results, and joining relations is what a database is supposed to be good at. For example, maybe the optimizer can spot how to take better advantage of an index now.
It isn't so much the subquery as the IN clause, although joins are at the foundation of at least Oracle's SQL engine and run extremely quickly.
The subquery was probably executing a "full table scan". In other words, not using the index and returning way too many rows that the Where from the main query were needing to filter out.
Just a guess without details of course but that's the common situation.
Taken from the Reference Manual (14.2.10.11 Rewriting Subqueries as Joins):
A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better—a fact that is not specific to MySQL Server alone.
So subqueries can be slower than LEFT [OUTER] JOINS.