Is your die fair? You roll it 120 times and record how often each face comes up. A fair die should give each face about 20 times, but you got 14 ones, 22 twos, 18 threes, 27 fours, 17 fives and 22 sixes. Twenty-seven fours looks suspicious, and fourteen ones looks low. The chi-square test turns that hunch into a number. For each face it measures how far the observed count OO is from the expected count EE, scaled by the expected count, and adds the results:

χ2=∑(O−E)2E.\chi^2 = \sum \frac{(O - E)^2}{E}.

For these rolls the answer is χ2=5.30\chi^2 = 5.30 on 5 degrees of freedom, with a p-value of 0.38: a fair die produces deviations this large in roughly 38 of every 100 sets of 120 rolls, so there is no real reason to accuse it. The test compares observed with expected counts, which makes it the standard tool for categories rather than measurements. This article works through the chi-square formula step by step for the goodness of fit test and the test of independence, shows how to compute expected frequencies and degrees of freedom, and covers 2×2 tables, Fisher’s exact test, effect sizes, residuals, the assumptions, and the strange case of Gregor Mendel’s peas.

What is a chi-square test used for?

A t-test asks whether means differ. The chi-square test asks whether counts in categories are distributed the way a hypothesis predicts. The raw material is always a tally: rolls per face, patients improved per treatment group, leading digits equal to 1, 2, 3 and so on. It comes in two main forms.

  • Goodness of fit: one categorical variable, compared with a set of proportions fixed in advance. Is the die fair? Do births spread evenly across the days of the week? Do the offspring of a genetic cross appear in a 3:1 ratio?
  • Test of independence: two categorical variables, cross-tabulated in a contingency table. Is preferred course format related to year of study? Is recovery related to which treatment a patient received?

A third variant, the test of homogeneity, compares one variable across several separately sampled groups; its arithmetic is identical to the test of independence. The p-value at the end has the usual meaning and caveats, set out in what p-values really mean.

How do you calculate chi-square for a goodness of fit test?

Return to the die. The null hypothesis is that each face has probability 1/61/6; the alternative is that at least one does not. With n=120n = 120 rolls, the expected frequency for each face is

Ei=n pi=120×16=20.E_i = n\,p_i = 120 \times \tfrac{1}{6} = 20.

Step 1, lay out observed and expected counts, and compute each cell’s contribution.

Face Observed O Expected E O − E (O − E)² (O − E)²/E
1 14 20 −6 36 1.80
2 22 20 2 4 0.20
3 18 20 −2 4 0.20
4 27 20 7 49 2.45
5 17 20 −3 9 0.45
6 22 20 2 4 0.20
Total 120 120 0 106 5.30

Step 2, add the contributions.

χ2=1.80+0.20+0.20+2.45+0.45+0.20=5.30.\chi^2 = 1.80 + 0.20 + 0.20 + 2.45 + 0.45 + 0.20 = 5.30.

Squaring makes negative and positive deviations count alike; dividing by EE makes the statistic fair across categories, since a shortfall of 6 matters far more against an expectation of 20 than of 2,000. Most of the total comes from the four (2.45) and the one (1.80).

Step 3, find the degrees of freedom. For a goodness of fit test with kk categories,

df=k−1=6−1=5.\text{df} = k - 1 = 6 - 1 = 5.

The subtraction reflects a constraint: the six counts must add up to 120, so once five of them are known the sixth is determined. If you had to estimate parameters from the data to obtain the expected counts, for example fitting a Poisson mean before testing whether counts follow a Poisson distribution, you would subtract one more degree of freedom for each estimated parameter.

Step 4, compare with the chi-square distribution. The critical value for α=0.05\alpha = 0.05 with 5 degrees of freedom is χ0.05, 52=11.07\chi^2_{0.05,\,5} = 11.07. The observed 5.30 is well below it, and the p-value is

p=P(χ52≥5.30)=0.380.p = P(\chi^2_5 \ge 5.30) = 0.380.

The test does not reject fairness. It also does not prove the die is fair: 120 rolls are not enough to detect a modest bias. A die that lands on four with probability 0.20 instead of 0.167 would often pass this test too.

How do you read the result? The chi-square distribution

Why should the sum of scaled squared deviations follow any particular distribution? Each count is approximately normal for a reasonably large sample, with mean EiE_i and variance close to EiE_i, so each term

Zi≈Oi−EiEiZ_i \approx \frac{O_i - E_i}{\sqrt{E_i}}

