What is an index in SQL?

An index is used to speed up searching in the database. MySQL have some good documentation on the subject (which is relevant for other SQL servers as well): http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html An index can be used to efficiently find all rows matching some column in your query and then walk through only that subset of the table … Read more

SQL join: selecting the last records in a one-to-many relationship

This is an example of the greatest-n-per-group problem that has appeared regularly on StackOverflow. Here’s how I usually recommend solving it: SELECT c.*, p1.* FROM customer c JOIN purchase p1 ON (c.id = p1.customer_id) LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND (p1.date < p2.date OR (p1.date = p2.date AND p1.id < p2.id))) … Read more

Does PostgreSQL support “accent insensitive” collations?

Use the unaccent module for that – which is completely different from what you are linking to. unaccent is a text search dictionary that removes accents (diacritic signs) from lexemes. Install once per database with: CREATE EXTENSION unaccent; If you get an error like: ERROR: could not open extension control file “/usr/share/postgresql/<version>/extension/unaccent.control”: No such file … Read more

C++ sorting and keeping track of indexes

Using C++ 11 lambdas: #include <iostream> #include <vector> #include <numeric> // std::iota #include <algorithm> // std::sort, std::stable_sort using namespace std; template <typename T> vector<size_t> sort_indexes(const vector<T> &v) { // initialize original index locations vector<size_t> idx(v.size()); iota(idx.begin(), idx.end(), 0); // sort indexes based on comparing values in v // using std::stable_sort instead of std::sort // to … Read more

With MySQL, how can I generate a column containing the record index in a table?

You may want to try the following: SELECT l.position, l.username, l.score, @curRow := @curRow + 1 AS row_number FROM league_girl l JOIN (SELECT @curRow := 0) r; The JOIN (SELECT @curRow := 0) part allows the variable initialization without requiring a separate SET command. Test case: CREATE TABLE league_girl (position int, username varchar(10), score int); … Read more