w3resource

A Complete Guide to Creating Tables in SQLite3


Creating Tables in SQLite3

The CREATE TABLE statement in SQLite3 is used to define a new table in a database. A table consists of columns and rows, where each column has a specific data type and constraints. This command allows you to specify column names, data types, primary keys, foreign keys, and other constraints. Proper table creation is foundational for efficient data storage and retrieval.


Syntax:

CREATE TABLE table_name (
    column1_name data_type constraints,
    column2_name data_type constraints,
    ...
    columnN_name data_type constraints
);
  • table_name: Name of the table to be created.
  • column_name: Name of the column.
  • data_type: Data type of the column (e.g., INTEGER, TEXT, REAL, BLOB).
  • constraints: Optional rules applied to the column (e.g., PRIMARY KEY, NOT NULL, UNIQUE).

Examples:

1. Creating a Simple Table

Code:

-- Create a table named employees
CREATE TABLE employees (
    id INTEGER PRIMARY KEY, -- Unique identifier for each employee
    name TEXT NOT NULL,     -- Name of the employee (cannot be NULL)
    age INTEGER,            -- Age of the employee
    department TEXT         -- Department where the employee works
);

Explanation:

  • The id column is a primary key and must contain unique values.
  • The name column is mandatory (NOT NULL).
  • The age column can store numeric data.
  • The department column stores text values.

2. Creating a Table with Default Values and Constraints

Code:

-- Create a table for tasks with default values
CREATE TABLE tasks (
    task_id INTEGER PRIMARY KEY,       -- Unique task ID
    description TEXT NOT NULL,         -- Description of the task
    priority INTEGER DEFAULT 1,        -- Default priority (1 if not specified)
    due_date TEXT,                     -- Due date for the task
    is_completed INTEGER DEFAULT 0     -- Boolean-like column (0: FALSE, 1: TRUE)
);

Explanation:

  • The priority column has a default value of 1.
  • The is_completed column defaults to 0 (not completed).
  • The NOT NULL constraint ensures the description column is mandatory.

3. Creating a Table with Foreign Keys

Code:

-- Create a table with a foreign key relationship
CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,     -- Unique order ID
    customer_id INTEGER NOT NULL,     -- ID of the customer placing the order
    order_date TEXT,                  -- Date of the order
    FOREIGN KEY (customer_id)         -- Establish relationship
    REFERENCES customers(customer_id) -- Links to the customers table
);

Explanation:

  • The customer_id column establishes a relationship with the customers table.
  • The FOREIGN KEY constraint ensures data consistency between tables.

4. Using the IF NOT EXISTS Clause

Code:

-- Create a table only if it does not already exist
CREATE TABLE IF NOT EXISTS inventory (
    product_id INTEGER PRIMARY KEY, -- Unique product ID
    product_name TEXT NOT NULL,    -- Name of the product
    quantity INTEGER DEFAULT 0     -- Quantity of the product (defaults to 0)
);

Explanation:

  • The IF NOT EXISTS clause prevents errors if the table already exists.
  • The quantity column defaults to 0 when no value is provided.

Best Practices for Table Creation

    1. Choose Descriptive Names: Use meaningful names for tables and columns to enhance readability.

    2. Use Constraints Wisely: Apply constraints like PRIMARY KEY, NOT NULL, and UNIQUE to ensure data integrity.

    3. Plan Relationships: Define foreign keys for related tables to maintain data consistency.

    4. Default Values: Use default values to reduce the need for explicit data during insertion.

    5. Indexes: Add indexes for frequently queried columns to improve performance (e.g., CREATE INDEX).


Key Points to Remember

  • Use the IF NOT EXISTS clause to avoid errors during table creation.
  • Define primary and foreign keys for better data relationships.
  • Choose appropriate data types and constraints for each column.
  • Plan the table structure based on your application’s requirements.

Conclusion

The CREATE TABLE statement in SQLite3 is a powerful tool for defining the structure of your database. By carefully planning your table schema, you can ensure efficient data storage, retrieval, and integrity. Whether working with simple or complex databases, understanding table creation in SQLite3 is essential for any developer.

Practical Guides to SQLite Snippets and Examples.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/sqlite/snippets/sqlite3-create-table.php