Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Ranking position in a SQL index

by Anonymous Monk
on Oct 06, 2004 at 20:00 UTC ( [id://397152]=note: print w/replies, xml ) Need Help??


in reply to Ranking position in a SQL index

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

Replies are listed 'Best First'.
Re^2: Ranking position in a SQL index
by monktim (Friar) on Oct 06, 2004 at 20:14 UTC
    Oops, make that join
    JOIN Abc a2 ON a1.letter >= a2.letter
    otherwise 'a' gets lost. Sorry about that.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://397152]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-04-19 19:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found