1. Home
SQL

SQL Tutorial: Learn Structured Query Language Basics

Learn all SQL tutorial concepts in detail and master your career today.

  • 59
  • 9 Hours
right-top-arrow

Tutorial Playlist

46 Lessons
18

SQL CREATE TABLE With Examples

Updated on 10/06/202481 Views

Introduction

In Relational database management systems (RDBMS), tables serve as the foundational structure for storing data. They are like organized containers where each column defines a specific type of data (known as a field), while each row holds the actual data (known as a record).

Structured Query Language (SQL) provides the tools to manage your database efficiently. One of the fundamental SQL statements managing and creating databases is the CREATE TABLE command or statement. It gives you the ability to set up your tables' structure in a database.

In this guide, we will thoroughly discuss the SQL CREATE TABLE statement. I will guide you through its syntax and functionality with practical examples.

Overview

SQL Create Table

Source: Freepik

In database management, one of the initial steps you'll encounter is creating tables to organize and store your data effectively. This is where the SQL CREATE TABLE statement comes into play.

Throughout this guide, I'll walk you through the SQL CREATE TABLE COMMAND usage. I will use practical examples to ensure you grasp its functionality with ease. By the end, you'll be equipped with the knowledge to confidently create tables.

What is the SQL CREATE TABLE Statement

The SQL CREATE TABLE statement is a powerful command that lets you create new tables within your database.

When you use the CREATE TABLE statement, you're essentially defining the blueprint of your table. You first specify the table's name, the columns it'll contain, and the data types each column can hold. You should note that each table in your database must have a unique name to avoid any confusion.

Here's a breakdown of the syntax (This is same syntax to CREATE TABLE in SQL Server):

CREATE TABLE table_name (

column1 datatype,

column2 datatype,

column3 datatype,

....

);

  • CREATE TABLE: This is the keyword that begins the statement and tells the database system that you want to create a new table.
  • table_name: This is the name that you decide to give your table. It must be unique within the database.
  • (column1 datatype, column2 datatype, ...): Within parentheses, you list the columns you want to include in your table. Each column is defined by its name followed by its data type. For example, column1 could be PersonID and its datatype could be INT, indicating it will hold integer values.
  • datatype: This specifies the type of data that the column can hold, such as INT for integers, VARCHAR for variable-length character strings, DATE for dates, etc.

For MySQL CREATE TABLE examples, you can also use the same syntax:

CREATE TABLE name_of_table (column1 the_datatype, column2 the_datatype, ...);

PostgreSQL CREATE TABLE syntax is also the same:

CREATE TABLE name_of_table (column1 the_datatype, column2 the_datatype, ...);.

To CREATE TABLE in SQLite database is also the same

Let’s look at an example to explain the SQL CREATE TABLE statement.

Suppose we want to create a table named "Products" to store information about various products in an inventory management system. Here's how we can use the CREATE TABLE statement:

CREATE TABLE Products (

ProductID INT PRIMARY KEY,

Name_of_Product VARCHAR(100),

Category VARCHAR(50),

Price DECIMAL(10, 2),

StockQuantity INT

);

In this example:

  • Products is the name of the table we're creating.
  • ProductID is a column that will store unique identifiers for each product. It's defined as an integer (INT) and marked as the primary key using the PRIMARY KEY constraint, ensuring each value is unique and serves as a unique identifier for each product.
  • Name_of_Product is a column to store the names of the products. It's defined as a variable-length character string (VARCHAR) with a maximum length of 100 characters.
  • Category is a column to store the category or type of each product. It's also defined as a VARCHAR with a maximum length of 50 characters.
  • Price is a column to store the price of each product. It's defined as a decimal number (DECIMAL(10, 2)), allowing up to 10 digits with 2 decimal places.
  • StockQuantity is a column to store the quantity of each product available in stock. It's defined as an integer (INT).

After executing this SQL statement, the database system will create a new table named "Products" with the specified columns and data types. So, we have this table

ProductID

Name_of_Product

Category

Price

StockQuantity

To insert data into the Products table, use the insert into command

INSERT INTO table_name (column1, column2, column3, ...)

VALUES (value1, value2, value3, ...);

So now we have; INSERT INTO Products (ProductID, Name_of_Product, Category, Price, StockQuantity)

VALUES

(1, 'Laptop', 'Electronics', 999.99, 10),

(2, 'Smartphone', 'Electronics', 699.99, 20),

(3, 'Headphones', 'Electronics', 99.99, 50),

(4, 'T-shirt', 'Apparel', 19.99, 100),

(5, 'Jeans', 'Apparel', 39.99, 75);