behaves roughly like a standard normal variable, and χ2=∑Zi2\chi^2 = \sum Z_i^2 is a sum of squared standard normals. That is exactly how the chi-square distribution is defined: if Z1,…,ZkZ_1, \dots, Z_k are independent standard normal variables, then

Q=Z12+Z22+⋯+Zk2Q = Z_1^2 + Z_2^2 + \cdots + Z_k^2

has a chi-square distribution with kk degrees of freedom. The deviations in a goodness of fit test are not quite independent, because they must sum to zero, and that single linear constraint costs one degree of freedom, which is why the die statistic is compared with 5 degrees of freedom rather than 6.

The chi-square distribution with kk degrees of freedom has density

f(x)=xk/2−1e−x/22k/2 Γ(k/2),x>0,f(x) = \frac{x^{k/2 - 1} e^{-x/2}}{2^{k/2}\,\Gamma(k/2)}, \qquad x > 0,

where Γ\Gamma is the gamma function. Its mean is kk and its variance is 2k2k, because each Zi2Z_i^2 has mean 1 and variance 2. A quick simulation confirms this: with a fixed seed chosen in advance, summing the squares of five standard normals 100,000 times gave an average of 5.01 and a variance of 9.98, against the theoretical 5 and 10.

Chi-square distributions for several degrees of freedom, with the critical value and observed statistic for the die exampledf = 1df = 2df = 4df = 802468101214161820value of the chi-square statistic0.10.20.30.40.5densitycritical value 11.075% right tail (α = 0.05)observed χ² = 5.30df = 5, p = 0.38df = 5 (die example)df = 1, 2, 4, 8

Figure 1 — Chi-square densities, computed from the formula above, for 1, 2, 4 and 8 degrees of freedom (grey) and for 5 degrees of freedom (black), the reference distribution for the die. The red right tail beyond the critical value 11.07 contains 5% of the probability. The observed statistic for the 120 rolls, 5.30 (blue), sits in the bulk of the distribution: df = 5, p = 0.38.

Figure 1 shows how the shape changes. With 1 or 2 degrees of freedom the density is highest near zero; as the degrees of freedom grow, the peak moves right (it sits at k−2k - 2 for k≥2k \ge 2) and the curve becomes more symmetric, approaching a normal shape for large kk, as the central limit theorem predicts for a sum of many independent terms.

Two features matter when reading a result. First, the test is one-tailed by construction: large values signal a poor fit, so the rejection region is the right tail only. Second, since the mean equals the degrees of freedom, a statistic close to its degrees of freedom is entirely ordinary. The die’s 5.30 on 5 degrees of freedom is about as typical as a result can be.

The approximation can be checked directly. With a second fixed seed, 100,000 sets of 120 rolls of a fair simulated die gave χ2≥5.30\chi^2 \ge 5.30 in 38.9% of cases (theory: 38.0%) and exceeded 11.07 in 5.1% (nominal: 5%). With expected counts of 20 per face, the approximation is excellent.

How does the chi-square test of independence work?

Now an illustrative scenario with two variables. A university surveys 220 students, 120 in their first year and 100 in their final year, and asks which course format they prefer. The results form a 2×3 contingency table:

In-person Hybrid Online Row total
First-year 40 35 45 120
Final-year 50 20 30 100
Column total 90 55 75 220

The null hypothesis is that format preference is independent of year. If it were, the proportion preferring each format would be the same in both rows. Overall, 90/220=40.9%90/220 = 40.9\% prefer in-person, so under independence we would expect 40.9% of the 120 first-years to prefer it, which is 49.0949.09 students. In general, the expected count in row ii and column jj is

Eij=(row i total)×(column j total)grand total.E_{ij} = \frac{(\text{row } i \text{ total}) \times (\text{column } j \text{ total})}{\text{grand total}}.

This formula comes straight from the multiplication rule for independent events in probability: P(A∩B)=P(A) P(B)P(A \cap B) = P(A)\,P(B), with each probability estimated from the margins. The expected counts are:

In-person Hybrid Online
First-year 120 × 90 / 220 = 49.09 120 × 55 / 220 = 30.00 120 × 75 / 220 = 40.91
Final-year 100 × 90 / 220 = 40.91 100 × 55 / 220 = 25.00 100 × 75 / 220 = 34.09

Each row and column of expected counts adds up to the same totals as the observed table, as it must. The contributions (O−E)2/E(O - E)^2/E are:

