Debugging performance differences (and issues) between a query with a double-subquery, a single-subquery and an all inner-join statements - sql

I have a complex business logic that requires me to perform a 2-levels nested query. The queries are generated by Django's ORM. At the bottom of the question I'll provide the queries as-is as well as a full EXPLAIN suitable to be viewed with PEV2, but in order to help readers understand better the question, I'll start with a more conceptual explanation.
This is how a very naive description of what we're doing looks like:
some_ids = get_id_based_on_some_conditions(*conditions*)
some_other_ids = get_some_other_ids_based_on_some_conditions_and_filtering_by_some_ids(*other_conditions*, some_ids)
results = get_results_based_on_even_more_conditions_and_filtering_by_some_other_ids(*another_set_of_conditions*, some_other_ids)
Translating the following pseudo-code to actual SQL using subqueries is quite easy. A straightforward translation becomes into the following pseudo-query:
select
foo,
bar
from
t1,
t2
where
condition1 = something and
condition2 in ( <---- first level subquery
select
id
from
t3
where
condition3 = another_something and
condition4 in ( <---- second level subquery
select
another_id
from
t4
where
condition5 = something_something and
condition6 = another_something_something
)
)
Since the query is taking a considerable amount of time (~0.6s) given the number of rows that it returns (a little bit over 9.000), I thought that it might help replacing the second level subquery with an inner join.
That, in fact, made the query even slower (now at ~1.7s). So I thought that maybe the planner didn't correctly understood what would happen with a subquery with an inner join inside and made some serious miscalculations / overestimations / underestimations, so I replaced the first level subquery with more inner joins, which led to even poorer results (now at ~10s).
I have been analysing the EXPLAINS of the queries for hours, and I can't figure out why using inner joins makes everything slower. I also don't know how to tell if my (currently) best query is actually the best I can get or if there are things that I'm not doing and that might speed it up.
So, the questions that I have are:
why are the inner joins slower than subqueries?
how can I tell if I'm doing everything possible in order to squeeze the maximum performance out of my database or if I'm missing something?
Actual queries and EXPLAINS as-is:
Query with 2-levels subqueries:
SELECT DISTINCT
"phdrug_phdrug"."id",
"phdrug_phdrug"."uuid",
"phdrug_phdrug"."default_description",
"phdrug_phdrug"."alternative_description",
"phdrug_phdrug"."ean",
"phdrug_phdrug"."mirror_ean",
"phdrug_phdrug"."parent_ean",
"phdrug_phdrug"."reg_num",
"phdrug_phdrug"."medika_code",
"phdrug_phdrug"."atc_iv",
"phdrug_phdrug"."product_type",
"phdrug_phdrug"."fraction",
"phdrug_phdrug"."active",
"phdrug_phdrug"."loyal",
"phdrug_phdrug"."patent",
"phdrug_phdrug"."chronics",
"phdrug_phdrug"."recipe",
"phdrug_phdrug"."deal",
"phdrug_phdrug"."specialized",
"phdrug_phdrug"."armored",
"phdrug_phdrug"."top_hight_speciality",
"phdrug_phdrug"."top_generic",
"phdrug_phdrug"."hight_speciality",
"phdrug_phdrug"."temp_8_15",
"phdrug_phdrug"."temp_15_25",
"phdrug_phdrug"."temp_2_8",
"phdrug_phdrug"."temp_less_15",
"phdrug_phdrug"."new",
"phdrug_phdrug"."mdk_internal_code",
"phdrug_phdrug"."mdk_single_id",
"phdrug_phdrug"."mdk_object_id",
"phdrug_phdrug"."is_from_mdk_db",
"phdrug_phdrug"."top",
"phdrug_phdrug"."laboratory_name",
"phdrug_phdrug"."laboratory_alternative_name",
"phdrug_phdrug"."imported",
"phdrug_phdrug"."imported_country",
"phdrug_phdrug"."laboratory_id",
"phdrug_phdrug"."specialty",
"phdrug_phdrug"."dimension_id",
"phdrug_phdrug"."featured",
"phdrug_phdrug"."top_ae_rank",
"phdrug_phdrug"."top_farma_rank"
FROM
"phdrug_phdrug"
INNER JOIN "monetary_drugprice" ON ( "phdrug_phdrug"."id" = "monetary_drugprice"."drug_id" )
INNER JOIN "phdrug_phdrugpicture" ON ( "phdrug_phdrug"."id" = "phdrug_phdrugpicture"."drug_id" )
WHERE
(
"monetary_drugprice"."id" IN (
SELECT
V0."id"
FROM
"monetary_drugprice" V0
WHERE
(
V0."pricelist_id" IN (
SELECT DISTINCT ON
( U0."id" ) U0."id"
FROM
"monetary_pricelist" U0
INNER JOIN "monetary_pricelistdestinations" U1 ON ( U0."id" = U1."pricelist_id" )
INNER JOIN "organization_organization" U2 ON ( U0."manager_id" = U2."id" )
INNER JOIN "courier_carrier_pricelists" U3 ON ( U0."id" = U3."pricelist_id" )
INNER JOIN "courier_carrier" U4 ON ( U3."carrier_id" = U4."id" )
INNER JOIN "courier_carrierdelivery" U5 ON ( U4."id" = U5."carrier_id" )
INNER JOIN "monetary_pricelistcountry" U6 ON ( U0."id" = U6."pricelist_id" )
WHERE
(
(
U0."expires" = FALSE
OR (
U0."expires" = TRUE
AND ( U0."datestart" AT TIME ZONE'UTC' ) :: DATE <= '2020-05-01'
AND ( U0."dateend" AT TIME ZONE'UTC' ) :: DATE >= '2020-05-01'
)
)
AND U0."active" = TRUE
AND U1."to_public" = TRUE
AND U2."organization_type" = 2
AND (
U5."dst_country" = 'MX'
OR U5."ignore_country_filter" = TRUE
)
AND U6."country" = 'MX'
AND U2."active" = TRUE
)
)
AND V0."stock" > 0
)
)
AND "phdrug_phdrug"."active" = TRUE
AND "phdrug_phdrugpicture"."is_main" = TRUE
)
ORDER BY
"phdrug_phdrug"."id" ASC,
"phdrug_phdrug"."default_description" ASC
Full explain: https://pastebin.com/jDy3FyKp
Query with 1-level subquery:
SELECT DISTINCT
"phdrug_phdrug"."id",
"phdrug_phdrug"."uuid",
"phdrug_phdrug"."default_description",
"phdrug_phdrug"."alternative_description",
"phdrug_phdrug"."ean",
"phdrug_phdrug"."mirror_ean",
"phdrug_phdrug"."parent_ean",
"phdrug_phdrug"."reg_num",
"phdrug_phdrug"."medika_code",
"phdrug_phdrug"."atc_iv",
"phdrug_phdrug"."product_type",
"phdrug_phdrug"."fraction",
"phdrug_phdrug"."active",
"phdrug_phdrug"."loyal",
"phdrug_phdrug"."patent",
"phdrug_phdrug"."chronics",
"phdrug_phdrug"."recipe",
"phdrug_phdrug"."deal",
"phdrug_phdrug"."specialized",
"phdrug_phdrug"."armored",
"phdrug_phdrug"."top_hight_speciality",
"phdrug_phdrug"."top_generic",
"phdrug_phdrug"."hight_speciality",
"phdrug_phdrug"."temp_8_15",
"phdrug_phdrug"."temp_15_25",
"phdrug_phdrug"."temp_2_8",
"phdrug_phdrug"."temp_less_15",
"phdrug_phdrug"."new",
"phdrug_phdrug"."mdk_internal_code",
"phdrug_phdrug"."mdk_single_id",
"phdrug_phdrug"."mdk_object_id",
"phdrug_phdrug"."is_from_mdk_db",
"phdrug_phdrug"."top",
"phdrug_phdrug"."laboratory_name",
"phdrug_phdrug"."laboratory_alternative_name",
"phdrug_phdrug"."imported",
"phdrug_phdrug"."imported_country",
"phdrug_phdrug"."laboratory_id",
"phdrug_phdrug"."specialty",
"phdrug_phdrug"."dimension_id",
"phdrug_phdrug"."featured",
"phdrug_phdrug"."top_ae_rank",
"phdrug_phdrug"."top_farma_rank"
FROM
"phdrug_phdrug"
INNER JOIN "monetary_drugprice" ON ( "phdrug_phdrug"."id" = "monetary_drugprice"."drug_id" )
INNER JOIN "phdrug_phdrugpicture" ON ( "phdrug_phdrug"."id" = "phdrug_phdrugpicture"."drug_id" )
WHERE
(
"monetary_drugprice"."id" IN (
SELECT
U0."id"
FROM
"monetary_drugprice" U0
INNER JOIN "monetary_pricelist" U1 ON ( U0."pricelist_id" = U1."id" )
INNER JOIN "monetary_pricelistdestinations" U2 ON ( U1."id" = U2."pricelist_id" )
INNER JOIN "organization_organization" U3 ON ( U1."manager_id" = U3."id" )
INNER JOIN "courier_carrier_pricelists" U4 ON ( U1."id" = U4."pricelist_id" )
INNER JOIN "courier_carrier" U5 ON ( U4."carrier_id" = U5."id" )
INNER JOIN "courier_carrierdelivery" U6 ON ( U5."id" = U6."carrier_id" )
INNER JOIN "monetary_pricelistcountry" U7 ON ( U1."id" = U7."pricelist_id" )
WHERE
(
(
U1."expires" = FALSE
OR (
U1."expires" = TRUE
AND ( U1."datestart" AT TIME ZONE'UTC' ) :: DATE <= '2020-05-01'
AND ( U1."dateend" AT TIME ZONE'UTC' ) :: DATE >= '2020-05-01'
)
)
AND U1."active" = TRUE
AND U2."to_public" = TRUE
AND U3."organization_type" = 2
AND (
U6."dst_country" = 'MX'
OR U6."ignore_country_filter" = TRUE
)
AND U7."country" = 'MX'
AND U3."active" = TRUE
AND U0."stock" > 0
)
)
AND "phdrug_phdrug"."active" = TRUE
AND "phdrug_phdrugpicture"."is_main" = TRUE
)
ORDER BY
"phdrug_phdrug"."id" ASC,
"phdrug_phdrug"."default_description" ASC
Full explain: https://pastebin.com/NidTZMxY
Query with only inner joins:
SELECT DISTINCT
"phdrug_phdrug"."id",
"phdrug_phdrug"."uuid",
"phdrug_phdrug"."default_description",
"phdrug_phdrug"."alternative_description",
"phdrug_phdrug"."ean",
"phdrug_phdrug"."mirror_ean",
"phdrug_phdrug"."parent_ean",
"phdrug_phdrug"."reg_num",
"phdrug_phdrug"."medika_code",
"phdrug_phdrug"."atc_iv",
"phdrug_phdrug"."product_type",
"phdrug_phdrug"."fraction",
"phdrug_phdrug"."active",
"phdrug_phdrug"."loyal",
"phdrug_phdrug"."patent",
"phdrug_phdrug"."chronics",
"phdrug_phdrug"."recipe",
"phdrug_phdrug"."deal",
"phdrug_phdrug"."specialized",
"phdrug_phdrug"."armored",
"phdrug_phdrug"."top_hight_speciality",
"phdrug_phdrug"."top_generic",
"phdrug_phdrug"."hight_speciality",
"phdrug_phdrug"."temp_8_15",
"phdrug_phdrug"."temp_15_25",
"phdrug_phdrug"."temp_2_8",
"phdrug_phdrug"."temp_less_15",
"phdrug_phdrug"."new",
"phdrug_phdrug"."mdk_internal_code",
"phdrug_phdrug"."mdk_single_id",
"phdrug_phdrug"."mdk_object_id",
"phdrug_phdrug"."is_from_mdk_db",
"phdrug_phdrug"."top",
"phdrug_phdrug"."laboratory_name",
"phdrug_phdrug"."laboratory_alternative_name",
"phdrug_phdrug"."imported",
"phdrug_phdrug"."imported_country",
"phdrug_phdrug"."laboratory_id",
"phdrug_phdrug"."specialty",
"phdrug_phdrug"."dimension_id",
"phdrug_phdrug"."featured",
"phdrug_phdrug"."top_ae_rank",
"phdrug_phdrug"."top_farma_rank"
FROM
"phdrug_phdrug"
INNER JOIN "monetary_drugprice" ON ( "phdrug_phdrug"."id" = "monetary_drugprice"."drug_id" )
INNER JOIN "monetary_pricelist" ON ( "monetary_drugprice"."pricelist_id" = "monetary_pricelist"."id" )
INNER JOIN "monetary_pricelistdestinations" ON ( "monetary_pricelist"."id" = "monetary_pricelistdestinations"."pricelist_id" )
INNER JOIN "organization_organization" ON ( "monetary_pricelist"."manager_id" = "organization_organization"."id" )
INNER JOIN "courier_carrier_pricelists" ON ( "monetary_pricelist"."id" = "courier_carrier_pricelists"."pricelist_id" )
INNER JOIN "courier_carrier" ON ( "courier_carrier_pricelists"."carrier_id" = "courier_carrier"."id" )
INNER JOIN "courier_carrierdelivery" ON ( "courier_carrier"."id" = "courier_carrierdelivery"."carrier_id" )
INNER JOIN "monetary_pricelistcountry" ON ( "monetary_pricelist"."id" = "monetary_pricelistcountry"."pricelist_id" )
INNER JOIN "phdrug_phdrugpicture" ON ( "phdrug_phdrug"."id" = "phdrug_phdrugpicture"."drug_id" )
WHERE
(
(
"monetary_pricelist"."expires" = FALSE
OR (
"monetary_pricelist"."expires" = TRUE
AND ( "monetary_pricelist"."datestart" AT TIME ZONE'UTC' ) :: DATE <= '2020-05-01'
AND ( "monetary_pricelist"."dateend" AT TIME ZONE'UTC' ) :: DATE >= '2020-05-01'
)
)
AND "monetary_pricelist"."active" = TRUE
AND "monetary_pricelistdestinations"."to_public" = TRUE
AND "organization_organization"."organization_type" = 2
AND (
"courier_carrierdelivery"."dst_country" = 'MX'
OR "courier_carrierdelivery"."ignore_country_filter" = TRUE
)
AND "monetary_pricelistcountry"."country" = 'MX'
AND "organization_organization"."active" = TRUE
AND "monetary_drugprice"."stock" > 0
AND "phdrug_phdrug"."active" = TRUE
AND "phdrug_phdrugpicture"."is_main" = TRUE
)
ORDER BY
"phdrug_phdrug"."id" ASC,
"phdrug_phdrug"."default_description" ASC
Full explain: https://pastebin.com/DaVztBuV