The new populated PRODUCTS table;

ProductID

Name_of_Product

Category

Price

StockQuantity

1

Laptop

Electronics

999.99

10

2

Smartphone

Electronics

699.99

20

3

Headphones

Electronics

99.99

50

4

T-shirt

Apparel

19.99

100

5

Jeans

Apparel

39.99

75

Using Different Data Types in CREATE TABLE Statement

When constructing your database tables, it's essential to consider the variety of data types available to accurately represent your information. Let's explore how you can integrate different data types within the CREATE TABLE statement to cater to diverse data requirements.

  • Integer: Integers are ideal for storing whole numbers. They're commonly used for identifiers, counts, or any numerical data that doesn't require decimal points.
  • Varchar: Varchar (Variable Character) is perfect for storing textual data of varying lengths. It's suitable for fields like names, addresses, or descriptions.
  • Date: Dates are essential for storing calendar dates. They're commonly used for timestamps, birthdays, or any temporal data.
  • Boolean: Booleans are perfect for representing true/false values. They're commonly used for flags, status indicators, or any binary data.
  • Decimal: Decimals are used for precise numeric values that require decimal points. They're suitable for storing monetary values, quantities with fractions, etc.
  • Text: Text data type is suitable for storing large amounts of text, such as long descriptions, articles, or any textual data that exceeds the capacity of Varchar.

Let's exemplify these data types using a single table:

CREATE TABLE Customers (

CustomerID INT,

FirstName VARCHAR(50),

LastName VARCHAR(50),

Email VARCHAR(100),

BirthDate DATE,

IsActive BOOLEAN,

TotalPurchases DECIMAL(10, 2),

Address TEXT

);

In this example:

  • CustomerID is an integer column serving as a unique identifier for each customer.
  • FirstName and LastName are varchar columns for storing the first and last names of customers.
  • Email is a varchar column that stores customers' email addresses.
  • BirthDate is a date column to store the birth date of customers.
  • IsActive is a boolean column indicating whether the customer's account is active or not.
  • TotalPurchases is a decimal column to store the total amount of purchases made by the customer with two decimal places for precision.
  • Address is a text column capable of holding large amounts of text, such as the customer's address.

Here's the table created:

CustomerID

FirstName

LastName

Email

BirthDate

IsActive

TotalPurchases

Address

Adding Constraints to Columns when using SQL CREATE TABLE statement

In database design, ensuring data integrity is important. Constraints play an important role in maintaining the quality and reliability of your data.

When creating tables using the SQL CREATE TABLE statement, you have the power to enforce various constraints on your columns. Let's explore some commonly used constraints:

  • Primary key: SQL CREATE TABLE primary key constraint uniquely identifies each record in a table. It ensures that no two rows can have the same value in the specified column(s). Typically, primary keys are used to uniquely identify each record in a table.
  • Foreign key: SQL CREATE TABLE foreign key establishes a relationship between two tables. It ensures referential integrity by enforcing that values in a column must match values in another table's primary key. This constraint is crucial for maintaining data consistency across related tables.
  • Unique: The unique constraint ensures that each value in the specified column(s) is unique within the table. Unlike the primary key constraint, multiple unique constraints can exist within a table, allowing for uniqueness across multiple columns.
  • Not null: A column can never have null values in it thanks to the not null constraint. It mandates that every record must have a value in the specified column, preventing the insertion of nulls.

Let's illustrate how these constraints are applied within the CREATE TABLE statement:

CREATE TABLE Employees (

EmployeeID INT PRIMARY KEY,

FirstName VARCHAR(50) NOT NULL,

LastName VARCHAR(50) NOT NULL,

DepartmentID INT,

CONSTRAINT fk_DepartmentID FOREIGN KEY (DepartmentID) REFERENCES

Departments(DepartmentID),

UNIQUE (FirstName, LastName)

);

In this example:

  • EmployeeID is specified as the primary key, ensuring each employee has a unique identifier.
  • FirstName and LastName columns are marked as not null, guaranteeing that every employee record includes these essential details.
  • DepartmentID column is defined as a foreign key, linking it to the DepartmentID column in the Departments table to maintain referential integrity.
  • The unique constraint on (FirstName, LastName) ensures that no two employees have the same first and last name combination.

Here is the Employee table we just created:

EmployeeID

FirstName

LastName

DepartmentID

Creating a Table From an Existing Table

When you're working with databases, there's often no need to reinvent the wheel. Instead of starting from scratch every time, you can leverage the structure and data of an existing table to create a new one effortlessly. This approach saves you time and ensures consistency across your database schema.

