How do they know how many viewers there are? I mean sure they can track down the number of people with the channel but who says they will watch the show?
Nielsen is a company that does television ratings. A select sample of people across the country either keep a log of what they watch or have a special box on their cable to keep track of what they are watching. Each person doing this represents a certain percentage of the population, so they can derive stats from that. For example, here were the top shows for last week:
http://tv.yahoo.com/nielsen/.
From that, the higher the ratings are, the broader an audience is watching the show, meaning a commercial shown will reach more people. So, if Motorola wanted to advertise the new SLIVR, they'd want to do it on American Idol over ER. But because American Idol gets better ratings, they can charge more.
Of course with that example, you can start getting more detailed with target markets and demographics. More 18-24 year olds are more likely to watch American Idol over ER (and this is also measured by Nielsen ratings) so advertising a new "hip" cell phone might work better on American Idol over ER.
And in the case of OC, I'm sure they make a lot of money from syndication and DVD sales.
And if you want to look at regular soap operas during the day (the kind that stay-at-home moms would watch), their demographics are different and usually have a little more money to spend, so companies will pay more because they know they can charge more/make more on their product over a teen show.