Troubleshooting at this level is difficult without seeing the database structure. I've had to write two different versions of the same script because the environments were different at the different sites.
Make sure the tables are properly indexed.
Make your subscript as part of the FROM statement and not the WHERE statement, unless its part of the IN clause.
Select *
from Table1 t1
left outer join (Select * from Table2) t2 on t1.field = t2.field
If its a large pull and/or large heavy used tables, then using temp tables will speed it as well. But it looks like your script is smaller and this is over kill.

Related

ORACLE SQL: Slow query when using "join table on id = id" vs "where id = number"

I'm having performance problem in a querie when I use a subquery to set an ID = number, and then join that subquery in the main query to look for that ID, this method takes about 150 seconds. But if I delete the subquery and look for the ID = number directly in the main query, it takes 0,5 second.
Here some code as exemple:
This is the example of 150 seconds
In this I set the cto_in_codigo in the With clause.
WITH CONTRATOS AS (
SELECT CTO_IN_CODIGO FROM MGCAR.CAR_CONTRATO
WHERE CTO_IN_CODIGO = 14393
)
SELECT
PT.PAR_IN_CODIGO,
PTC.PARCOR_IN_INDICE
FROM (
SELECT
MAX(PT.HPAR_IN_CODIGO) OVER (PARTITION BY PT.PAR_IN_CODIGO, PT.CTO_IN_CODIGO) HPAR_IN_CODIGO_MAX,
PT.HPAR_IN_CODIGO,
PT.CTO_IN_CODIGO,
PT.PAR_IN_CODIGO
FROM
QUERIE.PARCELA_TOTAL PT
JOIN CONTRATOS CTO
ON CTO.CTO_IN_CODIGO = PT.CTO_IN_CODIGO
WHERE
PT.PAR_DT_REAJUSTE <= TO_DATE('31/12/2017', 'DD/MM/YYYY')
) PT
LEFT OUTER JOIN (
SELECT
MAX(PTC.PARCOR_IN_CODIGO) OVER (PARTITION BY PTC.PAR_IN_CODIGO, PTC.CTO_IN_CODIGO) PARCOR_IN_CODIGO_MAX,
PTC.PARCOR_IN_CODIGO,
PTC.CTO_IN_CODIGO,
PTC.PAR_IN_CODIGO,
PTC.HPAR_IN_CODIGO,
PTC.PARCOR_IN_INDICE
FROM
QUERIE.PARCELA_TOTAL_CORRECAO PTC
JOIN CONTRATOS CTO
ON CTO.CTO_IN_CODIGO = PTC.CTO_IN_CODIGO
) PTC
ON PTC.CTO_IN_CODIGO = PT.CTO_IN_CODIGO
AND PTC.PAR_IN_CODIGO = PT.PAR_IN_CODIGO
AND PTC.HPAR_IN_CODIGO = PT.HPAR_IN_CODIGO
AND PTC.PARCOR_IN_CODIGO = PTC.PARCOR_IN_CODIGO_MAX
WHERE
PT.HPAR_IN_CODIGO = PT.HPAR_IN_CODIGO_MAX
and this is the 0,5 sec.
in this I set the cto_in_codigo inside each query
SELECT
PT.PAR_IN_CODIGO,
PTC.PARCOR_IN_INDICE
FROM (
SELECT
MAX(PT.HPAR_IN_CODIGO) OVER (PARTITION BY PT.PAR_IN_CODIGO, PT.CTO_IN_CODIGO) HPAR_IN_CODIGO_MAX,
PT.HPAR_IN_CODIGO,
PT.CTO_IN_CODIGO,
PT.PAR_IN_CODIGO
FROM
QUERIE.PARCELA_TOTAL PT
WHERE
PT.PAR_DT_REAJUSTE <= TO_DATE('31/12/2017', 'dd/MM/yyyy')
AND PT.CTO_IN_CODIGO = 14393
) PT
LEFT OUTER JOIN (
SELECT
MAX(PTC.PARCOR_IN_CODIGO) OVER (PARTITION BY PTC.PAR_IN_CODIGO, PTC.CTO_IN_CODIGO) PARCOR_IN_CODIGO_MAX,
PTC.PARCOR_IN_CODIGO,
PTC.CTO_IN_CODIGO,
PTC.PAR_IN_CODIGO,
PTC.HPAR_IN_CODIGO,
PTC.PARCOR_IN_INDICE
FROM
QUERIE.PARCELA_TOTAL_CORRECAO PTC
WHERE
PTC.CTO_IN_CODIGO = 14393
) PTC
ON PTC.CTO_IN_CODIGO = PT.CTO_IN_CODIGO
AND PTC.PAR_IN_CODIGO = PT.PAR_IN_CODIGO
AND PTC.HPAR_IN_CODIGO = PT.HPAR_IN_CODIGO
AND PTC.PARCOR_IN_CODIGO = PTC.PARCOR_IN_CODIGO_MAX
WHERE
PT.HPAR_IN_CODIGO = PT.HPAR_IN_CODIGO_MAX
what is confusing to me is that the with clause returns just one row with the cto_in_codigo number, much like if I hard code then inside each query like the second code. What is could be causing this super delay?

