Complex SQL query with optional tables

Status
Not open for further replies.
Hey guys,

Building a new video inventory system for my website. (MySQL)

Single Header record. (linked to a contract)

Multiple Detail Records - 4 in this case. (linked to the header record)

Multiple Inventory Records - again, 4 - (each detail record points to one specific inventory record, but the inventory may be the target of multiple detail records)

Optional Link records - 3 (the Link record is owned by a specific Inventory record, but it is an OPTIONAL record)

actual query

Code:
$query = "SELECT 
					video_control_detail.id AS videoDetailId, 
					video_control_detail.video_inventory_id AS videoInventoryId, 
					video_control_detail.start_date AS videoDetailStartDate,
					video_links.description AS videoLinkDescription, 
					video_links.link AS videoLinkTarget,  
					video_inventory.* 
			FROM 
				video_control_detail, video_inventory, video_links   
			WHERE video_control_detail.header_control_id = '$this->VideoInventoryControlId'   
			AND video_inventory.id = video_control_detail.video_inventory_id 
			AND video_links.video_id = video_control_detail.video_inventory_id  
			ORDER BY video_control_detail.start_date ASC";

Testing, I know there are 4 records I want returned. I am getting 3. The 3 that have optional link information (an entry in the video_links table).

I have hit this problem in the past, but I just bailed, and used a separate query to gather the optional data.

Question: Is there a way to include that into a single query? Or does the fact that there is no entry in that third table preclude the record from being selected?

:)
 
Just for my own readability, here is the query I propose using ANSI joins.

Code:
SELECT
    video_control_detail.id AS videoDetailId,
    video_control_detail.video_inventory_id AS videoInventoryId,
    video_control_detail.start_date AS videoDetailStartDate,
    video_links.description AS videoLinkDescription,
    video_links.link AS videoLinkTarget, 
    video_inventory.*
FROM video_inventory 

INNER JOIN video_control_detail
  ON video_inventory.id = video_control_detail.video_inventory_id

LEFT JOIN video_links 
  ON video_control_detail.video_inventory_id = video_links.video_id
  
WHERE video_control_detail.header_control_id = '$this->VideoInventoryControlId'   

ORDER BY video_control_detail.start_date ASC
 

wallinbl

