Skip to lesson

Practice: tables and data types

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most table bugs come from a small set of choices: a number type for a phone, FLOAT for money, text for dates, a careless MODIFY. Each has a short, reliable rule, and the exercises below put all of them to work.

Choosing types for a real requirement

Choosing a type means asking two questions about each value: what kind of value is it, and what is the largest or longest it can ever be?

Example 1 · A table from a cinema requirement

SQL
-- Requirement: a cinema stores each booking with a booking number,-- the customer's mobile, the show date and time, up to 10 seats,-- the seat class (SILVER, GOLD or RECLINER), the amount paid,-- whether parking was added, and when the booking was made.
CREATE TABLE cinema_ticket_bookings (  booking_id   INT AUTO_INCREMENT PRIMARY KEY,  mobile       VARCHAR(15),  show_at      DATETIME,  seats        TINYINT UNSIGNED,  seat_class   ENUM('SILVER', 'GOLD', 'RECLINER'),  amount_paid  DECIMAL(8,2),  has_parking     BOOLEAN,  booked_at    DATETIME DEFAULT CURRENT_TIMESTAMP);
DESCRIBE cinema_ticket_bookings;
Output
+-------------+----------------------------------+------+-----+-------------------+-------------------+
| Field       | Type                             | Null | Key | Default           | Extra             |
+-------------+----------------------------------+------+-----+-------------------+-------------------+
| booking_id  | int                              | NO   | PRI | NULL              | auto_increment    |
| mobile      | varchar(15)                      | YES  |     | NULL              |                   |
| show_at     | datetime                         | YES  |     | NULL              |                   |
| seats       | tinyint unsigned                 | YES  |     | NULL              |                   |
| seat_class  | enum('SILVER','GOLD','RECLINER') | YES  |     | NULL              |                   |
| amount_paid | decimal(8,2)                     | YES  |     | NULL              |                   |
| has_parking | tinyint(1)                       | YES  |     | NULL              |                   |
| booked_at   | datetime                         | YES  |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
+-------------+----------------------------------+------+-----+-------------------+-------------------+

What this code does

  • Each requirement maps to one type: mobile as text, the planned show as DATETIME, a small never-negative count as TINYINT UNSIGNED, the fixed classes as ENUM, money as DECIMAL, parking as BOOLEAN.
  • -- starts a comment: MySQL ignores the rest of the line. Writing the requirement above the table keeps the reasons next to the design.
  • DEFAULT_GENERATED under Extra marks a default that comes from a function, here CURRENT_TIMESTAMP.

A quick guide:

  • Id of the row: INT AUTO_INCREMENT PRIMARY KEY (BIGINT for very fast-growing tables).
  • Counts and small numbers: TINYINT, SMALLINT or INT by range; UNSIGNED if never negative.
  • Money: DECIMAL(p, 2), with p from the largest amount.
  • Phone, PIN, Aadhaar, IFSC: text (VARCHAR or CHAR), never a number type.

And for the rest:

  • Short text: VARCHAR(n); long free text: TEXT; short fixed list: ENUM.
  • A day: DATE; a planned date and time: DATETIME; a record time: TIMESTAMP or DATETIME.
  • Yes/no: BOOLEAN (stored as 0 and 1).

Fixing wrong types

A wrong type works on day one and fails later, when the data grows or someone runs a report. The usual suspects:

  • FLOAT/DOUBLE for money: totals drift by a few paise.

Example 2 · Text dates sort wrong and cannot be converted

SQL
CREATE TABLE scholarship_text_dates (  student     VARCHAR(30),  awarded_on  VARCHAR(10));
INSERT INTO scholarship_text_dates VALUES  ('Asha', '15-08-2025'), ('Ravi', '02-10-2024'), ('Meena', '26-01-2025');
SELECT * FROM scholarship_text_dates ORDER BY awarded_on;
ALTER TABLE scholarship_text_dates MODIFY awarded_on DATE;
Output
+---------+------------+
| student | awarded_on |
+---------+------------+
| Ravi    | 02-10-2024 |
| Asha    | 15-08-2025 |
| Meena   | 26-01-2025 |
+---------+------------+

ERROR 1292 (22007): Incorrect date value: '15-08-2025' for column 'awarded_on' at row 1