Recursive CTE and SELECT

I have written a fairly simple recursive CTE statement. The purpose is that it looks up a structure and returns the top level item
Here is the code
WITH cte_BOM(parent_serial_id, serial_id, serial_batch_no, sort)
AS (SELECT BOM.parent_serial_id, BOM.serial_id, p.serial_batch_no, 1
FROM serial_status AS BOM
INNER JOIN item_serial_nos p ON BOM.parent_serial_id = p.serial_id
WHERE BOM.serial_id = '16320' AND BOM.is_current = 'Y'
UNION ALL
SELECT
BOM1.parent_serial_id, bom1.serial_id, p1.serial_batch_no, cte_BOM.sort + 1
FROM cte_BOM
INNER JOIN serial_status AS BOM1 ON cte_BOM.parent_serial_id =
BOM1.serial_id
INNER JOIN item_serial_nos p1 ON BOM1.parent_serial_id = p1.serial_id
WHERE BOM1.is_current = 'Y'
)
SELECT TOP 1
cte_BOM.*
FROM
cte_BOM
ORDER BY sort desc
As you can see I just hard code the serial_id at the moment. What I now need to accomplish is to run this cte against a subset of data. I’m now stuck on how I can do this.
So I would produce a list of serial_ids by means of another select statement, and then for each row use this serial_id in place of the ones that is currently hard coded and return the 1st record. Importantly if a serial_id has no parent that should still return a row
The second SELECT would be this:
SELECT serial_id
FROM
item_serial_nos
WHERE
item_serial_nos.item_id = '15683'
Any suggestions appreciated. (using SQL 2008 R2)
If I understand your goal correctly, you can just remove the hardcoded serial_id from the cte and add the start serial_id:
WITH cte_BOM(parent_serial_id, serial_id, serial_batch_no, sort, Original_Serial_id)
AS (
SELECT BOM.parent_serial_id
, BOM.serial_id
, p.serial_batch_no
, 1
, BOM.serial_id
FROM serial_status AS BOM
INNER JOIN item_serial_nos p
ON BOM.parent_serial_id = p.serial_id
WHERE BOM.is_current = 'Y'
UNION ALL
SELECT BOM1.parent_serial_id
, bom1.serial_id
, p1.serial_batch_no
, cte_BOM.sort + 1
, cte_BOM.Original_Serial_id
FROM cte_BOM
INNER JOIN serial_status AS BOM1
ON cte_BOM.parent_serial_id = BOM1.serial_id
INNER JOIN item_serial_nos p1
ON BOM1.parent_serial_id = p1.serial_id
WHERE BOM1.is_current = 'Y'
)
SELECT cte_BOM.*
FROM cte_BOM
INNER JOIN (
SELECT cte_BOM.Original_Serial_id
, MAX(sort) sort_max
FROM cte_BOM
WHERE cte_BOM.Original_Serial_id IN (
SELECT serial_id
FROM item_serial_nos
WHERE item_serial_nos.item_id = '15683'
)
GROUP BY cte_BOM.Original_Serial_id
) max_cte
ON max_cte.Original_Serial_id = cte_BOM.Original_Serial_id
AND max_cte.sort_max = cte_BOM.sort
The recursive CTE is only executed when it's called from the last select, so it is only executed for those records that are selected in the IN query. So you shouldn't suffer a performance hit because of this.

