Link to home
Start Free TrialLog in
Avatar of Russ Suter
Russ Suter

asked on

TOP(1) query for Oracle AND Microsoft SQL Server

I have two tables. One called EMAILQUEUE and another called EMAILQUEUE_STATUS. EMAILQUEUE contains information about emails sent or to be sent. EMAILQUEUE_STATUS contains a record of the status of each item in EMAILQUEUE. I need to get a list of all items in EMAILQUEUE whose most recent status from the EMAILQUEUE_STATUS table is "Ready to send". If I was using an Oracle database I could use something like this:
SELECT ... FROM EMAILQUEUE_STATUS WHERE STATUS = 'Ready' AND ROWNUM = 1 ORDER BY TIME_STAMP DESC

Open in new window

For Microsoft SQL Server I could use something similar but different due to differences in syntax:
SELECT TOP(1) ... WHERE STATUS = 'READY' ORDER BY TIME_STAMP DESC

Open in new window

Here's the catch. I need a single query statement that will work with the same syntax for both Oracle and Microsoft SQL Server. I'm thinking some kind of group by or partition might be the way to go but I'm not quite figuring it out. Anyone have any ideas?

Oh and by the way, this needs to be compatible with Oracle 11g or later and Microsoft SQL Server 2012 or later. Unfortunately, Oracle 11g doesn't support CROSS APPLY so that option is out. :(
ASKER CERTIFIED SOLUTION
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>I need a single query statement that will work with the same syntax for both Oracle and Microsoft SQL Server.
Why?  This is not a realistic expectation that for every situation there will be SQL code that works in both databases.
I think this will do it:

SELECT ...
FROM EMAILQUEUE_STATUS
WHERE STATUS = 'Ready'
ORDER BY TIME_STAMP DESC
/* OFFSET ... [optional, of course] */
FETCH NEXT 1 ROWS ONLY

I guess sometimes ANSI standards do actually help.
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

>>I think this will do it:  ... FETCH NEXT 1 ROWS ONLY

I think that syntax is a new 12c feature and not available in 11g.
I'm certain you're right.  I'm a SQL DBA only now.  I knew SQL supported it, so I Googled it for Oracle, but I have no idea what version it started in.  [The last time I was an Oracle DBA was for Oracle8.]
Avatar of Russ Suter

ASKER

@slightwv

Thanks. That was pretty much it. I knew this already but was hitting a mental block for some reason. Thanks for jogging my memory.

@Jim Horn

I don't know what you're getting at here. I have no such expectation. I just knew that in this particular situation there was an answer. I just couldn't remember what the answer was.