In-person Hybrid Online
First-year 1.684 0.833 0.409
Final-year 2.020 1.000 0.491

Summing all six,

χ2=1.684+0.833+0.409+2.020+1.000+0.491=6.437.\chi^2 = 1.684 + 0.833 + 0.409 + 2.020 + 1.000 + 0.491 = 6.437.

The degrees of freedom for a table with rr rows and cc columns are

df=(r−1)(c−1)=(2−1)(3−1)=2.\text{df} = (r - 1)(c - 1) = (2 - 1)(3 - 1) = 2.

Once the row and column totals are fixed, you can fill in only two cells freely; the rest are forced by the totals. The critical value at α=0.05\alpha = 0.05 with 2 degrees of freedom is 5.991, and

p=P(χ22≥6.437)=0.040.p = P(\chi^2_2 \ge 6.437) = 0.040.

So at the 5% level the data suggest that format preference is associated with year of study, though not overwhelmingly. The test does not say which direction the association runs, how strong it is, or why it exists, and it says nothing about causation: final-years might prefer in-person teaching because of their year, or because of who stays on to the final year, a distinction that matters as much here as in Simpson’s paradox.

What about 2×2 tables? Yates’ correction and Fisher’s exact test

The simplest contingency table has two rows and two columns, and it gets special attention because it is so common and because small samples cause trouble there first. Consider a small illustrative pilot: 20 patients, 10 on a new treatment and 10 on standard care. Seven of the treated patients improve, against two of the controls.

Improved Not improved Total
Treatment 7 3 10
Control 2 8 10
Total 9 11 20

The expected counts are 10×9/20=4.510 \times 9/20 = 4.5 for the improved cells and 5.55.5 for the others. Every observed count is 2.5 away from its expected value, so

χ2=2×2.524.5+2×2.525.5=2.778+2.273=5.05,\chi^2 = 2 \times \frac{2.5^2}{4.5} + 2 \times \frac{2.5^2}{5.5} = 2.778 + 2.273 = 5.05,

with 1 degree of freedom and p=0.025p = 0.025. That looks like clear evidence. But two expected counts are below 5, and with counts this small the smooth chi-square curve is a poor approximation to the jumpy, discrete distribution of the real statistic.

Yates’ continuity correction. In 1934 Frank Yates proposed shrinking each absolute deviation by 0.5 before squaring, to compensate for approximating a discrete distribution with a continuous one:

χYates2=∑(∣O−E∣−0.5)2E.\chi^2_{\text{Yates}} = \sum \frac{\left(\lvert O - E \rvert - 0.5\right)^2}{E}.

Here every ∣O−E∣\lvert O - E \rvert becomes 2.02.0, giving

χYates2=2×44.5+2×45.5=3.23,p=0.072.\chi^2_{\text{Yates}} = 2 \times \frac{4}{4.5} + 2 \times \frac{4}{5.5} = 3.23, \qquad p = 0.072.

The conclusion flips. The correction is still debated. Defenders note that it brings the p-value close to that of Fisher’s exact test; critics reply that it does so by matching a test which is itself conservative, so the corrected test rejects a true null less often than the nominal 5% and loses power. Many statisticians prefer the uncorrected statistic when expected counts are adequate and an exact test when they are not. Some software applies Yates’ correction to 2×2 tables by default, so check which version you are reading.

Fisher’s exact test. Instead of approximating, compute the probability directly. Treat the row and column totals as fixed. Then the number of improved patients in the treatment row, aa, follows a hypergeometric distribution: of the 9 patients who improved, how many happen to fall among the 10 treated, if treatment makes no difference?

P(a)=(10a)(109−a)(209).P(a) = \frac{\binom{10}{a}\binom{10}{9 - a}}{\binom{20}{9}}.

For the observed table, a=7a = 7:

P(7)=(107)(102)(209)=120×45167,960=0.03215.P(7) = \frac{\binom{10}{7}\binom{10}{2}}{\binom{20}{9}} = \frac{120 \times 45}{167{,}960} = 0.03215.

The one-sided p-value adds the probabilities of this table and the more extreme ones in the same direction:

P(a≥7)=0.03215+0.00268+0.00006=0.0349.P(a \ge 7) = 0.03215 + 0.00268 + 0.00006 = 0.0349.

