Data Types, NULL, and Column Constraints

Choose common column types and make the database reject invalid data

🎯 Introduction

By the end of this article, you will be able to choose common column types and make the database reject data that violates your rules.


🔢 Choose types based on the data

A type determines what a column can store and how the database compares and calculates its values:

DataCommon typeExamples and considerations
User IDs, countsINT1, 20; consider BIGINT if the range is insufficient
Exact decimal valuesDECIMAL(8,2)1234.50; 8 digits in total, including 2 decimal places
Names, citiesVARCHAR(50)Variable length, up to 50 characters
Article bodyTEXTLonger text; names do not need to use TEXT as well
DateDATE2026-10-01, without a time component
Date and timeDATETIME2026-10-01 09:00:00
ToggleTINYINTUse 0 and 1, with a constraint to restrict the range

Do not substitute FLOAT for DECIMAL when decimal values must be stored exactly. Phone numbers and codes with leading zeros are text; being composed of digits does not make them integers.


🕒 Temporal types and time zones

DATETIME stores the date and time you supply without automatic conversion based on the connection's time zone. It suits business timestamps when you agree on a shared time zone. TIMESTAMP converts between the connection's time zone and UTC (Coordinated Universal Time), including on retrieval, so connection settings must be consistent.

Check the current connection's time zone:

SELECT @@session.time_zone;

If you have not changed the connection's time zone, a common result is shown below. Refer to the actual value if your server uses a different configuration:

@@session.time_zone
SYSTEM

SYSTEM means the connection follows the server's time zone. An offset such as +08:00 may also be returned. To use UTC consistently, configure every relevant connection:

SET time_zone = '+00:00';

This affects only the current connection. Setting it once in an administration tool does not change your application's connection pool. With DATETIME, the application must still generate timestamps according to your convention; the column itself carries no time zone information.


🛡 Reject invalid data with constraints

Create a separate practice table in blog_demo:

CREATE TABLE profile (
    id INT PRIMARY KEY AUTO_INCREMENT,
    email VARCHAR(100) NOT NULL UNIQUE,
    nickname VARCHAR(50) NOT NULL,
    enabled TINYINT NOT NULL DEFAULT 1,
    CONSTRAINT chk_profile_enabled CHECK (enabled IN (0, 1))
);

UNIQUE prevents two records from sharing an email address; CHECK restricts enabled to 0 or 1. DEFAULT specifies the value used when a column is omitted and does not replace validation.

First, insert a valid record:

INSERT INTO profile (email, nickname) VALUES ('ming@example.com', 'Xiao Ming');

enabled defaults to 1. Run the same insertion separately again: it produces a duplicate key error, and the table still contains only one record with that email address.

Try writing an invalid toggle value:

UPDATE profile SET enabled = 2 WHERE email = 'ming@example.com';

MySQL 8.4 rejects the update, leaving enabled at 1. The application can provide a helpful message beforehand, while database constraints reject invalid writes that bypass the application.


🕳 NOT NULL does not check for empty text

NOT NULL prohibits NULL, but it allows empty strings. A required nickname also needs a rule preventing it from being empty after leading and trailing spaces are removed:

ALTER TABLE profile ADD CONSTRAINT chk_profile_nickname
    CHECK (CHAR_LENGTH(TRIM(nickname)) > 0);

TRIM removes leading and trailing spaces, and CHAR_LENGTH counts characters. Empty nicknames and nicknames containing only spaces are now rejected. ALTER TABLE changes an existing table's structure; here, it adds just one check constraint.

Existing invalid data can prevent a constraint from being added. Query and correct that data first rather than disabling checks. A nullable UNIQUE column can contain multiple NULL values. If every record needs an email address, also use NOT NULL, as in this example.


🔤 What character sets and collations affect

A character set determines how text is stored; a collation determines how text is compared, including whether A and a are considered equal. Inspect the practice table's configuration:

SHOW FULL COLUMNS FROM profile;

The key columns for this article's table definition are shown below. The Collation of text columns depends on the collation actually inherited from the database:

FieldTypeNullKeyDefault
idintNOPRINULL
emailvarchar(100)NOUNINULL
nicknamevarchar(50)NONULL
enabledtinyintNO1

Only some output columns are included here. PRI denotes a primary key, and UNI a unique index. A displayed default of NULL alone does not tell you whether a required column can be omitted: also consider NOT NULL, default expressions, and auto-increment settings.

Inspect the Collation column for email. The commonly used utf8mb4_0900_ai_ci collation in 8.4 is case-insensitive and accent-insensitive; uniqueness checks for email use these same comparison rules. Case-sensitive external identifiers need a collation suited to the application's requirements; checking only that the type is VARCHAR is insufficient.


❓ Questions and Answers

Q1: Does TINYINT(1) automatically restrict values to 0 and 1?

No. The parenthesized notation does not validate Boolean values. Use a CHECK constraint.

Q2: Can I convert a BIGINT returned to JavaScript directly to Number?

Values outside the safe integer range lose precision. The driver can return a string, and the application should preserve the exact value.

Q3: When should I use a JSON column?

Use it for additional attributes whose structure varies. Prefer explicit columns for core data that is frequently filtered, joined, or requires validation.


🧪 Exercise

Insert a profile with enabled set to 0. Then try a duplicate email address and an empty nickname separately, and record why each operation succeeds or fails.

-- Write your SQL or record your verification results here