To accomplish this task, you can harness the power of SQL's CREATE TABLE and SELECT statements. By combining these commands, you can duplicate the structure and contents of an existing table into a fresh one.

The following is a basic syntax to create a table from another table:

CREATE TABLE NEW_TABLE_NAME AS

SELECT [column1, column2...columnN]

FROM EXISTING_TABLE_NAME

WHERE Condition;

In this syntax:

  • NEW_TABLE_NAME: This is the name you give to the new table that you're creating.
  • EXISTING_TABLE_NAME: This is the name of the table you're copying from.
  • column1, column2...: These are the fields from the existing table that you want to include in the new table.
  • Condition: This is an optional condition that specifies which rows from the existing table should be copied into the new table.

Now let’s look at an example;

Let's say you have an existing table called "CUSTOMERS" with fields like "ID" and "SALARY".

ID

NAME

AGE

SALARY

1

John

30

50000.00

2

Jane

28

60000.00

3

Michael

35

75000.00

4

Emily

32

55000.00

You want to create a new table called "SALARY" based on this existing table. Here's how you would do it:

CREATE TABLE SALARY_ABOVE_60000 AS

SELECT ID, NAME, SALARY

FROM CUSTOMERS

WHERE SALARY > 60000;

In this example, the "SALARY_ABOVE_60000" table is created by selecting the "ID", "NAME", and "SALARY" fields from the "CUSTOMERS" table but only for those rows where the "SALARY" is greater than $60,000.

After executing this SQL command, the "SALARY_ABOVE_60000" table will contain only the rows from the "CUSTOMERS" table where the salary is above $60,000.

Output Table (SALARY_ABOVE_60000):

ID

NAME

SALARY

3

Michael

75000.00

Best Practices and Tips For Using SQL CREATE

When harnessing the power of SQL's CREATE statement, adhering to best practices ensures smooth database management.

Descriptive Naming Conventions: Ensure descriptive yet concise naming conventions for tables and columns, facilitating easier understanding and maintenance. For example, instead of naming a column "Column1" or "Field1," opt for descriptive names like "ProductID" or "EmployeeName" to enhance readability and maintainability.

Data Integrity Constraints: Establish data integrity by defining appropriate constraints like primary and foreign keys, ensuring accuracy and consistency. In the example above for example, you should ensure each table has a primary key constraint to uniquely identify each row, preventing duplicate entries and ensuring data accuracy.

Performance Optimization: Consider performance optimization by minimizing redundant data and utilizing appropriate data types.

Documentation: Regularly document your database schema and changes made using comments, aiding future troubleshooting and collaboration.

Regular Review and Refinement: Regularly review and refine your table structures based on evolving business requirements to maintain efficiency and relevance.

Conclusion

The SQL CREATE TABLE statement stands as a foundational tool for structuring data. Throughout this guide, we've learned how to use it to create tables, add constraints to keep data safe, and even copy existing tables.

Remember to give tables and columns clear names. Also, keeping data in check with rules and making sure things run smoothly is key. Writing down what you do and checking back regularly can also help keep things organized.

With these tips and examples, you're now set to confidently create and manage tables in SQL. Just remember to keep things simple and organized as you go.

FAQs

  1. How do you CREATE TABLE in SQL?

To create a table in SQL, you use the CREATE TABLE statement followed by the table name and the columns you want to include.

  1. How to create a SQL table from SQL files?

You can create an SQL table from SQL files by writing the CREATE TABLE statement in the file and executing it using an SQL database management tool or command-line interface.

  1. How do you create columns in SQL?

Columns in SQL are created within a CREATE TABLE statement by specifying the column name and data type. For example: "column_name data_type".

  1. How to create a customer table in SQL?

To create a customer table in SQL, you would use the CREATE TABLE statement and define columns such as CustomerID, FirstName, LastName, etc., based on the information you want to store.

  1. How to create a SQL file?

You can create an SQL file using a text editor and save it with the ".sql" file extension. In this file, you can write SQL commands such as CREATE TABLE, INSERT INTO, etc.

  1. What are tables in SQL?

In SQL, tables are structures that store data in rows and columns. They act as containers for organizing and storing related information.

  1. How to create a query in SQL?

To create a query in SQL, you use the SELECT statement followed by the columns you want to retrieve data from and specify the table or tables you want to query.

  1. How to use SQL Server?

To use SQL Server, you first need to install and configure it on your computer or server. Once installed, you can connect to SQL Server using a client tool like SQL Server Management Studio (SSMS) and then execute SQL commands to manage databases, tables, and data.

Pavan vadapalli

Pavan Vadapalli

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working … Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...