The usual two-sided p-value adds every table at least as improbable as the observed one in either direction. Because both groups have 10 patients the distribution is symmetric, and the two-sided p-value is 0.06980.0698. So the exact test, like Yates, says this small pilot is suggestive but not conclusive, while the uncorrected chi-square overstates the evidence. With today’s computers there is little reason not to use the exact test whenever expected counts are small.

What assumptions does the chi-square test make?

Independent observations. Each subject or event must contribute to exactly one cell, and observations must not influence each other. Counting the same person twice, or treating repeated answers from one respondent as separate observations, breaks the test in a way no formula can repair. For paired categorical data, such as the same people answering yes or no before and after an intervention, McNemar’s test is the right tool instead.

Counts, not percentages or means. The statistic depends on the absolute size of the counts. Feeding in percentages gives nonsense: the die table expressed as percentages would sum deviations of a few percentage points against expected values of 16.7, and would yield a statistic that changes with the arbitrary choice of scale rather than the amount of evidence. Doubling every count in the die example, with the same proportions, doubles χ2\chi^2 to 10.60.

Large enough expected counts. The chi-square distribution is a large-sample approximation. The rule of thumb usually attributed to William Cochran, set out in his papers of the early 1950s including “Some Methods for Strengthening the Common χ² Tests” (Biometrics, 1954), is that no expected count should fall below 1 and no more than 20% of expected counts should fall below 5. For a 2×2 table, that effectively means all four expected counts should be at least 5. Notice that the rule concerns expected counts; an observed zero is not a problem in itself. Cochran himself regarded the threshold as somewhat arbitrary, and later research suggests the approximation is often fine with smaller expected values, but the rule remains a sensible default. When it fails, merge sparse categories where that makes substantive sense, use Fisher’s exact test, or compute a Monte Carlo p-value by simulating tables under the null.

Categories fixed in advance. Choosing category boundaries after seeing the data inflates the false-positive rate like any other analysis decided after the fact.

How strong is the association? Cramér’s V and phi

The chi-square statistic measures evidence, not strength. Like any test statistic it grows with the sample size. If you multiplied every cell of the course-format table by 10, the proportions would be identical but χ2\chi^2 would rise tenfold to 64.4 and the p-value would become astronomically small. To describe how strong an association is, you need an effect size that removes the dependence on nn.

For a 2×2 table the standard measure is the phi coefficient,

ϕ=χ2n,\phi = \sqrt{\frac{\chi^2}{n}},

which equals the absolute value of the Pearson correlation coefficient between the two binary variables coded as 0 and 1. For larger tables, Cramér’s V generalises it:

V=χ2n (min⁡(r,c)−1).V = \sqrt{\frac{\chi^2}{n\,(\min(r, c) - 1)}}.

Both run from 0 (no association) to 1 (perfect association). For the course-format survey,

V=6.437220×1=0.171,V = \sqrt{\frac{6.437}{220 \times 1}} = 0.171,

a weak to modest association by the usual conventions. For tables with one degree of freedom in the smaller dimension, Cohen’s often-quoted benchmarks for small, medium and large are about 0.1, 0.3 and 0.5, though like all such benchmarks they are only a rough guide.

The danger of reporting only the p-value is clearest with very large samples. Imagine an illustrative online experiment with 100,000 users in each of two versions of a page. In version A, 50.5% click a button; in version B, 49.5% do. The 2×2 chi-square test gives

χ2=20.0,df=1,p=7.7×10−6,\chi^2 = 20.0, \qquad \text{df} = 1, \qquad p = 7.7 \times 10^{-6},

a result that sounds dramatic. But ϕ=20.0/200,000=0.010\phi = \sqrt{20.0/200{,}000} = 0.010: a one-point difference in click rates that may or may not matter, depending entirely on context. Report the effect size and the actual proportions, ideally with a confidence interval for the difference, alongside the test.

Which cells drive a significant chi-square result?

A significant test of independence says only that the table as a whole departs from independence. To see where, look at the residuals. The Pearson residual for each cell is

rij=Oij−EijEij,r_{ij} = \frac{O_{ij} - E_{ij}}{\sqrt{E_{ij}}},

whose square is that cell’s contribution to χ2\chi^2. Pearson residuals do not have variance 1, so the more useful quantity for post hoc inspection is the adjusted standardised residual,

dij=Oij−EijEij(1−Rin)(1−Cjn),d_{ij} = \frac{O_{ij} - E_{ij}}{\sqrt{E_{ij}\left(1 - \dfrac{R_i}{n}\right)\left(1 - \dfrac{C_j}{n}\right)}},

