SQL Create Table | DigitalOcean (2024)

When we have to store data in relational databases, the first part is to create the database. Next step is to create a table in the database that will store our data. In this tutorial, we will discuss how to create a table using SQL queries in MySQL and PostgreSQL databases.

I am not covering SQL Server create table examples, because they are similar to PostgreSQL queries.

SQL Create Table

In order to store data in a table, it is very important to understand the type of data that needs to be stored. Let us try to understand the syntax for creating a table.

SQL Create Table Syntax

CREATE TABLE table_name( column1 datatype, column2 datatype,... column-N datatype, PRIMARY KEY(one or more column) );
  • CREATE TABLE is the keyword to tell the database to create a table.
  • table_name is the unique name that is used for the table.
  • The brackets that are next to the table name contains the list of columns.
  • The list contains the column name and the data type that can be stored in the respective columns.
  • PRIMARY KEY is used to specify the columns to be used for primary key.

SQL Create Table with one column Primary Key

When we create a table, we have to provide the primary key information along with the column structure. Let’s look at some example to create a table with a single column as the primary key.

MySQL

CREATE TABLE `test`.`student` (`studentId` INT NOT NULL,`studentName` VARCHAR(45) NULL,`State` VARCHAR(45) NULL,`Country` VARCHAR(45) NULL,PRIMARY KEY (`studentId`),UNIQUE INDEX `studentId_UNIQUE` (`studentId` ASC) VISIBLE);

Above query will create a new table “Student” with the primary key column as “studentId”. Notice that every column name has a data type defined. For example, we can store only INT data in the studentId column whereas we can store VARCHAR data in the studentName column. VARCHAR(45) means that the maximum size of the string data allowed is 45 characters. Since the primary key can’t be null, we specify it in the studentId column definition.

SQL Create Table | DigitalOcean (1)

PostgreSQL

We can create a table in PostgreSQL database using the following query.

CREATE TABLE "test.student"("StudentId" integer NOT NULL,"StudentName" character varying(45),"State" character varying(45),"Country" character varying(45),PRIMARY KEY ("StudentId"));
SQL Create Table | DigitalOcean (2)

SQL Create Table with Multiple Primary Keys

Let’s look at another example where we will use multiple columns in the primary key.

MySQL

CREATE TABLE `test`.`customer` ( `CustomerId` INT NOT NULL, `CustomerName` VARCHAR(45) NULL, `ProductId` VARCHAR(45) NOT NULL, `State` VARCHAR(45) NULL,PRIMARY KEY (`CustomerId`, `ProductId`),UNIQUE INDEX `CustomrId_UNIQUE` (`CustomerId` ASC) VISIBLE);

Above query will create “customer” table in the “test” database schema. The primary key of this table is the combination of CustomerId and ProductId.

SQL Create Table | DigitalOcean (3)

PostgreSQL

CREATE TABLE "test.customer"("CustomerId" integer NOT NULL,"CustomerName" character varying(45),"ProductId" character varying(45),"Country" character varying(45),PRIMARY KEY ("CustomerId","ProductId"));
SQL Create Table | DigitalOcean (4)

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

SQL Create Table | DigitalOcean (2024)

FAQs

How do you create a table in SQL? ›