Alias to a join query

( SELECT Vraboteni.v, Ulogi.p, Zarabotuva.honorar
FROM Vraboteni, Ulogi, Zarabotuva
WHERE Vraboteni.v = Ulogi.v
AND ima_uloga='sporedna'
AND Ulogi.p = Zarabotuva.p
) as F
JOIN
( SELECT Vraboteni.v, Ulogi.p, Zarabotuva.honorar
FROM Vraboteni, Ulogi, Zarabotuva
WHERE Vraboteni.v = Ulogi.v
AND ima_uloga='glavna'
AND Ulogi.p = Zarabotuva.p
) as S
ON (F.honorar > S.honorar)
Can anyone tell me what is wrong with the syntax that I am using above? I'm having the same issue over multiple queries and I'm not sure I quite understand how I am supposed to assign an alias when I use a join (having the same issue when trying to assign alliases to multiple nested joins)
The subselects you join should be considered as a normal table or view, so imagine they are, and your select statement looks like this:
SELECT1 as F
JOIN SELECT2 as S ON (F.honorar > S.honorar)
This statement is missing essential parts, like a SELECT and FROM clause.
So fix it, if you want to join two selects, you should encapsulate them in another select, so you get:
SELECT
S.*,
F.*
FROM
(SELECT ... ) AS F
JOIN (SELECT ...) AS S ON (F.honorar > S.honorar)
Alternatively, you could get rid of the two subselects, use normal joins for all your tables, and end up with a query like this:
SELECT
Vraboteni.v, Ulogi.p, Zarabotuva.honorar
FROM
Vraboteni AS v1
JOIN Ulogi AS u1 ON v1.v = u1.v
JOIN Zarabotuva AS z1 ON u1.p = z1.p
CROSS JOIN Vraboteni AS v2 -- Not sure if you would want/need a condition here
JOIN Ulogi AS u2 ON v2.v = u2.v
JOIN Zarabotuva AS z2 ON u2.p = z2.p
WHERE
v1.ima_uloga = 'sporedna' -- Not sure if this should be v1, u1 or z1
AND v2.ima_uloga = 'glavna'
AND z1.honorar > z2.honorar
this is what you need to do:
SELECT *
FROM
(SELECT Vraboteni.v
, Ulogi.p
, Zarabotuva.honorar
FROM Vraboteni
, Ulogi
, Zarabotuva
WHERE Vraboteni.v = Ulogi.v
AND ima_uloga = 'sporedna'
AND Ulogi.p = Zarabotuva.p) AS F
JOIN
(SELECT Vraboteni.v
, Ulogi.p
, Zarabotuva.honorar
FROM Vraboteni
, Ulogi
, Zarabotuva
WHERE Vraboteni.v = Ulogi.v
AND ima_uloga = 'glavna'
AND Ulogi.p = Zarabotuva.p) AS S ON F.honorar > S.honorar;

