Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
The most efficient way is dependent on the DBMS, the hardware, the data, the query optimizer, if the code is run as a stored procedure or ad-hoc query, proper indexes, good dB coding, etc. A lot also depends on how often this ranking is needed. Can the query be run on an alternate dB that is used for reporting and isn't constantly being updated? You may want to lock a table and perform the query on a reporting dB and then unlock the table and let the transactions catch up through replication. Is the done once a day, week, month, hour, etc. SQL performance is both a science and an art.

Here is a way to do it. SQL is a lot like Perl in the TMTOWTDI. The code joins the table on itself which is usually not a very good performer when you have millions of rows. The nice thing about this example is that it's SQL ANSI 92 standard so it should run on all compliant dBs and it gives you the result you want.

CREATE TABLE Abc(letter char(1), position int) INSERT INTO Abc (letter, position) VALUES ('a', 1) INSERT INTO Abc (letter, position) VALUES ('b', 2) INSERT INTO Abc (letter, position) VALUES ('d', 4) INSERT INTO Abc (letter, position) VALUES ('j', 10) INSERT INTO Abc (letter, position) VALUES ('z', 26) SELECT COUNT(*) AS rank, a1.letter FROM Abc a1 JOIN Abc a2 ON a1.letter > a2.letter GROUP BY a1.letter

In reply to Re: Ranking position in a SQL index by Anonymous Monk
in thread Ranking position in a SQL index by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2024-04-26 07:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found