SQL CREATE TABLE Statement
  1. CREATE TABLE table_name ( column1 datatype, column2 datatype, ...
  2. ExampleGet your own SQL Server. CREATE TABLE Persons ( PersonID int, ...
  3. CREATE TABLE new_table_name AS. SELECT column1, column2,... FROM existing_table_name. ...
  4. Example. CREATE TABLE TestTable AS. SELECT customername, contactname.

How do you create a table as SELECT * from MySQL? ›

You can create one table from another by adding a SELECT statement at the end of the CREATE TABLE statement: CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl; MySQL creates new columns for all elements in the SELECT .

How to create a SQL query? ›

How to Create a SQL Statement
  1. Start your query with the select statement. select [all | distinct] ...
  2. Add field names you want to display. field1 [,field2, 3, 4, etc.] ...
  3. Add your statement clause(s) or selection criteria. Required: ...
  4. Review your select statement. Here's a sample statement:
Oct 13, 2022

How to create a table function in SQL? ›

Creating SQL table functions
  1. Define the CREATE FUNCTION (table) statement: Specify a name for the function. Specify a name and data type for each input parameter. Specify the routine attributes. Specify the RETURNS TABLE keyword. ...
  2. Execute the CREATE FUNCTION (table) statement from a supported interface.

How to create a table using like in MySQL? ›

Use CREATE TABLE ... LIKE to create an empty table based on the definition of another table, including any column attributes and indexes defined in the original table: CREATE TABLE new_tbl LIKE orig_tbl; The copy is created using the same version of the table storage format as the original table.

How to insert data in a table in MySQL? ›

MySQL INSERT INTO – General Syntax

INSERT INTO table_name(column_1,column_2,column_3) VALUES (value_1,value_2,value_3); In the INSERT INTO query, you should specify the following information: table_name : A MySQL table to which you want to add a new row.

How do you create a table in MySQL database? ›

mysql> CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE); VARCHAR is a good choice for the name , owner , and species columns because the column values vary in length. The lengths in those column definitions need not all be the same, and need not be 20 .

How do I add a table to a database? ›

In SSMS, in Object Explorer, connect to the instance of Database Engine that contains the database to be modified. In Object Explorer, expand the Databases node and then expand the database that will contain the new table. In Object Explorer, right-click the Tables node of your database and then select New Table.

How many ways to create a table in MySQL? ›

MySQL provides multiple methods for creating tables. The two primary methods include using the Command Line Interface(CLI) and the Graphical User Interface(GUI) provided by MySQL Workbench.

How to create a table from select in MySQL? ›

You can create one table from another by adding a SELECT statement at the end of the CREATE TABLE statement: CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl ; MySQL creates new columns for all elements in the SELECT .

How to create a table in SQL command line? ›

Create Table: The general syntax for creating a table is: CREATE TABLE table_name (column1 datatype, column2 datatype, ...); For example, to create a table named Students , enter the following command: CREATE TABLE Students (StudentId int, StudentName nvarchar(50), StudentAge int);

What is the create command in SQL? ›

SQL CREATE command is a type of DDL Command and is among the commands which is primarily used for creating databases and tables. The CREATE command has a particular syntax which needs to be followed In order to create databases or tables with desired structure.

What is the structure of a table in SQL? ›

SQL Table Structure: Components include columns, data types, constraints, primary and foreign keys, indexes, and performance optimisation. SQL Table Types: Common types include temporary tables, system tables, and partitioned tables, each serving different functions for efficient data storage and management.

How do I create a table with many columns in SQL? ›

To add several columns to a table in SQL Server, you can modify the standard command syntax in the following way: ALTER TABLE table_name ADD column_name1 data_type1, ADD column_name2 data_type2, ADD column_nameN data_typeN; You can add as many columns to a table as needed, and specify different data types for them all.

How to create a table for an employee in SQL? ›

Let's see the command to create a table in MySQL database.
  1. CREATE TABLE Employee.
  2. (
  3. EmployeeID int,
  4. FirstName varchar(255),
  5. LastName varchar(255),
  6. Email varchar(255),
  7. AddressLine varchar(255),
  8. City varchar(255)

Top Articles
What is the Gig Economy? - Definition from WhatIs.com
BRICS Making Good Progress On Their Golden Path
No Hard Feelings Showtimes Near Metropolitan Fiesta 5 Theatre
Victor Spizzirri Linkedin
Uca Cheerleading Nationals 2023
Time in Baltimore, Maryland, United States now
Housing near Juneau, WI - craigslist
Craigslist Motorcycles Jacksonville Florida
Top Golf 3000 Clubs
Nj Scratch Off Remaining Prizes
Most McDonald's by Country 2024
Kris Carolla Obituary
Alexandria Van Starrenburg
Craiglist Tulsa Ok
Po Box 35691 Canton Oh
Sonic Fan Games Hq
Dark Chocolate Cherry Vegan Cinnamon Rolls
Kamzz Llc
Healthier Homes | Coronavirus Protocol | Stanley Steemer - Stanley Steemer | The Steem Team
Gayla Glenn Harris County Texas Update
*Price Lowered! This weekend ONLY* 2006 VTX1300R, windshield & hard bags, low mi - motorcycles/scooters - by owner -...
Village
Why Are Fuel Leaks A Problem Aceable
Arrest Gif
Dal Tadka Recipe - Punjabi Dhaba Style
2023 Ford Bronco Raptor for sale - Dallas, TX - craigslist
Craigslist Brandon Vt
5 Star Rated Nail Salons Near Me
Does Circle K Sell Elf Bars
Sports Clips Flowood Ms
How to Get Into UCLA: Admissions Stats + Tips
Weekly Math Review Q4 3
Craigslist Car For Sale By Owner
Weapons Storehouse Nyt Crossword
Ksu Sturgis Library
Pp503063
Publictributes
Atlanta Musicians Craigslist
How Does The Common App Work? A Guide To The Common App
Best Restaurants Minocqua
Nail Salon Open On Monday Near Me
Vindy.com Obituaries
Anthem Bcbs Otc Catalog 2022
Best Haircut Shop Near Me
John Wick: Kapitel 4 (2023)
Wisconsin Volleyball titt*es
Craigslist Marshfield Mo
Madden 23 Can't Hire Offensive Coordinator
What Time Do Papa John's Pizza Close
Cbs Scores Mlb
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 5668

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.