Ars Legatus Legionis
14,319
Subscriptor
[url=http:/civis/viewtopic.php?p=29014881#p29014881:6ljub3vj said:
Hadesdarklord[/url]":6ljub3vj]Thank you very much for that.

The downsides of being a self-taught SQL guy is that the limits of your experience are the limits of your experience.

I will take your code and play with it (thank you VERY much) and read the hell up on joins.

:D
If I were you, I'd stop writing joins implicitly (FROM table1, table2, etc) and start writing them explicitly. It's both more clear and more common, aside from being less risky (the implicit allows you to inadvertently cross join).
 

C0rinthian

Ars Tribunus Angusticlavius
6,858
[url=http:/civis/viewtopic.php?p=29014881#p29014881:3tj6rsgr said:
Hadesdarklord[/url]":3tj6rsgr]Thank you very much for that.

The downsides of being a self-taught SQL guy is that the limits of your experience are the limits of your experience.

I will take your code and play with it (thank you VERY much) and read the hell up on joins.

:D
If I were you, I'd stop writing joins implicitly (FROM table1, table2, etc) and start writing them explicitly. It's both more clear and more common, aside from being less risky (the implicit allows you to inadvertently cross join).

++ to this. It's confusing when your joining conditions are mixed in with your filtering conditions in the WHERE clause. It's also much easier to forget a joining condition and end up with a cartesian/cross join. (And I could never remember the proper structure of the (+) notation)

Also a good idea to brush up on how/why the various joins work: http://blog.codinghorror.com/a-visual-e ... sql-joins/
 
Just following up to see if that solved your issue.

Personally I only use * when I need to see the data, not for actual queries. You might consider explicitly calling out the columns you need for your app. Also indexing.... not sure if you set any primary keys on those tables, but it would be a good idea. I know you are new to the SQL world, but its better you learn best practices now. If you have any other questions, please ask.
 

Schluppy

Ars Tribunus Militum
2,486
[url=http:/civis/viewtopic.php?p=29038041#p29038041:28ccmhoa said:
FoamingPipeSnake[/url]":28ccmhoa]
Personally I only use * when I need to see the data, not for actual queries. You might consider explicitly calling out the columns you need for your app.

Any particular reason why? Excepting unusually wide tables, I find myself using * more often lately just for the sake of simplicity when making changes (scope creep++); one less chunk of code to edit.
 

wallinbl

Ars Legatus Legionis
14,319
Subscriptor
[url=http:/civis/viewtopic.php?p=29038081#p29038081:2yf98nw1 said:
Schluppy[/url]":2yf98nw1]
[url=http:/civis/viewtopic.php?p=29038041#p29038041:2yf98nw1 said:
FoamingPipeSnake[/url]":2yf98nw1]
Personally I only use * when I need to see the data, not for actual queries. You might consider explicitly calling out the columns you need for your app.

Any particular reason why? Excepting unusually wide tables, I find myself using * more often lately just for the sake of simplicity when making changes (scope creep++); one less chunk of code to edit.
It's always better to be explicit, so you avoid any unwanted side effects or bugs.

If the set of columns you need is entirely within an index, it's much faster. For example, SELECT CustomerId, Name will be much more efficient than SELECT * if there's a related index.

Never use SELECT * with something like an INSERT ... SELECT, as something as seemingly innocuous as adding a column to the SELECTed table will break that query.

If you're using EXISTS(), you should probably only return the primary key, as it will generally be much easier for SQL to accomplish that.

If you use SELECT *, you open yourself to the possibility that a future database change introduces a column to your query with a conflicting name, and it affects code you didn't touch during the change. Consider the following:
Products: ProductId, Name, Description, Price
Orders: OrderId, Date, CustomerId
OrderLines: OrderId, ProductId, Quantity

Your report uses SELECT * FROM Orders INNER JOIN OrderLines ON Orders.OrderId = OrderLines.OrderID INNER JOIN Products ON OrderLines.ProductId = Products.ProductId WHERE CustomerId = @CustomerId to show a customer their purchase history. At some point, you realize you should track the price at the time of the order, and you add Price to the OrderLines table. Your SELECT * now has two different Price columns returned, and you don't know which Price is going to get used.

(The example is simplified to illustrate a point, but it's a real concern with SELECT *).
 
[url=http:/civis/viewtopic.php?p=29042987#p29042987:w3rpgknx said:
Nazgutek[/url]":w3rpgknx]
[url=http:/civis/viewtopic.php?p=29038515#p29038515:w3rpgknx said:
wallinbl[/url]":w3rpgknx]
If you're using EXISTS(), you should probably only return the primary key, as it will generally be much easier for SQL to accomplish that.

I got into the habit of going even simpler and just using EXISTS (SELECT 1 FROM ... )

I was under the impression that EXISTS (SELECT * FROM ...) was optimized to the point--in SQL Server, at least--to not make much of a difference in performance. This blog post I stumbled upon links to discussions that make it seem like there is a trivial hit taken for SELECT *: http://blog.sqlauthority.com/2010/0...l-from-table-vs-if-existsselect-1-from-table/

Personally, I generally use EXISTS (SELECT NULL FROM ...), which one-ups both of you ;)
 
[url=http:/civis/viewtopic.php?p=29056379#p29056379:q8gsgwhq said:
ledbutter[/url]":q8gsgwhq]
[url=http:/civis/viewtopic.php?p=29042987#p29042987:q8gsgwhq said:
Nazgutek[/url]":q8gsgwhq]
[url=http:/civis/viewtopic.php?p=29038515#p29038515:q8gsgwhq said:
wallinbl[/url]":q8gsgwhq]
If you're using EXISTS(), you should probably only return the primary key, as it will generally be much easier for SQL to accomplish that.

I got into the habit of going even simpler and just using EXISTS (SELECT 1 FROM ... )

I was under the impression that EXISTS (SELECT * FROM ...) was optimized to the point--in SQL Server, at least--to not make much of a difference in performance.

Yup. From T-SQL Querying, by Itzik Ben-Gan et al, "Another interesting thing about EXISTS is that, from an indexing selection perspective, the optimizer ignores the subquery’s SELECT list."
 

wallinbl

Ars Legatus Legionis
14,319
Subscriptor
[url=http:/civis/viewtopic.php?p=29056379#p29056379:1zp8njnu said:
ledbutter[/url]":1zp8njnu]
[url=http:/civis/viewtopic.php?p=29042987#p29042987:1zp8njnu said:
Nazgutek[/url]":1zp8njnu]
[url=http:/civis/viewtopic.php?p=29038515#p29038515:1zp8njnu said:
wallinbl[/url]":1zp8njnu]
If you're using EXISTS(), you should probably only return the primary key, as it will generally be much easier for SQL to accomplish that.

I got into the habit of going even simpler and just using EXISTS (SELECT 1 FROM ... )

I was under the impression that EXISTS (SELECT * FROM ...) was optimized to the point--in SQL Server, at least--to not make much of a difference in performance. This blog post I stumbled upon links to discussions that make it seem like there is a trivial hit taken for SELECT *: http://blog.sqlauthority.com/2010/0...l-from-table-vs-if-existsselect-1-from-table/

Personally, I generally use EXISTS (SELECT NULL FROM ...), which one-ups both of you ;)
I suppose, though I'm generally only using that when I need to deal with a compound key or something like that, and I'm already specifying in the WHERE clause, the columns are already indexed, so they've already been read. It's not actually returning them anywhere, so specifying them isn't impacting performance. I find it a bit more readable (even though admittedly the columns are in the WHERE clause and anyone that can read SQL can figure it out anyway).
 

Fristie Blade

Ars Tribunus Militum
1,722
Subscriptor++
[url=http:/civis/viewtopic.php?p=29056379#p29056379:27y7saj0 said:
ledbutter[/url]":27y7saj0]
Personally, I generally use EXISTS (SELECT NULL FROM ...), which one-ups both of you ;)
That's exactly what I came to post here. Suddenly I feel less lonely up there on my throne when I frown on some of my colleagues' work :)
 
I prefer SELECT 1, personally.... muscle memory. I think we can all agree SELECT * in an EXISTS is bad (or can be based on wide tables).

I had an interesting case once where I was using a NOT EXISTS to insert data into a large table (~1 billion rows). In that instance, I found doing a left join to my temp table was much faster than using NOT EXISTS, even though both used each tables primary key.
 

Nazgutek

Ars Scholae Palatinae
1,298
[url=http:/civis/viewtopic.php?p=29056579#p29056579:3neczhhc said:
bral[/url]":3neczhhc]
Yup. From T-SQL Querying, by Itzik Ben-Gan et al, "Another interesting thing about EXISTS is that, from an indexing selection perspective, the optimizer ignores the subquery’s SELECT list."

Exactly the reason why I use SELECT 1... less typing! ;)
 

QuadDamaged

Ars Praefectus
3,983
Subscriptor++
In the same vein, when I am drafting SQL statements (because why should I stop and think when I can just type-away! :/) I always use the following style for WHERE clauses:

Code:
SELECT
  Foo,
  Bar,
  *
FROM
  Db..Table
WHERE 1=1
  AND Foo<>Bar
  AND Baz='Frob'

so I can cut statements without stopping to think whether or not I need an AND (same goes for the coma in my select clause before star)
 

Fristie Blade

Ars Tribunus Militum
1,722
Subscriptor++
[url=http:/civis/viewtopic.php?p=29087889#p29087889:2srzk9ck said:
QuadDamaged[/url]":2srzk9ck]In the same vein, when I am drafting SQL statements (because why should I stop and think when I can just type-away! :/) I always use the following style for WHERE clauses:

Code:
SELECT
  Foo,
  Bar,
  *
FROM
  Db..Table
WHERE 1=1
  AND Foo<>Bar
  AND Baz='Frob'

so I can cut statements without stopping to think whether or not I need an AND (same goes for the coma in my select clause before star)

I agree that 1=1 might be handy to quickly enable/disable the other restriction parts during development.

But the bad thing is I have seen colleagues then apply the resulting query as-is including the 1=1 into the final release that goes to production.
Hell I have even seen systems building dynamic restrictions in prod like that.
Fucking ugly to some one as me :mad:

/end of rant
 
[url=http:/civis/viewtopic.php?p=29087991#p29087991:102y6k2s said:
Richard Berg[/url]":102y6k2s]What's wrong with 1=1 in production?

Are you serious?

Though it won't make a meaningful affect on performance, it just shows a lack of detail by the original query writer. I can't stand sloppy, and in fact was one of the reasons I quit my last job.
 

Fristie Blade

Ars Tribunus Militum
1,722
Subscriptor++
[url=http:/civis/viewtopic.php?p=29087991#p29087991:2lw2l1u6 said:
Richard Berg[/url]":2lw2l1u6]What's wrong with 1=1 in production?
Imho it is wrong to use such dummy statements like 1=1 in production because they have no functional meaning or intended side-effect.
All they can do is make the query slower or generate unintentional side effects.
They add no value but will need to be parsed and evaluated.
Granted, it will not add much time or overhead to evaluate the 1= 1, but nor does it take much time to avoid it being there in the first place.

Whenever I see that in production, I always wonder "The dev did not consider it important enough to take that useless clause out, so what else did they not deem important to look at. What else did they not optimize because it all just worked anyway. That is until it needs to work in production where we have millions of records and bla bla ... and where indexes make a huge difference just like setting the correct restrictions or how to join the data etc."
Maybe in the past I've seen too much stuff where I needed to bank my head (full cross joins on large tables and then doing some restrictions when what they wanted could have been achieved by inner joins and then wondering that it is all so slow) that I got sensitive about laziness ;)

/End of rant :)
 

wallinbl

Ars Legatus Legionis
14,319
Subscriptor
[url=http:/civis/viewtopic.php?p=29088179#p29088179:29g3wogo said:
FoamingPipeSnake[/url]":29g3wogo]
[url=http:/civis/viewtopic.php?p=29087991#p29087991:29g3wogo said:
Richard Berg[/url]":29g3wogo]What's wrong with 1=1 in production?

Are you serious?

Though it won't make a meaningful affect on performance, it just shows a lack of detail by the original query writer. I can't stand sloppy, and in fact was one of the reasons I quit my last job.
Some things are important to scrutinize. That one is not.
 
[url=http:/civis/viewtopic.php?p=29088193#p29088193:2w2kfv6k said:
wallinbl[/url]":2w2kfv6k]
[url=http:/civis/viewtopic.php?p=29088179#p29088179:2w2kfv6k said:
FoamingPipeSnake[/url]":2w2kfv6k]
[url=http:/civis/viewtopic.php?p=29087991#p29087991:2w2kfv6k said:
Richard Berg[/url]":2w2kfv6k]What's wrong with 1=1 in production?

Are you serious?

Though it won't make a meaningful affect on performance, it just shows a lack of detail by the original query writer. I can't stand sloppy, and in fact was one of the reasons I quit my last job.
Some things are important to scrutinize. That one is not.

Agree. It still bugs though.
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
Are you serious?
Yes.

They add no value but will need to be parsed and evaluated.
They make the formatting neater.

Tab characters also need to be parsed despite not adding performance, but they too are worth it. Value is in the eyes of the human readers, not the dumb machines (which will cache query plans regardless).
 

wallinbl

Ars Legatus Legionis
14,319
Subscriptor
[url=http:/civis/viewtopic.php?p=29088191#p29088191:2mys25y9 said:
Fristie Blade[/url]":2mys25y9]
Granted, it will not add much time or overhead to evaluate the 1= 1, but nor does it take much time to avoid it being there in the first place.

Whenever I see that in production, I always wonder "The dev did not consider it important enough to take that useless clause out, so what else did they not deem important to look at. What else did they not optimize because it all just worked anyway. That is until it needs to work in production where we have millions of records and bla bla ... and where indexes make a huge difference just like setting the correct restrictions or how to join the data etc."

Prior to EntityFramework, we rolled our own ORM. 1 = 1 was prevalent mostly as a way to simplify the code and make it more readable, since the queries were going to be built based on the calling code and we'd otherwise have to track whether to prepend the current clause with AND or OR. The basic list interface was queryable from calling code, and therefore SQL was constructed on the fly to respond to the call. While we could have avoided 1 = 1, it would have just added more code and made it less readable.

We have some dynamic reporting tools available to users that likewise use 1 = 1 to simplify code, since the users can use the UI to build all sorts of random things, and the SQL is being constructed in response to input.

And, like Richard said, I do leave it in there in some places just because it improves readability, even within a static SELECT in a stored proc. The 1 = 1 goes on the line with WHERE, and the remainder of the lines are clearly started with AND or OR and visually line up well with each other. The brain can parse them much faster when there's a consistent layout.
 

fitten

Ars Legatus Legionis
55,634
Subscriptor++
Yeah, the WHERE 1=1 bit helps out a bit when constructing WHERE clauses conditionals that are dependent upon other conditions. You can do that and make the dynamic SQL construction straightforward or you can take the "1=1" out and add some logic in to process the start of the conditions in the WHERE clause being careful that there may be no conditions in the WHERE clause, in which case you don't need the WHERE, either... and all that detracts from readability of the code (and adds complexity as well as testing), IMO.
 

Fristie Blade

Ars Tribunus Militum
1,722
Subscriptor++
[url=http:/civis/viewtopic.php?p=29088331#p29088331:3stir2vp said:
wallinbl[/url]":3stir2vp]
[url=http:/civis/viewtopic.php?p=29088191#p29088191:3stir2vp said:
Fristie Blade[/url]":3stir2vp]
Granted, it will not add much time or overhead to evaluate the 1= 1, but nor does it take much time to avoid it being there in the first place.

Whenever I see that in production, I always wonder "The dev did not consider it important enough to take that useless clause out, so what else did they not deem important to look at. What else did they not optimize because it all just worked anyway. That is until it needs to work in production where we have millions of records and bla bla ... and where indexes make a huge difference just like setting the correct restrictions or how to join the data etc."

Prior to EntityFramework, we rolled our own ORM. 1 = 1 was prevalent mostly as a way to simplify the code and make it more readable, since the queries were going to be built based on the calling code and we'd otherwise have to track whether to prepend the current clause with AND or OR. The basic list interface was queryable from calling code, and therefore SQL was constructed on the fly to respond to the call. While we could have avoided 1 = 1, it would have just added more code and made it less readable.

We have some dynamic reporting tools available to users that likewise use 1 = 1 to simplify code, since the users can use the UI to build all sorts of random things, and the SQL is being constructed in response to input.

And, like Richard said, I do leave it in there in some places just because it improves readability, even within a static SELECT in a stored proc. The 1 = 1 goes on the line with WHERE, and the remainder of the lines are clearly started with AND or OR and visually line up well with each other. The brain can parse them much faster when there's a consistent layout.

I do feel where you come from and can sympathize with it in such dynamic reporting cases.
Although one thing I have a different opinion on: that you need to add more and less readable code to avoid the 1 = 1 situation while building dynamic restrictions on the fly server side, eg in a web app. I've also built stuff like that in the past. It's not that hard to keep an array of all your restriction clauses and their AND/OR operators and join it all together into one restriction string - even joining with CRLF for readability if you want it. When the restriction string is an empty string, it stays that way, else you prefix it with the "WHERE " part (or "WHERE " + CRLF for readability).
The nice thing is that in case no restrictions where requested from the caller then the restriction part stays completely empty and your resulting SQL statement does not have a restriction part in there at all, instead of a "WHERE 1=1".
This technique with arraying the restriction parts works in addition perfectly fine with using parameters for your restrictions. One array that builds the restriction parts like "field1 = ?" and another array that contains the actual values that will be passed as parameters.

So while the "WHERE 1=1" is no big deal in itself and has no real measurable negative impact (I think we all agree upon that part) there is no reason to generate it even in an automated dynamic restriction builder. Such a builder can have readable code and easily output humanly readable CRLF code if desired.

Of course, if you need to work with legacy systems that just started off that way, there is no need to go change them in order to be academically perfect. That's not what I wanted to claim.
 

wallinbl

Ars Legatus Legionis
14,319
Subscriptor
[url=http:/civis/viewtopic.php?p=29088533#p29088533:y3osyw3u said:
Fristie Blade[/url]":y3osyw3u]
This technique with arraying the restriction parts works in addition perfectly fine with using parameters for your restrictions. One array that builds the restriction parts like "field1 = ?" and another array that contains the actual values that will be passed as parameters.
Both the legacy ORM and the dynamic report builder produce substantially more complex WHERE clauses than a simple string.Join() would adequately produce. We have a data structure that manages the AND/OR/IN/NOT relationships and produces the resultant strings. Remember that this is essentially hierarchical, and each component doesn't know (and shouldn't know) its place in the overall hierarchy - it renders the string that pertains to it and what's down the tree from it only. A higher level in the tree will worry about its place in the overall clause.
 

Fristie Blade

Ars Tribunus Militum
1,722
Subscriptor++
[url=http:/civis/viewtopic.php?p=29088795#p29088795:2tdwqz0b said:
wallinbl[/url]":2tdwqz0b]
[url=http:/civis/viewtopic.php?p=29088533#p29088533:2tdwqz0b said:
Fristie Blade[/url]":2tdwqz0b]
This technique with arraying the restriction parts works in addition perfectly fine with using parameters for your restrictions. One array that builds the restriction parts like "field1 = ?" and another array that contains the actual values that will be passed as parameters.
Both the legacy ORM and the dynamic report builder produce substantially more complex WHERE clauses than a simple string.Join() would adequately produce. We have a data structure that manages the AND/OR/IN/NOT relationships and produces the resultant strings. Remember that this is essentially hierarchical, and each component doesn't know (and shouldn't know) its place in the overall hierarchy - it renders the string that pertains to it and what's down the tree from it only. A higher level in the tree will worry about its place in the overall clause.

The point of the simple example was to counter the statement that code would inherently become complex and unreadable if you had to track and check if the initial "WHERE 1=1" needed to be removed or not.

Now that you brought up restriction building as a hierarchical process, my follow-up question would be: do you start each nested level with a 1=1 block that combines with the other parts of that level? I guess not. And if it is not needed at sub levels, why would it be needed at the highest level?
 

Fristie Blade

Ars Tribunus Militum
1,722
Subscriptor++
[url=http:/civis/viewtopic.php?p=29103243#p29103243:32i4otbt said:
ShuggyCoUk[/url]":32i4otbt]
[url=http:/civis/viewtopic.php?p=29088199#p29088199:32i4otbt said:
Fristie Blade[/url]":32i4otbt]I just discovered that instead of a grammar nazi, I may have become a SQL nazi. The best kind of nazi or null ;)

FTFY :)

select max(lol) from rofl ;--)
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
[url=http:/civis/viewtopic.php?p=29088215#p29088215:1zyp89e2 said:
FoamingPipeSnake[/url]":1zyp89e2]
[url=http:/civis/viewtopic.php?p=29088193#p29088193:1zyp89e2 said:
wallinbl[/url]":1zyp89e2]
[url=http:/civis/viewtopic.php?p=29088179#p29088179:1zyp89e2 said:
FoamingPipeSnake[/url]":1zyp89e2]
[url=http:/civis/viewtopic.php?p=29087991#p29087991:1zyp89e2 said:
Richard Berg[/url]":1zyp89e2]What's wrong with 1=1 in production?

Are you serious?

Though it won't make a meaningful affect on performance, it just shows a lack of detail by the original query writer. I can't stand sloppy, and in fact was one of the reasons I quit my last job.
Some things are important to scrutinize. That one is not.

Agree. It still bugs though.

I have never seen that idiom, and it would drive me batshit insane if I came across it in any code I was maintaining. What purpose does it serve? If it's to enable/disable WHERE clauses, couldn't that be done a bit more gracefully by the query generation logic? As hacks go, that looks...stupid.
 
It does make adding optional WHERE clauses a bit more concise while having no performance impact on the query, for example:

Code:
query = "SELECT foo, bar, baz FROM tbl WHERE 1=1"
params = []

if (barCondition) {
    query += " AND bar = ?"
    params.push(bar)
}

if (bazCondition) {
    query+= " AND baz = ?"
    params.push(baz)
}

Without the 1=1 you'd have to make an additional check to see whether to add WHERE to the query. There's obviously more than one way to accomplish that task, but this way generally isn't harmful.

Edit: Response to all the SQL nazis above: "Premature optimization is the root of all evil"; an extra 1=1 statement isn't going the be the bottleneck that kills your app.
 
Status
Not open for further replies.