What this code does

  • Sorted as text, the dates come out by day number: 2 October 2024, then 15 August 2025, then 26 January 2025. The real order is October 2024, January 2025, August 2025.
  • Changing the column to DATE fails with error 1292, because 15-08-2025 is not in year-first form. The right type at the start would have avoided both problems.

Use DECIMAL.

  • INT for a mobile number: error 1264, and leading zeros vanish. Use VARCHAR(15).
  • VARCHAR for dates: no checks, and '02-10-2024' sorts before '15-08-2025' and '26-01-2025' as text, which is the wrong calendar order. Use DATE.
  • VARCHAR for prices: '120.00' sorts before '45' as text, and maths needs conversions.
  • TIMESTAMP for far-future dates: refused after January 2038. Use DATETIME.

Many wrong types can be changed in place with ALTER TABLE ... MODIFY, if every stored value can be converted: '45' becomes 45.00. Values that cannot be read in the new type, such as 'Rs 5' as a decimal or '15-08-2025' as a date, make the whole change fail, so you clean the data first.

Find the bug

Find the wrong type

Each table has one column with the wrong type. Find it.

Store the fee a student paid.

Round 1 of 3
Text dates in day-first form must be converted row by row. The Changing Data module shows how with UPDATE and the STR_TO_DATE function.

Changing tables safely with ALTER TABLE

A safe change is one where you know in advance what happens to every existing row. Five checks cover nearly every case:

  1. Read the current definition with SHOW CREATE TABLE before you write the ALTER. 2.

Example 3 · Converting text prices to DECIMAL

SQL
CREATE TABLE stationery_items (  item   VARCHAR(30),  price  VARCHAR(10));
INSERT INTO stationery_items VALUES ('Pen', '10.50'), ('Notebook', '45'), ('Geometry box', '120.00');SELECT * FROM stationery_items ORDER BY price;
ALTER TABLE stationery_items MODIFY price DECIMAL(7,2) NOT NULL;SELECT * FROM stationery_items ORDER BY price;
INSERT INTO stationery_items VALUES ('Eraser', 'Rs 5');
Output
+--------------+--------+
| item         | price  |
+--------------+--------+
| Pen          | 10.50  |
| Geometry box | 120.00 |
| Notebook     | 45     |
+--------------+--------+
+--------------+--------+
| item         | price  |
+--------------+--------+
| Pen          |  10.50 |
| Notebook     |  45.00 |
| Geometry box | 120.00 |
+--------------+--------+

ERROR 1366 (HY000): Incorrect decimal value: 'Rs 5' for column 'price' at row 1

What this code does

  • As text, 120.00 sorts before 45, because 1 comes before 4. After MODIFY ... DECIMAL(7,2), every value was converted (45 became 45.00) and the sort is numeric.
  • Now the column refuses text that is not a number: Rs 5 fails with error 1366. Had that value been stored before the change, the ALTER itself would have failed with the same error.

When adding a required column, give it a DEFAULT, or old rows silently get 0 or an empty text. 3. In MODIFY and CHANGE, write the full definition, including NOT NULL and DEFAULT, or they are dropped. 4. Before shrinking a column, make sure every value fits; otherwise the change fails with 1264 or 1265. 5. Before DROP COLUMN or RENAME, make sure no query or app still uses the old column.

Combine related changes in one ALTER TABLE separated by commas: the table is rebuilt once, and either all of them apply or none.

Mixed review: reading the error codes

An error code points straight at the cause, so learn to read the number first. The ones from this module:

  • 1064: a syntax mistake, such as a comma after the last column or a reserved word used as a name.
  • 1050 / 1051 / 1146: the table already exists / is unknown / does not exist.
  • 1264: a number out of range for its type; 1406: text too long.
  • 1265: a value outside an ENUM, or a value cut while shrinking a column.

And a few more:

  • 1292: an impossible or badly formatted date, or a TIMESTAMP after 2038.
  • 1366: a value that cannot be read as that type ('abc' as a number), or an emoji in a utf8mb3 column.
  • 1075: an AUTO_INCREMENT column that is not a key; 1091: dropping a column that does not exist.
  • 3730: dropping a table that another table points to.

Finish up

Mark complete & continue

Next: Mini project: college library tables