SQL Practice: S&P 500 Companies and Their Filings
Practice SELECT, GROUP BY, HAVING, and UPDATE on real company data, and learn to check whether a number is believable before using it.
Last updated:
How far can a query take us, and what must we check before trusting a number?
A company’s founding year, industry, headquarters, and annual revenue are public facts.
How far can SQL take us when we compare 500 large American companies, and what must we check before we trust a number?
In this practice set you will write queries, and you will also test whether the results make sense.
This practice continues the DB Browser SQL guide, part 1 and part 2.
Try each question before you open the answer.
This set adds what the practice generator does not: financial data of a different kind, with ratios and missing values; questions about whether a number is believable; and a change to the data with UPDATE, checked before it runs.
It needs a file you download yourself, so it is not part of the practice generator.
Get the data
The data come from a public Kaggle dataset, S&P 500 Database, published by the Kaggle user eliasdimatis.
According to its provenance note (the author’s description of where the data came from), the company list was taken from Wikipedia, and the financial information from Yahoo Finance, collected by web scraping (reading data automatically from web pages) and with yfinance, a Python library for Yahoo Finance data.
The dataset does not state a license (Kaggle lists it as “Unknown”), so our course site does not host a copy of it.
Download it yourself:
- Sign in to Kaggle (a free account is enough) and open the dataset page.
- Select Download and save the ZIP file. Open the ZIP and extract
s_p.sqlite. - In DB Browser, choose Open Database and select
s_p.sqlite.
Work on a copy of the file. Queries that change data, such as UPDATE, change the open database only after you select Write Changes, and Revert Changes cancels them.
The two tables
The column names of the tables contain financial terms, so we explain them, in plain language, before presenting the tables themselves:
- A ticker (
Stock_Ticker) is the short code under which a company’s stock is traded, for exampleAAPLfor Apple. - A filing is an annual financial report that a company submits to the US Securities and Exchange Commission (SEC), the regulator of the stock market. The annual report form is called Form 10-K, and the
CIKcolumn holds the company’s identification number at the SEC. - Sales revenue (
Sales_Revenue) is the money that came into the company from selling its products and services during the year, before expenses. - Total assets (
Total_Assets) is everything the company owns, total liabilities (Total_Liabilities) is everything it owes, and shareholder equity (Shareholder_Equity) is what remains for the owners: assets minus liabilities. - Net income (
Net_Income) is the profit left after all expenses and taxes. - Debt-to-equity ratio (
Debt_to_Equity) is a ratio that compares what the company owes with the owners’ share.
With the terms in hand, back to the tables. The database has two tables:
| Table | One row describes | Main columns |
|---|---|---|
SP500 | One company | Stock_Ticker_Symbol, Company_Name, Industry, Sub_Industry, Headquarters_Location, Date_Added, CIK, Founded |
Filings | One annual financial filing of one company | Stock_Ticker, Filed_Date, Sales_Revenue, Total_Assets, Total_Liabilities, Shareholder_Equity, Net_Income, Debt_to_Equity, and more ratios |
The ticker column has a different name in each table: SP500.Stock_Ticker_Symbol matches Filings.Stock_Ticker.SP500 has 500 rows, one for each ticker; they belong to 497 companies, because Alphabet, News Corp and Fox each trade under two tickers (two classes of shares).Filings has 2,063 rows for 497 of the tickers, from January 2020 to November 2024, so most companies have four or five annual filings.
Money amounts are in US dollars, written in full (for example, 394328000000).
A missing value is stored as NULL.
The columns of SP500
| Column | Type | Meaning |
|---|---|---|
Stock_Ticker_Symbol | TEXT | The company’s ticker, unique; the key that Filings.Stock_Ticker points to |
Company_Name | TEXT | The company’s name |
Industry | TEXT | The broad industry, for example Health Care or Financials (11 industries) |
Sub_Industry | TEXT | The narrower line of business inside the industry |
Headquarters_Location | TEXT | City and state or country of the headquarters, written as City, State |
Date_Added | DATE | The date the company joined the S&P 500 index, stored as text such as 1957-03-04 |
CIK | TEXT | The company’s identification number at the SEC, a text with leading zeros |
Founded | INTEGER | The year the company was founded |
The columns of Filings
Money amounts are in US dollars, written in full. The columns that start with Average_ are the average of the value at the end of this year and at the end of the previous year, taken from the previous filing in the file.
The ratios below were checked against the other columns of the same row:
each one equals the formula written next to it.
| Column | Type | Meaning |
|---|---|---|
Stock_Ticker | TEXT | The company’s ticker; matches SP500.Stock_Ticker_Symbol |
Filed_Date | DATE | The end date of the period that the annual report covers, stored as text such as 2024-10-31; it is not the day on which the report was submitted (the report of Walmart, for example, is dated 31 January, the end of its fiscal year) |
Current_Assets | REAL | Assets that turn into cash within a year: cash, customers’ debts and inventory |
Total_Assets | REAL | Everything the company owns |
Current_Liabilities | REAL | Debts that fall due within a year |
Total_Liabilities | REAL | Everything the company owes |
Shareholder_Equity | REAL | What remains for the owners: Total_Assets minus Total_Liabilities |
Sales_Revenue | REAL | Money received from selling products and services during the year, before expenses |
Net_Income | REAL | Profit after expenses and taxes; missing in most rows and not reliable in this file (see Check that a number is believable) |
Cost_of_Goods_Sold | REAL | The direct cost of producing what was sold |
Accounts_Receivable | REAL | Money that customers still owe the company |
Inventory | REAL | Goods the company holds for sale |
Accounts_Payable | REAL | Money the company still owes its suppliers |
Average_Total_Assets, Average_Total_Liabilities, Average_Shareholder_Equity | REAL | The yearly average of Total_Assets, Total_Liabilities and Shareholder_Equity |
Average_Accounts_Receivable, Average_Inventory, Average_Accounts_Payable | REAL | The yearly average of Accounts_Receivable, Inventory and Accounts_Payable |
Return_on_Assets | REAL | Profit per dollar of assets: Net_Income / Average_Total_Assets |
Profit_Margin | REAL | Profit per dollar of sales: Net_Income / Sales_Revenue |
Asset_Turnover | REAL | Sales per dollar of assets: Sales_Revenue / Average_Total_Assets |
Return_on_Equity | REAL | Profit per dollar of the owners’ share: Net_Income / Average_Shareholder_Equity |
Current_Ratio | REAL | Short-term assets against short-term debts: Current_Assets / Current_Liabilities |
Debt_to_Equity | REAL | All liabilities against the owners’ share: Total_Liabilities / Shareholder_Equity |
Receivables_Turnover | REAL | How many times a year customers’ debts are collected: Sales_Revenue / Average_Accounts_Receivable |
Average_Collection_Period | REAL | Days it takes to collect a customer’s debt: 365 / Receivables_Turnover |
Inventory_Turnover | REAL | How many times a year the inventory is sold: Cost_of_Goods_Sold / Average_Inventory |
Average_Days_Inventory_Held | REAL | Days the inventory stays on the shelf: 365 / Inventory_Turnover |
Payables_Turnover | REAL | How many times a year suppliers are paid: Cost_of_Goods_Sold / Average_Accounts_Payable |
Average_Days_Payables | REAL | Days it takes to pay suppliers: 365 / Payables_Turnover |
Days_in_Financing | REAL | Days the company funds its operation before cash comes in: Average_Collection_Period + Average_Days_Inventory_Held - Average_Days_Payables |
The SQLite type describes how a value is stored. Filed_Date and Date_Added are declared DATE, but SQLite stores them as text, so they sort and compare as text; a missing value is stored as NULL.
Practice
Write each query in the box under the question and run it before opening the answer.
Every answer shows a possible query, its result, and its meaning.
Several have a plausible mistake.
1. Which companies whose names start with A were founded in 1995? How many are there?
Show a possible answer
SELECT Company_Name
FROM SP500
WHERE Founded = 1995
AND Company_Name LIKE 'A%';
The result has two companies: American Tower and Arch Capital Group.
To count them, replace the selected column with COUNT(*), which returns 2.
A plausible mistake: no wildcard
The reasoning: LIKE 'A' looks like “starts with A”. But without %, the pattern matches only a name that is exactly A, so the query returns no rows.
The % stands for any number of characters after the A.
SELECT Company_Name
FROM SP500
WHERE Founded = 1995
AND Company_Name LIKE 'A';
2. Find the ten filings with the highest Debt_to_Equity. Then check whether the top value is believable.
Show a possible answer
SELECT Stock_Ticker, Filed_Date, Debt_to_Equity
FROM Filings
ORDER BY Debt_to_Equity DESC
LIMIT 10;
The top row is COR (Cencora) in the filing of 2022-09-30, with a ratio of about 792.6.
Next are NCLH (about 269.6) and MTD (about 139.9). The same company can appear more than once, because each row is a filing, not a company.
To understand 792.6, look at the equity:
SELECT Filed_Date, Total_Liabilities, Shareholder_Equity, Debt_to_Equity
FROM Filings
WHERE Stock_Ticker = 'COR'
ORDER BY Filed_Date;
In this file, Debt_to_Equity equals Total_Liabilities divided by Shareholder_Equity:
all liabilities, not only borrowed money. In 2022 the company’s equity was only about 71 million dollars, against liabilities of about 56 billion, so the ratio is extreme.
In 109 filings the equity is negative, which gives a negative ratio that ORDER BY ... DESC pushes to the bottom.
A ratio is only as meaningful as its denominator.
A plausible mistake: reading the ratio as a company ranking
The reasoning: the ten rows are the ten most indebted companies.
But the rows are filings, not companies, COR appears three times, and an extreme value can come from a tiny equity rather than from heavy borrowing.
Check the denominator before drawing a conclusion.
3. Which five companies had the highest average annual revenue (Sales_Revenue), in billions of dollars? Show the ticker and the average, rounded to one decimal.
Show a possible answer
SELECT Stock_Ticker,
ROUND(AVG(Sales_Revenue) / 1e9, 1) AS average_revenue_billions
FROM Filings
GROUP BY Stock_Ticker
ORDER BY AVG(Sales_Revenue) DESC
LIMIT 5;
The result is WMT (597.8), AMZN (486.2), AAPL (383.6), CVS (310.3), and UNH (307.6).
The average is over the filings in the file, so it covers a different number of years for different companies.
Dividing by 1e9, one billion, turns dollars into billions, as in Calculations in a query.
A plausible mistake: no GROUP BY
The reasoning: AVG already computes an average, so adding the ticker should give an average for each company.
But without GROUP BY, the average is calculated over the whole table and the query returns a single row, with an arbitrary ticker next to it.
SELECT Stock_Ticker,
AVG(Sales_Revenue)
FROM Filings
ORDER BY AVG(Sales_Revenue) DESC
LIMIT 5;
4. Intel’s ticker is INTC. How many filings does it have, and how many of them have a value in Net_Income? What is the average of Net_Income? Show the three numbers in one row, in this order.
Show a possible answer
SELECT COUNT(*) AS filings,
COUNT(Net_Income) AS with_net_income,
AVG(Net_Income) AS average_net_income
FROM Filings
WHERE Stock_Ticker = 'INTC';
Intel has 4 filings, but only 3 have a value in Net_Income. COUNT(*) counts rows, and COUNT(column) counts only the rows where that column is not NULL.AVG also skips NULL, so the average of about 1.478 billion covers three years, not four.
(Check that a number is believable shows that Net_Income in this file is not reliable, so use this result to learn how AVG and NULL behave, not as Intel’s profit.) In the whole table, 1,274 of the 2,063 filings have no Net_Income.
A plausible mistake: assuming a missing value is zero
The reasoning: if the first year is missing, it probably counts as 0 in the average.
In fact AVG ignores it. If a missing year is treated as zero, the average would be lower, so the choice changes the result.
Decide on purpose how to treat missing values.
5. How many companies have their headquarters in California?
Show a possible answer
SELECT COUNT(*) AS companies_in_california
FROM SP500
WHERE Headquarters_Location LIKE '%California';
The result is 68 rows (tickers), which are 67 companies, because Alphabet has two tickers.
(A question about companies would count distinct company identifiers.) The location column holds a city and a state, for example Cupertino, California, so the pattern %California looks for text that ends with California, as in the LIKE pattern list.
A plausible mistake: comparing with =
The reasoning: = 'California' is the direct way to ask for California.
But no row consists only of the word California, because each value also contains a city, so the result is 0.
SELECT COUNT(*) AS companies_in_california
FROM SP500
WHERE Headquarters_Location = 'California';
6. In which five years were the most Health Care companies founded? If two years have the same number of companies, show the earlier year first.
Show a possible answer
SELECT Founded,
COUNT(*) AS companies
FROM SP500
WHERE Industry = 'Health Care'
GROUP BY Founded
ORDER BY companies DESC, Founded
LIMIT 5;
Four years tie with 3 companies each: 1958, 1979, 1985, and 1989.
Five more years have 2 companies each (1961, 1978, 1980, 1982, and 1999), so the fifth place is itself a tie, and the second sort key Founded chooses the earliest of them, 1961.
The second sort key makes the order of tied years fixed, as in Sort and limit results.
Without it, LIMIT may cut a tie in an arbitrary place, and the result is harder to repeat.
7. Which companies had revenue above 100 billion dollars in at least one filing?
Show a possible answer
SELECT Stock_Ticker,
ROUND(MAX(Sales_Revenue) / 1e9, 1) AS highest_revenue_billions
FROM Filings
GROUP BY Stock_Ticker
HAVING MAX(Sales_Revenue) > 100000000000
ORDER BY MAX(Sales_Revenue) DESC;
The result has 36 tickers, from WMT (about 648 billion) to PFE (about 100 billion).GOOG and GOOGL are two share classes of the same company, so they have the same revenue.
The condition on a group result belongs in HAVING, because WHERE filters rows before grouping.
A plausible mistake: an aggregate in WHERE
The reasoning: the condition is about the highest revenue, so it can be written in WHERE.
But MAX is calculated per group, after the rows are chosen, so SQLite reports an error.
SELECT Stock_Ticker, MAX(Sales_Revenue)
FROM Filings
WHERE MAX(Sales_Revenue) > 100000000000
GROUP BY Stock_Ticker;
8. Change the industry Health Care to Hefker, an invented test value (the Hebrew word for “ownerless”), to practice an update. How many rows will it change, and how do you check before running it?
Show a possible answer
First check which rows the condition selects:
SELECT COUNT(*) AS rows_to_change
FROM SP500
WHERE Industry = 'Health Care';
The result is 59. Then run the update (Change data) with the same condition:
UPDATE SP500
SET Industry = 'Hefker'
WHERE Industry = 'Health Care';
Run the check again with 'Hefker' to see 59, and select Revert Changes when you finish, so that the file stays as downloaded.
A plausible mistake: no WHERE
The reasoning: the statement names the new value, so it seems enough.
Without WHERE, the update applies to all 500 companies, and every industry becomes Hefker.
Always check the condition with a SELECT first.
UPDATE SP500
SET Industry = 'Hefker';
Check that a number is believable
Many queries on this page rely on the values in the file being right.
Test one.
SELECT Filed_Date, Net_Income, Sales_Revenue
FROM Filings
WHERE Stock_Ticker = 'AAPL'
ORDER BY Filed_Date;
For the filing of 2022-09-30, the file shows a Net_Income of about 6.55 billion dollars and Sales_Revenue of about 394.3 billion.
Apple’s annual report for fiscal 2022 (Form 10-K, available on SEC EDGAR, the free public archive of company reports) shows revenue of 394,328 million dollars, which matches the file, and net income of 99,803 million (about 99.8 billion), which does not match the 6.55 billion in the file.
For fiscal 2021 the report shows net income of 94,680 million, while the file has no value at all.
What to conclude
In the example we checked, Net_Income is far from the net income that the company reported, and it is missing in most rows.
Until you verify it against the source, do not use averages and rankings based on it, or ratios derived from it such as Profit_Margin and Return_on_Assets, as company results.
In the same example Sales_Revenue matched the report (we did not compare the assets and equity here), but one example is not a proof for all 500 companies.
The method applies to any dataset, not only this one: compare one value you can verify in the original source, read the provenance of the data, and ask which columns you have actually checked before writing a conclusion.
What to remember
COUNT(*)counts rows;COUNT(column)counts rows where that column is notNULL.- A row can describe a filing and not a company. Check what one row is before you count or rank.
- A ratio can be extreme because of its denominator.
- Put a condition on a group result in
HAVING, and a condition on rows inWHERE. - Check an
UPDATEwith aSELECTthat uses the same condition. - Before you trust a column, compare one value with the original source.
Return to the SQL guide to review a command, or to the glossary for a term.