where RiR_i and CjC_j are the row and column totals. Under independence each dijd_{ij} is approximately standard normal, so values beyond about ±2\pm 2 flag cells that depart noticeably from expectation. For the survey:

In-person Hybrid Online
First-year −2.50 +1.56 +1.17
Final-year +2.50 −1.56 −1.17

The story is now clear. The association is driven mainly by the in-person column: final-year students prefer in-person teaching more often than independence predicts (50 observed against 40.9 expected), and first-years less often. The hybrid and online differences point the opposite way but are smaller. In a 2×k table the residuals in each column are equal and opposite, because the two rows must balance.

Two cautions apply. Inspecting six residuals is itself a set of multiple comparisons, so a single value just beyond 2 in a large table is weak evidence; a Bonferroni-style adjustment of the threshold is a common safeguard. And residuals describe where the data depart from independence, not why.

Was Mendel’s data too good to be true?

The goodness of fit test has a famous history in genetics. In his 1866 paper on pea hybrids, Gregor Mendel reported that a cross between plants with round and wrinkled seeds produced, in the second generation, 5,474 round seeds and 1,850 wrinkled ones. His theory predicted a 3:1 ratio. Of 7,324 seeds, the expected counts are 5,493 round and 1,831 wrinkled, and

χ2=(5474−5493)25493+(1850−1831)21831=0.066+0.197=0.263,\chi^2 = \frac{(5474 - 5493)^2}{5493} + \frac{(1850 - 1831)^2}{1831} = 0.066 + 0.197 = 0.263,

with 1 degree of freedom and p=0.61p = 0.61. A comfortable fit.

The problem, which R. A. Fisher raised in his 1936 paper “Has Mendel’s Work Been Rediscovered?” in Annals of Science, is that nearly all of Mendel’s experiments fit like this. Fisher applied the chi-square test across the experiments and added up the results. His total was about 41.6 on 84 degrees of freedom. Recall that the mean of the chi-square distribution equals its degrees of freedom: if the data came from honest random sampling, a total near 84 would be typical. A total as low as 41.6 means the data are closer to the theory than chance usually allows. Fisher’s table put the probability of a fit at least this good at about 7 in 100,000 (his tabled value of PP was 0.99993, computed with a normal approximation; the exact chi-square lower tail for these numbers is closer to 3 in 100,000). Here the left tail of the distribution is the interesting one: too good a fit is evidence of something other than chance. Fisher concluded that most of the data had been adjusted to agree with Mendel’s expectations, and suggested that an assistant who knew what Mendel hoped to find might have been responsible.

The debate that followed, mostly from the 1960s onward, has produced dozens of papers and no consensus. Proposed explanations include unconscious bias in classifying ambiguous seeds, stopping counts once the ratio looked right, selective reporting of the most convincing experiments, and objections to Fisher’s assumption that seeds and plants behave as independent binomial trials. Some analysts argue the results need no deliberate falsification to explain them; others find Fisher’s case essentially sound. The method itself, testing for an excessively good fit, is not in dispute.

Goodness of fit tests also appear in forensic accounting: testing whether leading digits follow Benford’s law is a chi-square test with nine categories and 8 degrees of freedom. As that article explains, a significant result shows only that the data do not match the reference distribution, which can happen for entirely innocent reasons. The test is only as meaningful as the expected distribution behind it.

Where did the chi-square test come from?

Karl Pearson introduced the test in a 1900 paper in the Philosophical Magazine with the formidable title “On the Criterion that a Given System of Deviations from the Probable in the Case of a Correlated System of Variables is Such that it Can Be Reasonably Supposed to Have Arisen from Random Sampling”. He derived the distribution of the statistic, which he wrote as χ2\chi^2, and applied it to examples including dice-throwing data, an apt beginning for a test that is still taught with dice.

Pearson got one important detail wrong. When the expected counts are computed from the data, as in a contingency table, he used too many degrees of freedom; in effect he counted the cells of the table rather than the independent pieces of information. In a 1922 paper in the Journal of the Royal Statistical Society, “On the Interpretation of χ² from Contingency Tables, and the Calculation of P”, R. A. Fisher showed that for contingency tables the correct number is (r−1)(c−1)(r - 1)(c - 1); for a 2×2 table that means 1 degree of freedom, not the 3 that Pearson’s approach implied. Fisher extended the argument to estimated parameters in 1924. Pearson resisted, and the dispute fed a lasting hostility between the two men, but Fisher’s degrees of freedom are what every textbook now uses.

