Instagram
youtube
Facebook
Twitter

MS SQL Server- Create table

MS SQL Server CREATE DATABASE

  • A table is used to store data and arrange the data in rows and columns.
  • Three components are needed to create a table: Name of the table, Name of fields, and Definition for each field.
  • There are mainly two ways to create a table in SQL Server: SQL Server Management Studio and Transact-SQL Command.

Using SQL Server Management Studio

  • In Object Explorer, click on the '+' to expand the Database folder.
  • Select the database and click on the '+' to expand the selected database.
  • Select the tables folder, right-click on it select new, and then click on the Table option.
  • After clicking the Table option, a Table Designer window appears which includes column name, datatypes, and Not Null constraint.
  • For defining more properties, click on the desired column and it will display the column 'properties tab' and select the appropriate properties.
  • Right-click on the desired column and set it as the primary key by clicking on Set Primary Key if required. and If you want a foreign key Right-click the desired column and select the relationship option.
  • Right click anywhere in Table Designer Pane select properties then Schema and select the appropriate Schema. A table is by default stored in dbo schema.
  • Once we have done, choose the save table name in the File menu. As we click on the save button, a dialog box to choose the name of the table will display. Enter the name of the table and click on OK.
  • Once the table is created, click on refresh or press F5 and see the name of the table will appear in the list of tables in the selected database.

Using Transact-SQL command

  • Create a table with help of CREATE TABLE command in the selected database.
  • Query to create a table in the selected database:
CREATE TABLE [database_name].[schema_name].table_name(column_definition1, column_definition2,.....,table_constraints);
  • database_name is the name of the database where you want to create a table. Otherwise, It will assume the current database by default.
  • Schema_name indicates the schema newly created table belongs.
  • table_name is the name of the table and the name should be unique in the selected database.
  • column_definition indicates the column name with datatypes like int, float, char, varchar, and so on.
  • table_constraints indicates the table constraints like PRIMARY KEY, UNIQUE KEY, FOREIGN KEY, CHECK, etc.
  • For Example:
CREATE TABLE University.dbo.student(Id INT IDENTITY PRIMARY KEY, Name VARCHAR(65)NOT NULL, Branch CHAR(10), CGPA INT)
  • Once the table is created, you can add data to this table using INSERT statement.