start learning
Image 1
610

SQL Data Types and Constraints

In MySQL, data types define the type of data that a column can store, and constraints specify rules that limit the type of data that can be inserted into a column.

Here's an overview of common data types and constraints in MySQL :

Common Data Types

Numeric Types


CREATE TABLE example (
    age INT,
    salary DECIMAL(10,2)
);

String Types


CREATE TABLE example (
    name VARCHAR(50),
    description TEXT
);

Date and Time Types


CREATE TABLE example (
    birthdate DATE,
    last_login DATETIME
);

Boolean Type


CREATE TABLE example (
    is_active BOOLEAN
);

Common Constraints

PRIMARY KEY


CREATE TABLE example (
    id INT PRIMARY KEY,
    name VARCHAR(50)
);

AUTO_INCREMENT


CREATE TABLE example (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50)
);

UNIQUE


CREATE TABLE example (
    email VARCHAR(100) UNIQUE,
    username VARCHAR(50)
);

NOT NULL


CREATE TABLE example (
    username VARCHAR(50) NOT NULL,
    password VARCHAR(100) NOT NULL
);

CHECK


CREATE TABLE example (
    age INT CHECK (age >= 18),
    email VARCHAR(100)
);

FOREIGN KEY


CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    product_id INT,
    FOREIGN KEY (product_id) REFERENCES products(product_id)
);

These are some common data types and constraints in MySQL. The examples provided demonstrate how to use them when creating tables. Always refer to the official MySQL documentation for the most accurate and detailed information