SQL Server 2012 : Multiple Queries in One Stored Procedure

How do I create Stored Procedure on these queries and he output should show which check the anomaly was captured from, along with all the relevant data.
SELECT cm.Cust_id, cm.cust_ref_id4, cm.cust_ref_id3, cm.plan_group, cm.Company_name, cm.Cust_firstname, cm.Cust_lastname
COALESCE(c.pkCustomerID, c2.fkCustomerID, c3.pkCustomerID, c4.pkCustomerID) AS pkCustomerID, c3.CompanyName FROM PRODUCTIONSQL.[SigmaPaTri].[dbo].[CUSTOMER_MASTER] cm
LEFT JOIN PHOENIX.CORE.dbo.Customers AS c ON cust_ref_id4 = c.pkCustomerID AND cm.cust_ref_id3 = c.pkCustomerID AND cm.cust_ref_id3 >= 1000000 AND cm.Cust_firstname + ' ' + cm.Cust_lastname = c.CompanyName
LEFT JOIN PHOENIX.CORE.dbo.Contracts AS c2 ON cm.cust_ref_id3 = c2.ConfirmationNumber
WHERE cm.cust_status IN ('A','P','R','G') AND COALESCE(c.pkCustomerID, c2.fkCustomerID) IS NULL ORDER BY cust_ref_id4;
and
SELECT [pkCustomerID],b.[pkContractID],[pkCustomerTypeID],[CustomerType],b.[ContractType] AS Contractype1,c.[ContractType]
AS Contractype2 FROM [CORE].[dbo].[Customers] a
JOIN [CORE].[dbo].[CustomerTypes] ON [pkCustomerTypeID] = [fkCustomerTypeID]
LEFT JOIN (SELECT [pkContractID],[ContractType],[fkCustomerID] FROM [CORE].[dbo].[Contracts]
JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID] WHERE [ContractType] NOT LIKE 'Holdover%')b ON a.pkCustomerID=b.fkCustomerID
LEFT JOIN (SELECT [pkContractID],[fkCustomerID],[ContractType] FROM [CORE].[dbo].[Contracts]
JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID] WHERE ContractType LIKE 'Holdover%')c ON b.fkCustomerID=c.fkCustomerID WHERE [CustomerType] IN ('Customer','Former Customer') AND (b.ContractType IS NULL OR c.ContractType IS NULL)
You question is lacking a very important piece of information, the explanation of what you are trying to do. I took a shot in the dark here as a guess to what you might be looking for. BTW, I ran this through a formatter so it was legible.
SELECT 'Found in query1'
,cm.Cust_id
,cm.cust_ref_id4
,cm.cust_ref_id3
,cm.plan_group
,cm.Company_name
,cm.Cust_firstname
,cm.Cust_lastname
,COALESCE(c.pkCustomerID, c2.fkCustomerID, c3.pkCustomerID, c4.pkCustomerID) AS pkCustomerID
,c3.CompanyName
FROM PRODUCTIONSQL.[SigmaPaTri].[dbo].[CUSTOMER_MASTER] cm
LEFT JOIN PHOENIX.CORE.dbo.Customers AS c ON cust_ref_id4 = c.pkCustomerID
AND cm.cust_ref_id3 = c.pkCustomerID
AND cm.cust_ref_id3 >= 1000000
AND cm.Cust_firstname + ' ' + cm.Cust_lastname = c.CompanyName
LEFT JOIN PHOENIX.CORE.dbo.Contracts AS c2 ON cm.cust_ref_id3 = c2.ConfirmationNumber
WHERE cm.cust_status IN (
'A'
,'P'
,'R'
,'G'
)
AND COALESCE(c.pkCustomerID, c2.fkCustomerID) IS NULL
SELECT 'Found in query 2'
,[pkCustomerID]
,b.[pkContractID]
,[pkCustomerTypeID]
,[CustomerType]
,b.[ContractType] AS Contractype1
,c.[ContractType] AS Contractype2
FROM [CORE].[dbo].[Customers] a
INNER JOIN [CORE].[dbo].[CustomerTypes] ON [pkCustomerTypeID] = [fkCustomerTypeID]
LEFT JOIN (
SELECT [pkContractID]
,[ContractType]
,[fkCustomerID]
FROM [CORE].[dbo].[Contracts]
INNER JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID]
WHERE [ContractType] NOT LIKE 'Holdover%'
) b ON a.pkCustomerID = b.fkCustomerID
LEFT JOIN (
SELECT [pkContractID]
,[fkCustomerID]
,[ContractType]
FROM [CORE].[dbo].[Contracts]
INNER JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID]
WHERE ContractType LIKE 'Holdover%'
) c ON b.fkCustomerID = c.fkCustomerID
WHERE [CustomerType] IN (
'Customer'
,'Former Customer'
)
AND (
b.ContractType IS NULL
OR c.ContractType IS NULL
)