The short version

The chi-square test compares observed counts with the counts a hypothesis predicts, using χ2=∑(O−E)2/E\chi^2 = \sum (O - E)^2/E. In a goodness of fit test the expected counts come from proportions you specify, and the degrees of freedom are k−1k - 1, minus one for each estimated parameter. In a test of independence the expected counts come from the contingency table’s margins, row total times column total over grand total, and the degrees of freedom are (r−1)(c−1)(r - 1)(c - 1). Large values of the statistic, in the right tail of the chi-square distribution, signal a poor fit; a value near its degrees of freedom is ordinary. Use counts rather than percentages, keep observations independent, check that expected frequencies are mostly 5 or more, and switch to Fisher’s exact test for small 2×2 tables. Then go beyond the p-value: report Cramér’s V or phi to show how strong the association is, and adjusted residuals to show where it lies. And remember Mendel’s peas: a fit can also be too good.


Related topics: T-Test Explained: How to Do a T-Test, the Formula, and Which Type to Use, What P-Values Really Mean (and What They Don’t), Confidence Interval: What It Means, How to Calculate It, and What 95% Really Says, How to Calculate Probability: The Formula, the Rules and Worked Examples, What Is a Normal Distribution? The Density, the Parameters, and the Limits, What Is Standard Deviation? The Formula, a Worked Calculation, and Why n − 1, Correlation Coefficient: What r Means and How to Calculate It, Simpson’s Paradox: When Every Subgroup Disagrees With the Whole, Why Benford’s Law Does Not Prove Election Fraud, The Central Limit Theorem: Why Bell Curves Are Everywhere

Frequently asked

What is a chi-square test used for?

A chi-square test checks whether observed counts differ from the counts you would expect under some hypothesis by more than random sampling would explain. The goodness of fit test compares the counts in one categorical variable with a fixed set of proportions, for example whether a die lands on each face equally often. The test of independence asks whether two categorical variables in a contingency table are associated, for example whether preferred course format depends on year of study. It works on counts of categories, not on means of measurements.

How do you calculate chi-square?

For every category or cell, subtract the expected count from the observed count, square the difference, and divide by the expected count. Add these contributions up. For a die rolled 120 times, each face is expected 20 times; observed counts of 14, 22, 18, 27, 17 and 22 give contributions 1.80, 0.20, 0.20, 2.45, 0.45 and 0.20, so the statistic is 5.30. Compare it with the chi-square distribution on the right degrees of freedom, here 5, which gives p = 0.38.

What is the difference between goodness of fit and test of independence?

A goodness of fit test has one categorical variable and a set of expected proportions that you specify in advance, such as 1/6 for each face of a die or 3:1 for a Mendelian cross. A test of independence has two categorical variables cross-tabulated in a contingency table, and the expected counts are not given in advance but computed from the table's own row and column totals, as row total times column total divided by the grand total. The arithmetic of the statistic is identical; the degrees of freedom and the source of the expected counts differ.

How do you find degrees of freedom for chi-square?

For a goodness of fit test with k categories and fully specified expected proportions, the degrees of freedom are k - 1, because the counts must add up to the sample size. If you estimate parameters from the data to obtain the expected counts, subtract one further degree of freedom for each parameter. For a test of independence on a table with r rows and c columns, the degrees of freedom are (r - 1)(c - 1), so a 2 by 2 table has 1 and a 2 by 3 table has 2.

What is the minimum expected frequency for a chi-square test?

The usual rule of thumb, generally attributed to William Cochran in the 1950s, is that no expected count should be below 1 and no more than 20 percent of the expected counts should be below 5. For a 2 by 2 table this means every expected count should be at least 5. The rule concerns expected counts, not observed ones. When it fails, combine sparse categories if that makes sense, or use an exact method such as Fisher's exact test or a simulated p-value.

What is the difference between a chi-square test and a t-test?

A t-test compares means of a numerical measurement, such as heights or reaction times, between one or two groups. A chi-square test compares counts of categorical outcomes, such as how many people chose each option, with what a hypothesis predicts. If your data are labels you can tally, use a chi-square test; if they are measurements you can average, a t-test or a related method is usually the right tool. A 2 by 2 chi-square test is equivalent to a two-sided z-test for the difference of two proportions.