|
-
Exactly as Tamilselvan said.
Do not implement it as a function as gandolf989 suggested - functions add unnecessary overhead.
Additionally, we need to know if that column is indexed, and whether or not this simplified example is anywhere close to what your real-world SQL will be. This sql is trying to say 'get me the latest entry in the entire table.
However, unless there is a unique index on that date column, it is possible to return more than one row from this SELECT. Is that what you want?
If the column were indexed, a simple MIN/MAX lookup by the optimizer would get the date you want followed by a range scan of the index to get the actual row. This should all be very fast. However, if in the real world you are applying multiple predicates to your actual statement, you must consider more. Here's another version of the statement:
Code:
SELECT
*
FROM
TEST
WHERE
SALESPERSON_ID = :SALESPERSON_ID AND
TRADE_DATE = (
SELECT
MAX(TRADE_DATE)
FROM
TEST
WHERE
SALESPERSON_ID = :SALESPERSON_ID AND
TRADE_DATE < TRUNC(SYSDATE)
)
In this case, you will want to make sure there is an index on SALESPERSON_ID, TRADE_DATE.
If you do not have the appropriate index for this query (or don't want to make one), another solution is:
Code:
SELECT
*
FROM
(
SELECT
T.* ,
ROW_NUMBER()
OVER(
ORDER BY TRADE_DATE DESC
)
AS RN
FROM
TEST T
WHERE
SALESPERSON_ID = :SALESPERSON_ID AND
TRADE_DATE < TRUNC(SYSDATE)
)
WHERE
RN = 2
With this solution, the table is only accessed once instead of twice. However, only the SALESPERSON_ID index will be used, if it exists. A SALESPERSON_ID, TRADE_DATE index, if it existed, would not be used fully (meaning the second column would be irrelevant). That is why, if a SALESPERSON_ID, TRADE_DATE index exists, use the original sub-select solution. If not, this solution may prove faster.
HTH,
- Chris
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|