Thursday 29 March 2012

SQL Create Database and Table


Create Database:
CREATE DATABASE MyDataBaseName

Query:
CREATE DATABASE Information

Database called Information will be created

Create Table:
Table exists with in data base, so it is important to mention with in which data base you want table to be created

Query:
USE [Information]

CREATE TABLE Persons
(
P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

Table called Persons will be created under data base Information
Column of the table will be, P_id, LastName, FirstName, Address, City.
Data Type is int, varchar, date etc.

CreateTable

SQL Constraints:
Constraints are used to limit the type of data that can go into a table. In the above picture you can be Column name P_Id and (int, null), null means, P_id column can have null value. If you create a table with query below, P_Id and LastName Columns can not have null value.

Query:

CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

NOT NULL constraints means value for that column can not be NULL. In the above example P_id and LastName can not be left null.

I deleted the table Persons created and created the same table with new query. Only difference between table created before and now is IP_Id and LastName constraint is not null.

CreateTable2

No comments:

Post a Comment