<body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener('load', function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <div id="navbar-iframe-container"></div> <script type="text/javascript" src="https://apis.google.com/js/platform.js"></script> <script type="text/javascript"> gapi.load("gapi.iframes:gapi.iframes.style.bubble", function() { if (gapi.iframes && gapi.iframes.getContext) { gapi.iframes.getContext().openChild({ url: 'https://www.blogger.com/navbar/1074803565153692547?origin\x3dhttp://innolearning.blogspot.com', where: document.getElementById("navbar-iframe-container"), id: "navbar-iframe" }); } }); </script>

InnoLearning

SQL SELECT TOP N (most expensive, high salary)
Sunday, October 28, 2007

SQL SELECT TOP N equivalent in ORACLE and MySQL (The most common database/Sql Interview Question)
Something I needed today... I wish this was standarized, but it is not, so here are some examples:

SQL Server:

SELECT TOP 10 product, descr, email
FROM products

ORACLE:

SELECT product, descr, email
FROM products
WHERE ROWNUM <= 10


MySQL:

SELECT product, descr, email
FROM products
LIMIT 10



Now i only want to show the top 5 records how do i do this?

Answer:
Here is the SQL to display the top-n items:

SELECT ENAME, SAL
FROM (SELECT ENAME, SAL FROM EMP ORDER BY SAL DESC)
WHERE ROWNUM < 4;

If you are using Oracle 9i you can use the RANK function also.

select *
from (select empno,sal,rank() over (order by sal desc ) rnk from emp)
where rnk <= 5;

thats all! Njoy...

Labels: , , , ,

posted by MIGHTYMAK @ 10:03 AM,




0 Comments:

Post a Comment

<< Home