Question

MySQL - 15 million rows or 300,000 tables : Which is a better choice?

Asked by: 1_21gigawatts

I am working with a mysql database of stock market transactions. I currently have a table for each day's ticks. There are approximately 14 million ticls per day, hence each table has about 14 million rows.

I have indexes on SerialNumber (bigint unique) and Symbol (varchar 20).

Executing a simple query like
  Select datetime FROM ticks WHERE symbol='ibm';
returns about 6000 rows, but can take up to 20 seconds to execute. Running the same query again executes almost instantly, suggesting that the results are buffered.

What can I do to make this faster?

  I have considered separating the more active symbols into a separate database, or even using a table per symbol. This would almost certainly make the queries faster, but at the expense of having a huge number of tables - there are, including futures and options, some 300,000 symbols. Most of them have little or no data, but all of them have to be accomodated.

I suppose I could have a table with pointers to which table contains the actual data, only having entries for the more active issues which would be stored in separate tables. If a symbol doesn't have an entry in this index, then its data is stored in the main table.

I guess a question that needs to be answered is how many tables is too many tables?

This, by the way is running on Windows XP with a Raid 0 array.  Core 2 Duo Processor, 2G ram, and the computer is not doing much other than running this database and collecting data from our service.

These are, by the way, MyISAM tables.

It just seems to me that this should run faster.

Any suggestions? And, while we're at it, would this work better in MS SQL server?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-09-11 at 17:02:52ID22822148
Tags

mysql

,

rows

Topic

MySQL Server

Participating Experts
2
Points
500
Comments
25

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. MySQL S-L-O-W when handling my 19 million row table
    Dear group, I am using MySQL 4.0.1-alpha on a i686 machine with RedHat 7.2. I'm afraid I don't have the exact machine specs available to me, but it's fast -- trust me! (SELECT BENCHMARK(1000000,1+1) = 0.1 seconds) I've got a large 19 million items table, with 9 indices, and...
  2. Building Averages on 3.4 million rows
    Kind of an odd one here. i have an open source php app i have been using in my work enviroment (hacking away at it to fit the needs of our company) and everything works pretty well. Basically, its a logging/graph building software that throws all of the mail transactions on...
  3. How to handle Millions of files? (Bogs windows file system)
    I'm developing a program that will need to keep a record of millions of images, created at a rate of about 5 per second. Right now, I'm simply writing them, separately (each image in its own separate file) into a folder. However, as soon as the folder gets 5, 10, 20 thousand...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Raynard7Posted on 2007-09-11 at 17:14:29ID: 19873069

Hi,

One of the most important thins is what you are doing with your table as far as queries as well as how you are running your hardware setup.

There is much you can do to optimize a database using your configuration settings to get the most out of it.

When you mention that you have indexes on the symbol then is this a composite index or just that field?

Sometimes you can get better improvement by simply creating a lookup table for each symbol then using their numeric index to do searches, as the indexes work better when they have numeric data to search on.

Also, how regularly are you optimizing your tables and rebuilding your indexes? if you are constantly adding new rows then you can end up with problems as far as having data that is not indexed added to the end of the file and as such this then needs to be trolled through one row at a time.

there is never too many tables but you need to consider what sorts of queries you will be running and how you are going to take these into account, also the method that you are getting your data is important to see if it is feasible to be writing data and splitting it across many tables.

Are all your fields in the table fixed width? if so then you should see much better performance of your indexes.

you also need to consider are you going to be doing date queries? or is this simply for the stock index, you have not mentioned if the datetime field is actually indexed, if not then this would mean that ever single ibm record for example would need to be checked to find the date.

Finally, depending on your space requiremnts I would say that once mysql 5.1 exits beta then its partitioning would be perfect for your situation.  you could have the same data in two tables, one could have a partition for each date and one could have a partition for each stock; the partitions would then in effect be separate tables but you could query the table like it was just one.  at the moment this is probably the one advantage that MSSQL has over mysql; as you could then receive your data, put the current day's data in one location, then write and arrange your partitions and indexes of a night; meaning everything will be fully optimized for you

 

by: hulaguttenPosted on 2007-09-11 at 17:33:31ID: 19873120

I think your problem is lack of normalization. The query should be like the following:'
Select datetime FROM ticks WHERE symbol=999;

You need to create a symbol table like the following:
create table symbol (id int not null auto_increment, symbol varchar(100), primary key(id));
insert into symbol values (null, 'ibm');

This should make your select statement run dramatically faster, and it should also reduce the space of your database because your database would not have to save the string 'ibm' for each row.

 

by: 1_21gigawattsPosted on 2007-09-11 at 17:36:21ID: 19873136

Here is the structure of a typical day's table:

CREATE TABLE `ticks_20070911` (
  `SerialNumber` bigint(20) NOT NULL auto_increment,
  `Symbol` varchar(20) NOT NULL default '',
  `DateTime` datetime default NULL,
  `Price` int(11) default NULL,
  `PriceType` int(11) default NULL,
  `Size` int(11) default NULL,
  PRIMARY KEY  (`SerialNumber`,`Symbol`),
  UNIQUE KEY `Serial Number` (`SerialNumber`),
  KEY `Symbol` (`Symbol`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

There is a table for each day, and all the ticks for the day are put in sequentially. I receive the data over the internet and (through the data vendor's API) extract the ticks and insert them into the table. I NEVER go back and edit a tick.

So, once a day is passed, there is no data added to that day's table. Are you syuggesting that I should reindex the table after the day is complete?

I do not currently do date queries, as each date is in a separate table. I also do not do time queries, as the application program only requests whole days. I do serialnumber queries on the real-time data, to only get the newest ticks. This doesn't appear to be a problem.

If I'm understanding you correctly, the lookup table would have pointers into the data table that contain the serial number of each tick for a given symbol. Would that really be any better than having a separate table for each symbol?

There's never too many tables must have some practcal limit, no? Each table has three files, there are over 300,000 symbols, so we're talking a million files or so. Somehow that seems excessive from the disk management standpoint. Making a backup could take forever, I think.

Thanks much.

 

by: 1_21gigawattsPosted on 2007-09-11 at 17:44:25ID: 19873161

hulagutten -

Do I understand this correctly that I would then be referencing the ticks by a newly created symbol number, and that the requisite two queries (one to obtain the symbol number from the symbol name table and the other to obtain the actual data) would be faster than the original query?

That's certainly an interesting approach, and probably not too hard to implement.

In writing the data, however, there would be at least two accesses per tick. One to get the symbol number, and one to write the tick data. There would have to be a third access to write to the symbol name table if the symbol didn't previously exist (there are some symbols that trade very infrequently).

I wonder how nasty this might be in processing incoming data.

 

by: hulaguttenPosted on 2007-09-11 at 17:53:20ID: 19873190

Yes you understand it correctly. I do not know if it helps, but the following is a Java example (from our code) of the code needed to get the ID of a tick (if it does not already exist in the table it needs to be inserted). Notice that it uses something called prepared statements to speed up the process.


      public int registerIna_V1(String ina) throws Exception {
            if(ina.equals("")) return -1;
            try {
                  int inaId = 0;
                  PreparedStatement ps = db.prepStat()[registerIna_V1_SELECT];
                  ResultSet inaRS = ps.executeQuery();
                  if(inaRS.next())
                        inaId = inaRS.getInt("id");
                  else {
                        ps = db.prepStat()[registerIna_V1_INSERT];
                        ps.setString(1, ina);
                        ps.executeUpdate();
                        inaId = (int) db.lastInsertId(ps);
                  }
                  inaRS.close();
                  return inaId;
            } catch (SQLException e) {
                  e.printStackTrace(log.err);
                  throw new Exception("Ina|Could not register Ina! " + e.getMessage());
            }

      }

You would probably loose some performance on inserts, but the database would become a lot easier to manage.

 

by: hulaguttenPosted on 2007-09-11 at 17:55:23ID: 19873194

You could research "star schema", which is what your database structure should be.

 

by: hulaguttenPosted on 2007-09-11 at 18:00:22ID: 19873210

 

by: 1_21gigawattsPosted on 2007-09-11 at 18:09:01ID: 19873234

hulagutten -

Thanks for all that, it makes a lot of sense. However, in your suggestion:

   create table symbol (id int not null auto_increment, symbol varchar(100), primary key(id));
   insert into symbol values (null, 'ibm');

Wouldn't I also want to have an index on the symbol field? That's where my queries will be aimed.

 

by: hulaguttenPosted on 2007-09-11 at 18:16:16ID: 19873256

Yes you would need an index on the symbol column in the symbol table. The symbol table would however, "just" contain 300.000 rows, not millions like in the ticks_20070911 table. You also need to put a key on the symbol column in the ticks_20070911 table, of course...

 

by: hulaguttenPosted on 2007-09-11 at 18:17:16ID: 19873260

Just out of curiosity, how much historical data do you have? I bought such data a while ago from all tickers on the nasdaq index, they had data back to 2003.

 

by: 1_21gigawattsPosted on 2007-09-11 at 18:33:41ID: 19873330

but that symbol column is now an integer, not a string. Correct?

I have tick data going back to 11/11/2005. This doesn't cover all of the exchanges. I have very full data going back about a year, and more full data going back just a couple of months. I don't have bid/ask data for most of it, as that would exceed the capacity of my T1.

I'm looking at purchasing some daily data going back about 10 years or so.

 

by: hulaguttenPosted on 2007-09-11 at 18:40:37ID: 19873360

Please write me at daa.alps ( a t ) gmail ( d o t ) com

 

by: hulaguttenPosted on 2007-09-11 at 18:42:20ID: 19873369

Yes the symbol column is now an integer, which is a lot faster to run queries against.

 

by: hulaguttenPosted on 2007-09-11 at 18:49:40ID: 19873403

Putting your data in the new schema should reduce the size significantly. You could also use MySQL compression or maybe the Archive Storage Engine.

 

by: Raynard7Posted on 2007-09-11 at 19:03:50ID: 19873450

Hi,

What exactly are you using this data for?

I would suggest that if you are not using it for transaction based applications and are using it for trending and analysis then I would suggest that you do not use a traditional transaction based OLTP approach, I would suggest for reporting and analysis then you use an OLAP or Cube based databases instead.  This will dramatically increase the speed of your queries and make them easier to write once it is setup.

 

by: hulaguttenPosted on 2007-09-11 at 19:08:23ID: 19873457

Raynard7- Can MySQL do OLAP? How is it done?

 

by: Raynard7Posted on 2007-09-11 at 19:26:33ID: 19873503

Mysql can not do olap however you need the correct tools for the job.  Whilst I think MySQL is excellent for transactional systems it, like most transactional databases  is not primarily designed for the sorts of data mining, trending or large scale analysis over huge datasets.  If however the aim for this system was to just store daily information for a long period of time and only a few days worth of data was required then it would be what I would recommend.

If large scale analysis is what is being done then I would recommend that OLAP be used, which is designed with this goal as its primary purpose.  Mondrian (now part of pentaho) is a good open source olap tool that can be used to pull its data from mysql http://mondrian.pentaho.org/ and there are other open source olap databases on the market.

 

by: 1_21gigawattsPosted on 2007-09-13 at 17:49:55ID: 19888259

OK, so I coded the whole thing up so that the symbols file looks like:

CREATE TABLE `symbols` (
  `SymbolNumber` int(11) NOT NULL auto_increment,
  `Symbol` varchar(30) NOT NULL,
  PRIMARY KEY  (`SymbolNumber`),
  KEY `Symbol` (`Symbol`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

and the tick file looks like:

CREATE TABLE `ticks_20070912` (
  `SerialNumber` bigint(20) NOT NULL auto_increment,
  `Symbol` int(11) NOT NULL,
  `DateTime` datetime default NULL,
  `Price` int(11) default NULL,
  `PriceType` int(11) default NULL,
  `Size` int(11) default NULL,
  PRIMARY KEY  (`SerialNumber`,`Symbol`),
  UNIQUE KEY `Serial Number` (`SerialNumber`),
  KEY `Symbol` (`Symbol`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

There is a very, very small improvement in speed with the new format. selecting all of the AAPL ticks took 12.5 seconds the old way (...where symbol='AAPL'), and 12.3 seconds the new way (...where symbol=7287),  +/- my finger delay on the stopwatch.

And yes, I am only counting the time that it takes for MySQL to *start* returning data, not the actual time to transmit the thousands of rows.

This is a very simple query - SELECT * FROM ticks_20070912 WHERE symbol=7287; So I don't see OLAP helping things at all.

Also the file sizes did not change much, the index file actually got larger

Old index file - 441,556K
New index file 550,014K

Old data file - 474,437K
New data file 398,815K

I know I could compress the data files, and that would help some, but I need this to be MUCH faster.

So, now what am I going to do to speed this up?




 

by: hulaguttenPosted on 2007-09-14 at 02:50:10ID: 19890041

The reason could be that you are selecting all rows. Try running queries like the following and compare the speed.

SELECT count(*) FROM ticks_20070912 WHERE symbol=7287;
or maybe
SELECT symbol, count(*) from ticks_20070912 group by symbol;

This should be significantly faster. Please send me an email as well.

 

by: 1_21gigawattsPosted on 2007-09-14 at 16:22:02ID: 19895740

OK, I did the tests you requested, and there really wasn't much difference. So, I got to thinking about compressing with myisampack. I had tried this a long time ago with pretty unimpressive results, but I figured I give it a shot after changing the varchar symbol column into an int.

Whoa! A query that ran for 12.5 seconds on the original file now takes 2.1 seconds! This is seriously looking good. I am now processing more days of raw data so I can do more in-depth testing. It takes about an hour to process each day's worth of ticks into the database, so I won't be able to try any of this till tomorrow. But I'm feeling optimistic.

BTW, Is there an easy way to time these things (easier, that is, than my stopwatch)?

 

by: hulaguttenPosted on 2007-09-14 at 16:48:57ID: 19895841

That is really good news! Congratulations!

If you use the standard mysql client. /mysql/bin/mysql.exe it says how long each query took after it was executed.

 

by: hulaguttenPosted on 2007-09-14 at 17:29:30ID: 19895975

I tried to get the same results compressing a table with 5 million rows containing only integer values, and it actually reduced the performance when I tried running similar select queries to what you did. Sometimes the performance was half...

 

by: 1_21gigawattsPosted on 2007-09-14 at 17:53:14ID: 19896040

Well, the proof will be in the pudding, I guess. I imagine the performance (and the effectiveness of these tuning measures) is very dependent on not only the specifics of the data and the queries, but also on the hardware, operating system and other processes.

I won't know till tomorrow (at least) whether this worked for more than a couple of symbols on an isolated day. I won't know till sometime next week (well, Monday, though I'm supposed to be on vacation until Friday( whether it works while there is incoming data being processed concurrently.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...