SQL Create Table
As we all know, SQL uses Tables to store and Manage Data. Table in Sql Server is a
combination of Rows and Columns. In order to create table, we have to use SQL
Create Table Statement. The syntax for SQL Server create table is
-- SQL Server Create Table Syntax
CREATE TABLE [Table Name]
Column_Name1 Data_Type(Size) [NULL | NOT NULL],
Column_Name2 Data_Type(Size) [NULL | NOT NULL],
Column_NameN Data_Type(Size) [NULL | NOT NULL]
);
Sql Server create table syntax items
Table Name: If you write the already existing table name, it will throw an error
Column_Name: Unique Column Names required for this table
Data Type: A valid Data type that the column will hold. For example, Int, Money,
Varchar, Nvarchar and Date
Size: Data types like Varchar, nvarchar, Char expects the size So, Please provide
valid number here
NULL or NOT NULL: If you select the NULL option then column will accept both
normal values and NULL values. Otherwise, it will throw an error saying Column
should not be empty
SQL Create Table Example
We create a new table in SQL Server called Customer inside the [SQL Tutorial]
Database
-- SQL Server Create Table Example
CREATE TABLE [Customer]
[CustomerKey] [int] NOT NULL,
[Name] [varchar](150) NULL,
[DateOfBirth] [date] NULL,
[EmailAddress] [nvarchar](50) NULL,
[Profession] [nvarchar](100) NULL
GO
The command is executed successfully and you can see the Newly created table in
Sql Server object explorer.
Messages
-------
Command(s) completed successfully.
From the above Sql Server Create Table code you can observe that We declared 5
Columns:
Our first column is CustomerKey of Integer data type and it will not allow NULL
values.
Name column belongs to Varchar data type and it allows NULL values. We also
assigned the size to 150, it means both the columns will accept up to 150 characters
The third column is DateOfBirth of Date data type and allows NULLs. This will allow
us to enter Date values only
EmailAddress and Profession columns belong to NVarchar data type and it will allow
NULL values.
NOTE: Before you start creating a table in SQL Server, It is always advisable
to check if a Table exists or not.
Let me show you the newly created table in Sql Server Object Explorer. Please
expand the Columns folder to see the available columns
TIP: If you didn’t find the newly created table, Please click on the refresh button in
object explorer
Create Table with Identity Column
In this example, we create a table with identity column in Sql Server. For this, we
defined the Customer Key column as an Identity column. This will auto-generate
numbers starting with 1 and incremented by 1. (This is optional If you want You can
remove IDENTITY (1, 1) portion completely)
-- SQL Server Create Table Example
CREATE TABLE [Customer11]
[CustomerKey] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[BirthDate] [date] NULL,
[EmailAddress] [nvarchar](50) NULL,
[Yearly Income] [money] NULL,
[Profession] [nvarchar](100) NULL
GO
Messages
-------
Command(s) completed successfully.
See the newly created table
SQL Create Table with Primary Key
How to create Table in Sql Server with Primary Key column. We just added the
PRIMARY KEY word to the Customer key. This will create a primary key on
Customer key column.
-- SQL Server Create Table Example
CREATE TABLE [Customer111]
[ID] [int] IDENTITY(1,1) NOT NULL,
[CustomerKey] [int] NOT NULL PRIMARY KEY,
[FirstName] [varchar](50) NOT NULL ,
[LastName] [varchar](50) NULL,
[BirthDate] [date] NULL,
[EmailAddress] [nvarchar](50) NULL,
[Yearly Income] [money] NULL,
[Profession] [nvarchar](100) NULL
GO
Create Table with All Constraints
How to create Table in Sql Server with Identity Column, Primary Key column, Unique
Key, and Check Constraint?. I suggest you refer to Primary Key, Unique Key, Default
Constraint, and Check Constraint articles. As you can see,
The last Name will accept Unique values.
If the user doesn’t provide a value to the Profession column then SQL writes
Software Developer as the default value
Check constraint check whether the Age value is between 0 and 100
-- SQL Server Create Table Example
CREATE TABLE [Customer11111]
[ID] [int] IDENTITY(1,1) NOT NULL,
[CustomerKey] [int] NOT NULL PRIMARY KEY,
[FirstName] [varchar](50) NOT NULL ,
[LastName] [varchar](50) NOT NULL UNIQUE,
[Age] [int] NULL,
[EmailAddress] [nvarchar](50) NULL,
[Yearly Income] [money] NULL,
[Profession] [nvarchar](100) NOT NULL DEFAULT ('Software
Developer'),
CONSTRAINT CK_Customer11111_Age CHECK([Age] > 0 AND [Age] <=
100)
GO
Messages
-------
Command(s) completed successfully.
If you expand the table definition in the Object Explorer, you can see all these
constraints
Sql Create Table from Another Table
It provides Select into Statement to create a table using an existing table along with
data (if any).. Data that we are going to use
Below query creates new table Customer1111111 using Employee table definition,
and insert all the records present in the Employee
-- SQL Server Create Table Example
SELECT [EmpID], [FirstName], [LastName], [Education]
,[Occupation], [YearlyIncome], [Sales], [HireDate]
INTO [SQL Tutorial].[dbo].[Customer1111111]
FROM [SQL Tutorial].[dbo].[Employee]
Messages
-------
(14 row(s) affected)
Data inside this table
SELECT [EmpID], [FirstName], [LastName], [Education]
,[Occupation], [YearlyIncome], [Sales], [HireDate]
FROM [SQL Tutorial].[dbo].[Customer1111111]
Create Table in Management Studio
In order to Create a Table, within the Management Studio object explorer, Expand
the Database folder in which you want to create table in Sql Server. Please select
the Tables folder and Right click on it will open the context menu. Select the New
option and then select the Table.. option to create Table in Sql Server.
Once you select the Table.. option, the following window will be opened to type the
Column Name, Data Type and Checkbox to decide whether the column allows NULL
values or Not. As you see, we added 7 columns of different data types.
Add Identity Column using Management Studio
Let me show you, how to add an identity column to already created table using
Management Studio. First, select the column and Go to the Column Properties tab.
Please change the IsIdentity option from default No to Yes in Identity Specification
property.
Once you finish creating a table, Please click on the save button and rename the
table name.
Click OK to finish saving. Write the following Select statement to check whether the
table holds all the column names or not.
TIP: You can use the INSERT Statement, or insert into to insert data into this newly
created table.
Create Local and Global Temp Table
Here, we create local and global temporary tables or temp tables in Sql Server.
Please refer Temp Tables article.
-- SQL Create Local Temp Table
CREATE TABLE #LocalTemp
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](255) NULL,
[Occupation] [nvarchar](255) NULL,
[Sales] [float] NULL
GO
-- SQL Create Global Temp Table
CREATE TABLE ##GlobalTemp
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](255) NULL,
[Occupation] [nvarchar](255) NULL,
[YearlyIncome] [float] NULL,
[Sales] [float] NULL
GO
Filed Under: SQL
SQL Alter Table
The SQL Server Alter Table Statement is used to alter Tables. The Alter
Table includes Add New Columns, Modifying existing Columns, Deleting existing
Column, Add or Removing Indexes, Dropping and adding Constraints like Primary
Keys to the existing table.
SQL Alter Table examples
The following are some of the examples of Alter Table to add, modify and delete
columns and constraints. Let us see how to use the SQL Alter Table statement to
alter the table definition with a live example. For this SQL Query, We use the
Customer table.
SQL Alter Table Add New Column
To add a new column to the existing table, please use the following syntax
-- SQL Alter table Add New Column
ALTER TABLE [Table_Name]
ADD [New_Column_Name] Data_Type (Length) NULL | NOT NULL
We are going to add the Education Column to the existing table customers
-- SQL Alter table Add New Column
ALTER TABLE [Customer]
ADD Education VARCHAR (50) NULL
From the above code SQL Server snippet, the Education Column belongs to varchar
data type, the data length is 50, and it will allow NULL Values.
Alter Table Delete Column
To delete or drop the existing column from the SQL table, Please use the following
syntax
-- SQL Alter table Drop Column
ALTER TABLE [Table_Name]
DROP COLUMN [Column_Name]
We will delete the existing column called Profession from the customer table.
-- SQL Alter table Delete Column
ALTER TABLE [Customer]
DROP COLUMN Profession
SQL Alter Table Change Column Data Type
To changer modify the existing columns Data Type in a table, use the following
syntax
-- SQL Server Alter table change Column data type
ALTER TABLE [Table_Name]
ALTER COLUMN [Column_Name] Data_Type NULL |NOT NULL
Here, we change the Education column data type from Varchar to Nvarchar and
length from 50 to 75
-- SQL Server Alter table change data type
ALTER TABLE [Customer]
ALTER COLUMN Education NVARCHAR(75)
To alter the NULL functionality to restrict the NULL or allow NULLS, use the following
code.
-- SQL Server Alter table change Column data type
ALTER TABLE [Customer]
ALTER COLUMN Education NVARCHAR(75) NOT NULL
We successfully changed the data type, length, and NULL handling of the existing
column present in the SQL Table.
Alter Table Add primary key
To add Primary key and a foreign key to existing columns, please use the following
SQL Server alter table add constraint syntax
-- SQL Alter Table Add primary key
ALTER TABLE [Customer]
ADD CONSTRAINT [Constraint_Name] PRIMARY KEY ([Column_Name])
Add a Primary Key constraint to the Customer Key Column
-- SQL Alter Table Add primary key
ALTER TABLE [Customer]
ADD CONSTRAINT PrimaryKey PRIMARY KEY ( [CustomerKey] )
Alter Table Drop Constraint
To delete or Drop primary keys and foreign key on existing columns, use the Alter
Table Drop constraint syntax
-- SQL Server ALTER Table Drop Constraint
ALTER TABLE [Customer]
DROP CONSTRAINT [Constraint_Name]
Delete the previously created Primary Key constraint on the Customer Key Column.
-- SQL Server ALTER Table Drop Constraint ALTER TABLE
[Customer] DROP CONSTRAINT PrimaryKey
Filed Under: SQL
SQL Rename Table
How to Rename Table in SQL Server with an example?. To demonstrate the
Rename Table name, we use the below-shown Customer table.
SQL Rename Table Name Example
There is a stored procedure called SP_RENAME to rename the table name. In this
example, we will rename the Customer table using this sp. The syntax to rename
table name using sp_rename
-- Syntax for SQL Server rename table Name is:
SP_RENAME '[Old Table Name]', '[New Table Name]'
We use the above sp_rename syntax to rename the Customers table to
NewCustomers
Rename Table using SSMS
If you can access Management Studio, double-click on the SQL Server Table allows
you to change the table name. Let me change the table name to CustomersTable
Rename Table Name Approach 2
To rename a table in SQL Server, within the Object Explorer, Go to the Database
where the table exists. Next, Right-click on the Table, and select the Rename from
the context menu.
We are changing the table name to Customers and you can see the new table name.
Filed Under: SQL
Get Table Names from SQL Server Database
In this article, we will show you how to write a SQL query to Get Table Names from
SQL Server Database with examples.
Get Table Names from SQL Server Database
Example 1
For this get list of table names in Sql Server database demonstration, we are using
the AdventureWorks DW database. In this SQL example query, we will show you
how to Get List of Table names in a database.
-- Query to Get SQL Server Database Table Names
USE [AdventureWorksDW2014]
GO
SELECT *
FROM INFORMATION_SCHEMA.TABLES
You can also use Where clause along with information_schema tables to restrict the
list of table names in SQL Server.
-- Query to Get SQL Server Database Table Names
USE [AdventureWorksDW2014]
GO
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Get Table Names in a Database Example 2
In this example, we are using the sys.objects table to find a list of table names in
SQL Server.
-- Query to Get SQL Server Database Table Names
USE [AdventureWorksDW2014]
GO
SELECT name, create_date, modify_date FROM sys.objects
WHERE type_desc = 'USER_TABLE'
-- WHERE type = 'U'
We are using the sys.tables table to find the list of table names.
-- Query to Get SQL Server Database Table Names
USE [AdventureWorksDW2014]
GO
SELECT * FROM sys.tables
You can also select the required columns from the sys.tables using the below-shown
query. By this, you can see the required columns, such as Table Name, Created
Date, and Table Modified Date, etc.
-- Query to Get SQL Server Database Table Names
USE [AdventureWorksDW2014]
GO
SELECT name, create_date, modify_date FROM sys.tables
Filed Under: SQL
SQL Add Column
In SQL Add Column is used to add a new column to the existing table. For this Sql
Server alter table add column demonstration, we use the Customer table.
SQL Add Column example
To add a new column to the existing table, please use the following Alter table Add
Column syntax.
-- SQL Server Add Column
ALTER TABLE [Table_Name]
ADD [New_Column] Data_Type (Length) NULL | NOT NULL
Let me add Sales Column that allows Nulls to an existing Customers table
-- SQl Server Add Column Example
USE [NewNameDB]
GO
ALTER TABLE Customers
ADD Sales MONEY NULL
Messages
-------
Commands completed successfully.
In the above Server code, we added Sales Column of Money data type, and it will
allow NULL Values. You can see the new column
Add Column using SSMS
From the Management Studio, right-click on the table, and select the Design to add a
new SQL Server column.
Selecting the Design option will open the table in design mode. Let me a add new
column called Tax of Money data type.
Click the Close button will display the pop-up window. Please select the Yes button
to save the changes.
Now you can see the newly added column called the tax.
Filed Under: SQL
SQL Rename Column
In SQL Server, there is a standard stored procedure called SP_RENAME to rename
the column name. The syntax of this Rename Column approach is
-- Syntax for SQL Server rename column Name is:
SP_RENAME '[Table Name].[Old Column Name]', '[New Column
Name]', COLUMN'
SQL Rename Column Example
In this example, we will rename the column using this SP_RENAME stored
procedure. To demonstrate the SQL Server Rename Column, We use the below
table.
We use the above-specified SQL Server syntax or stored procedure to rename the
YearlyIncome to a new name: Income
-- SQL Server Rename Column Name query is:
USE NewNameDB
GO
SP_RENAME 'Customers.YearlyIncome', 'Income', 'COLUMN'
See the changed column
Rename Column using SSMS
If you can access the Management Studio, then right-click on the table, and select
the Design from the context menu to change or rename the column.
Selecting the Design option will open the table in design mode. Let me rename the
Income column to Annual Income
Click the Close button and select the Yes button from the displayed pop-up window
to save the changes you made in the design window.
See the changed column.
Filed Under: SQL