SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL GROUP BY SQL Having SQL In SQL INSERT INTO SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL ORDER BY SQL Select SQL Select Into SQL Top Limit Fetch SQL Stored Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL Backup Database SQL Check SQL Constraints SQL Create View SQL Create Database SQL Create Table SQL Data types SQL Dates SQL Default Constraint SQL Drop Database SQL Drop Table SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL Default Constraint

Example Table

We will create a table named employees to demonstrate the SQL default constraint:


    CREATE TABLE employees (
        employee_id INT PRIMARY KEY,
        employee_name VARCHAR(100),
        hire_date DATE DEFAULT CURRENT_DATE,
        salary DECIMAL(10, 2) DEFAULT 50000.00
    );
    

Creating the Table

To create the table, use the following SQL command:


    CREATE TABLE employees (
        employee_id INT PRIMARY KEY,
        employee_name VARCHAR(100),
        hire_date DATE DEFAULT CURRENT_DATE,
        salary DECIMAL(10, 2) DEFAULT 50000.00
    );
    

Result:

Command CREATE TABLE employees (employee_id INT PRIMARY KEY, employee_name VARCHAR(100), hire_date DATE DEFAULT CURRENT_DATE, salary DECIMAL(10, 2) DEFAULT 50000.00);
Result
  • A table named employees is created with default values for hire_date and salary.

Inserting Data into the Table

Let's insert some data into the employees table:


    INSERT INTO employees (employee_id, employee_name) VALUES
    (1, 'John Doe'),
    (2, 'Jane Smith'),
    (3, 'Alice Johnson');
    

Result:

Command INSERT INTO employees (employee_id, employee_name) VALUES (1, 'John Doe'), (2, 'Jane Smith'), (3, 'Alice Johnson');
Result
  • Three records are inserted into the employees table with default values for hire_date and salary.

Querying the Table

We can query the employees table to see the data:


    SELECT * FROM employees;
    

Result:

Command SELECT * FROM employees;
Result
employee_id employee_name hire_date salary
1 John Doe 2023-10-01 50000.00
2 Jane Smith 2023-10-01 50000.00
3 Alice Johnson 2023-10-01 50000.00