home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.databases.ingres
- Path: sparky!uunet!ukma!asuvax!ncar!uchinews!gsbacd.uchicago.edu!cs_mj
- From: cs_mj@gsbacd.uchicago.edu (Mark Jaeger)
- Subject: Re: Is it possible to get the first "n" records of a table or view ?
- Message-ID: <1992Nov18.135025.1@gsbacd.uchicago.edu>
- Lines: 65
- Sender: news@uchinews.uchicago.edu (News System)
- Organization:
- References: <C4A55D13881F2037B8@ichcmns.cmns.mnegri.it>
- Date: Wed, 18 Nov 1992 19:50:25 GMT
-
- In article <C4A55D13881F2037B8@ichcmns.cmns.mnegri.it>,
- Marco Olivieri <OLIVIERI@ICHCMNS.CMNS.MNEGRI.IT> writes:
-
- > Is it possible to get the first "n" records of a table or view ?
- >
- > I have a table with about 230000 records, through query, I want
- > to read only the first 50 records, ignoring the other ones.
- > Does any SQL function exist ? (I don't thinks, but I'm not sure)
-
- I've attached a similar question and my response. You can do it
- directly in SQL if your table has the necessary design; otherwise, you
- can do it in a cursor or select loop in the host language (4GL, C,
- FORTRAN, etc.).
-
- --Mark Jaeger internet: cs_mj@gsbvax.uchicago.edu
- Graduate School of Business yellnet: (312) 702-0328
- University of Chicago faxnet: (312) 702-0233
- Disclaimer: My opinions are my own and not those of my employer.
- Ich bin ein Virus. Mach' mit und kopiere mich in Deine .signature.
-
- ================================================================================
- In article <1992Aug17.142452.24812@itm.uucp>, danny@itm.uucp (Danny Cox) writes:
- > We get many requests for the 'top N' rows from
- > a table. How does one accomplish this in SQL? Sorting is no problem,
- > but how does one request the first N rows? Obviously one could do an
- > 'endloop' to stop once N is reached in 4gl/ESQLC, but is there a better way?
-
- You can do this directly in a single SQL statement, if your table has a
- column of unique values that defines the order. I've attached a simple
- example. I won't say it's better, and in fact using a select or cursor
- loop will probably give better performance in general.
-
- ================================================================================
- select * from t order by id ;
- +------+
- |id |
- +------+
- | 10|
- | 20|
- | 30|
- | 40|
- | 50|
- | 60|
- | 70|
- | 80|
- +------+
-
- select * from t a where 3 >= ( select count(*) from t b where b.id <= a.id ) ;
- +------+
- |id |
- +------+
- | 10|
- | 20|
- | 30|
- +------+
-
- select * from t a where 3 >= ( select count(*) from t b where b.id >= a.id ) ;
- +------+
- |id |
- +------+
- | 60|
- | 70|
- | 80|
- +------+
-
-