ADVERTISEMENT

SQL NOT NULL / DEFAULT

NOT NULL ensures a column must have a value — it cannot be left empty (NULL).
DEFAULT sets a value automatically if no explicit value is provided during insert.

🔹 Basic Syntax

-- NOT NULL constraint
column_name data_type NOT NULL;

-- DEFAULT value assignment
column_name data_type DEFAULT default_value;

🔹 Example

CREATE TABLE employees (
  id INT PRIMARY KEY,
  first_name VARCHAR(50) NOT NULL,          -- must have a value
  last_name VARCHAR(50) NOT NULL,
  department VARCHAR(100) DEFAULT 'Sales'  -- default is 'Sales' if not specified
);

-- Insert with explicit department
INSERT INTO employees (id, first_name, last_name, department)
VALUES (1, 'John', 'Doe', 'HR');

-- Insert without department uses default
INSERT INTO employees (id, first_name, last_name)
VALUES (2, 'Jane', 'Smith');

-- Query to verify
SELECT * FROM employees;

🔹 Important Notes

  • NOT NULL columns reject any attempts to insert or update with NULL.
  • DEFAULT values help maintain consistent data and avoid NULLs.
  • You can combine both on a column to make it mandatory but still provide a fallback value.
  • Not all data types support DEFAULT in every DBMS (check your system docs).

🧠 Quick Recap

Key PointExplanation
NOT NULLColumn must have a value, no NULL allowed
DEFAULTAssigns default value if none provided
Use caseMandatory fields, ensure data consistency
Syntax examplecolumn datatype NOT NULL DEFAULT value

💡 Use NOT NULL and DEFAULT wisely to enforce data integrity and reduce errors during inserts.

ADVERTISEMENT