<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.g?targetBlogID\x3d1074803565153692547\x26blogName\x3dInnoLearning\x26publishMode\x3dPUBLISH_MODE_BLOGSPOT\x26navbarType\x3dBLUE\x26layoutType\x3dCLASSIC\x26searchRoot\x3dhttps://innolearning.blogspot.com/search\x26blogLocale\x3den_US\x26v\x3d2\x26homepageUrl\x3dhttp://innolearning.blogspot.com/\x26vt\x3d2174717628392424844', where: document.getElementById("navbar-iframe-container"), id: "navbar-iframe", messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER, messageHandlers: { 'blogger-ping': function() {} } }); } }); </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