MYSQL Tutorial



MySQL DEFAULT


MySQL DEFAULT Constraint

The DEFAULT constraint specifies a default value for a column when no value is provided. It helps ensure meaningful data and can simplify INSERT statements.

Syntax

column_name data_type DEFAULT default_value
  

Defining DEFAULT in CREATE TABLE

CREATE TABLE products (
  product_id   INT AUTO_INCREMENT PRIMARY KEY,
  name         VARCHAR(100) NOT NULL,
  price        DECIMAL(10,2) NOT NULL DEFAULT 0.00,
  in_stock     BOOLEAN         NOT NULL DEFAULT TRUE,
  created_at   TIMESTAMP       DEFAULT CURRENT_TIMESTAMP
);
  

Adding DEFAULT to an Existing Column

ALTER TABLE users
MODIFY COLUMN signup_date DATE NOT NULL DEFAULT '2025-01-01';
  

Removing a DEFAULT Constraint

ALTER TABLE products
ALTER COLUMN price DROP DEFAULT;
  
Tip: When adding a DEFAULT on an existing column, ensure any existing NULLs or missing values are handledβ€”use an UPDATE first if needed.

Common Use Cases

  • Numeric fields with logical defaults (e.g., quantity DEFAULT 0).
  • Boolean flags (e.g., is_active DEFAULT TRUE).
  • Timestamps with CURRENT_TIMESTAMP for automatic creation times.
  • Enum or status fields with a common default value.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review