another union all selecting all the rows that have not already been selected

Right now i have 2 select statements that are joined by a union what i was hopping to do was maybe name the first query like query1 and the second one query2 and then in my third query do a where bookno not in query1 or query2.
SELECT distinct t0.BOOKNO, t0.PaxName, t0.Locator, t0.FDATE7,
t0.BOARD, t0.ALIGHT, t0.AIRLINE, t0.FNUMBR, t0.DEP,
t0.ARR, t0.TOUR, t0.ROUTE,
t1.tour, t1.route, t1.sfrom , t1.sto,t1.seq,t0.seq, 'yes'
FROM
( SELECT TOP (100) PERCENT test.dbo.BNAMES.BOOKNO, RTRIM(test.dbo.BNAMES.SRNAME) + '/' + RTRIM(test.dbo.BNAMES.FIRST) + RTRIM(test.dbo.BNAMES.TITLE)
AS PaxName, test.dbo.PNRS.PNR AS Locator, test.dbo.PNRSECTORS.FDATE7, test.dbo.PNRSECTORS.BOARD, test.dbo.PNRSECTORS.ALIGHT,
test.dbo.PNRSECTORS.AIRLINE, test.dbo.PNRSECTORS.FNUMBR, test.dbo.PNRSECTORS.DEP, test.dbo.PNRSECTORS.ARR, test.dbo.BOOKINGS.TOUR,
test.dbo.BOOKINGS.ROUTE, test.dbo.BSTAGES.SEQ,(test.dbo.PNRSECTORS.BOARD + test.dbo.PNRSECTORS.ALIGHT) as both
FROM test.dbo.BOOKINGS LEFT OUTER JOIN
test.dbo.BNAMES ON test.dbo.BOOKINGS.BOOKNO = test.dbo.BNAMES.BOOKNO LEFT OUTER JOIN
test.dbo.BSTAGES ON test.dbo.BNAMES.BOOKNO = test.dbo.BSTAGES.BOOKNO LEFT OUTER JOIN
test.dbo.PNRSECTORS ON test.dbo.BSTAGES.SCODE = test.dbo.PNRSECTORS.SKEY LEFT OUTER JOIN
test.dbo.PNRS ON test.dbo.PNRSECTORS.PNRKEY = test.dbo.PNRS.PNRKEY
WHERE (test.dbo.BSTAGES.STYPE = 3)
ORDER BY test.dbo.BOOKINGS.BOOKNO, test.dbo.BNAMES.SEQ, locator
) t0
INNER JOIN ( SELECT TOUR, ROUTE, OFFSET, SEQ, SCODE, SFROM, STO, (SFROM + STO) AS BOTH
FROM test.dbo.TSTAGES
) t1 ON t1.tour = t0.tour and t1.route = t0.route and (t0.both = t1.both)
union all
SELECT distinct t0.BOOKNO, t0.PaxName, t0.Locator, t0.FDATE7,
t0.BOARD, t0.ALIGHT, t0.AIRLINE, t0.FNUMBR, t0.DEP,
t0.ARR, t0.TOUR, t0.ROUTE,
t1.tour, t1.route, t1.sfrom , t1.sto,t1.seq,t0.seq,'YES'
FROM
( SELECT TOP (100) PERCENT test.dbo.BNAMES.BOOKNO, RTRIM(test.dbo.BNAMES.SRNAME) + '/' + RTRIM(test.dbo.BNAMES.FIRST) + RTRIM(test.dbo.BNAMES.TITLE)
AS PaxName, test.dbo.PNRS.PNR AS Locator, test.dbo.PNRSECTORS.FDATE7, test.dbo.PNRSECTORS.BOARD, test.dbo.PNRSECTORS.ALIGHT,
test.dbo.PNRSECTORS.AIRLINE, test.dbo.PNRSECTORS.FNUMBR, test.dbo.PNRSECTORS.DEP, test.dbo.PNRSECTORS.ARR, test.dbo.BOOKINGS.TOUR,
test.dbo.BOOKINGS.ROUTE, test.dbo.BSTAGES.SEQ,(test.dbo.PNRSECTORS.BOARD + test.dbo.PNRSECTORS.ALIGHT) as both
FROM test.dbo.BOOKINGS LEFT OUTER JOIN
test.dbo.BNAMES ON test.dbo.BOOKINGS.BOOKNO = test.dbo.BNAMES.BOOKNO LEFT OUTER JOIN
test.dbo.BSTAGES ON test.dbo.BNAMES.BOOKNO = test.dbo.BSTAGES.BOOKNO LEFT OUTER JOIN
test.dbo.PNRSECTORS ON test.dbo.BSTAGES.SCODE = test.dbo.PNRSECTORS.SKEY LEFT OUTER JOIN
test.dbo.PNRS ON test.dbo.PNRSECTORS.PNRKEY = test.dbo.PNRS.PNRKEY
WHERE (test.dbo.BSTAGES.STYPE = 1)
ORDER BY test.dbo.BOOKINGS.BOOKNO, test.dbo.BNAMES.SEQ, locator
) t0
INNER JOIN ( SELECT TOUR, ROUTE, OFFSET, SEQ, SCODE, SFROM, STO, (SFROM + STO) AS BOTH
FROM test.dbo.TSTAGES
) t1 ON t1.tour = t0.tour and t1.route = t0.route and t1.seq = t0.seq and (t0.both = t1.both)
order by bookno
END
How about using WITH? You can declare you queries, join them with UNION and them search for the ones not there.
Take a look here: Multiple Select Statements using SQL Server 2005 "WITH" Statement . It should help you get started.
By using WITH statement, you will isolate logic of your queries, making your overall query more understandable.
just wrap your logic around what you wrote:
select bookno
where key not in (
your big select statement...
)