Database Programming Rule #1

Ovid on 2004-06-16T18:31:53

In production code, if your SELECT statement returns more than one record and it doesn't have an ORDER BY clause, it's probably a bug.

I'm still amazed at the number of professional programmers who don't seem to realize this.


Huh?

djberg96 on 2004-06-16T19:04:26

I don't follow the logic of requiring an ORDER BY, especially if I'm just slapping some data into a spreadsheet which the PHB's can sort on their own with Excel.

And what about the performance hit? I find that if I really need ordered data it's often better to just let Perl handle it on the client side.

What am I missing?

Re:Huh?

vek on 2004-06-16T19:39:12

...if I'm just slapping some data into a spreadsheet which the PHB's can sort on their own with Excel.

For one particular project I was specifically asked *not* to sort the data prior to dumping it into Excel for that very reason.

PHBs love to sort their spreadsheets :-)

Not quite

VSarkiss on 2004-06-16T19:20:05

I think what you really want to say is "if your program implicitly depends on the order of rows without explicitly using an ORDER BY clause, it's definitely a bug."

I rarely use ORDER BY -- except when I need it. The trick is to know the difference.

Opposite View

phillup on 2004-06-16T19:22:55

I have almost the opposite view.

When I get involved, it is because the problem requires data munging that the db schema doesn't make easy.

The data gets aggregated, munched, crunched and gyrated thru so many hoops... that it makes no sense to sort until the data is being output.

No need to tax the db for that, not when the delivery order (from the db) is not significant.

On the other hand... yeah, simple grab and display type of things... should have some order imposed upon them.

And, my final results always do. I just may not have the db do it...

Hmmm

vek on 2004-06-16T19:33:05

Not sure I agree with you. It *might* be a bug depending on what you're doing or expecting. Then again, it might not.

Today I added some code to retrieve email addresses from a table. The order in which the rows are returned to me is irrelevant. I'm not using the data to display on a report or on a webpage, I'm just sending out emails.

So, does my code have a bug? Maybe, but I'm pretty sure it's got nothing to do with the fact that I didn't use an ORDER BY :-)