To create a product table in SQL, you would use the CREATE TABLE
statement. This statement defines the table structure, including the columns, their data types, and any constraints (e.g., primary keys, not null, etc.).
Here is an example of how you might create a products
table:
CREATE TABLE products (
product_id INT PRIMARY KEY, -- Unique identifier for each product
product_name VARCHAR(255) NOT NULL, -- Product name, cannot be null
description TEXT, -- Description of the product
price DECIMAL(10, 2), -- Price of the product, up to 10 digits with 2 decimal places
quantity_in_stock INT, -- Quantity of the product in stock
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- Timestamp when the product is added
);
Explanation of each column:
- product_id: This is the primary key that uniquely identifies each product. It uses an
INT
data type, which stores integer values.PRIMARY KEY
ensures that each value in this column is unique. - product_name: This column stores the name of the product. It uses
VARCHAR(255)
to store variable-length strings up to 255 characters. TheNOT NULL
constraint ensures that every product must have a name. - description: A text column that provides a detailed description of the product. This is of type
TEXT
since descriptions can be long. - price: This column stores the price of the product, using the
DECIMAL
data type.DECIMAL(10, 2)
allows for 10 total digits, with 2 digits after the decimal point (for cents). - quantity_in_stock: This column stores the number of items available in stock for that product. It uses the
INT
data type to store integer values. - created_at: This is a timestamp column that stores the date and time when the product is added to the table. The
DEFAULT CURRENT_TIMESTAMP
sets the default value to the current date and time if not provided.
This is a basic product table structure. Depending on your needs, you may want to add more columns, such as category_id
(to link to a category table), supplier_id
(to link to a supplier table), or constraints like CHECK
for price values to ensure they are positive.
Let me know if you'd like more details or modifications!
No comments:
Post a Comment