You are on page 1of 10

1.

Create Database;

Create database <Database Name>


Create database TestDB;
or
CREATE DATABASE IF NOT EXISTS demo;
// It Check Name whether exist or not

2. Rename a database in SQL Server;

Alter database DatabaseName Modify Name = NewDatabaseName;


Execute sp_renameDB ‘OldDatabaseName’,’NewDatabaseName’ // Using Inbuilt
Store Procedure

3. Drop a database in SQL Server?

Drop Database DatabaseThatYouWantToDrop;


Alter Database DatabaseName Set SINGLE_USER With Rollback Immediate;

4. SQL Sub Languages:

SQL contains the following sublanguages?

a) DDL - DDL stand for Data Definition Language:


* DDL statements are used to alter or modify the structure of database.
* these 5 commands are used - (create, alter, sp_rename, drop,
truncate).

b) DML - Data Manipulation Language:


* DML statements are used to alter or modify the data in the table.
* These 3 commands are used - (Insert, Update, Delete).

c) DQL/ DRL (1 command- select).


d) TCL (3 commands- commit, rollback, savepoint)
e) DCL (2 commands- Grant, Revoke).

# DDL - Data Definition Language Commands:

1. Create Command in SQL Server:

Create Table <Table Name>


(
<Column Name1> <Data Type> <Size>,
<Column Name1> <Data Type> <Size>,
<Column Name1> <Data Type> <Size>
)

eg:-

CREATE TABLE student


(
studid INT,
sname VARCHAR(max),
salary DECIMAL(6, 2)
)

2. Alter column command in SQL Server:


eg- ALTER TABLE <TABLENAME> ALTER COLUMN <COLUMNNAME> <NEW DATA TYPE>[NEW
SIZE];

a. Change the width of a column:

eg- ALTER TABLE Student ALTER COLUMN Name VARCHAR(100);

Note: When you increase the width of a column, you won’t face any
problem but while
decreasing the width if the table contains data in it we cannot
decrease the
width less than the max existing characters in the column.

b. Changing the data type of an existing column:

eg- ALTER TABLE Student ALTER COLUMN Name NVARCHAR(100);

c. Changing the column NULL to NOT NULL:

eg- ALTER TABLE Student ALTER COLUMN No INT NOT NULL;

Note: by default it is NULL

d. Changing NOT NULL to NULL:

eg- ALTER TABLE Student ALTER COLUMN No INT NULL;

e. Adding a new column to an existing table in SQL Server:

eg- ALTER TABLE <TABLENAME> ADD <NEWCOLUMNNAME> <DATA TYPE>[NEW SIZE];


eg- ALTER TABLE Student ADD Branch VARCHAR(20);

f. Deleting Column in SQL Server:

eg- ALTER TABLE <TABLENAME> DROP COLUMN <COLUMNNAME>;


eg- ALTER TABLE Student DROP COLUMN Branch;

3. Store Procedure SP_RENAME Command in SQL Server:

eg- SP_RENAME ‘<TABLE NAME>.<OLD COLUMN NAME>’, ‘NEW COLUMN NAME’;


eg- SP_RENAME ‘Student.Name’, ‘StudentName‘;
eg- SP_RENAME ‘OLD TABLE NAME’, ‘NEW TABLE NAME’;
eg- SP_RENAME ‘Student‘, ‘StudentDetails’;

4. Truncate Command in SQL Server:

eg- TRUNCATE TABLE <TABLENAME>;


eg- TRUNCATE TABLE Student;

Note: * The truncate command will delete data rows but not the structure of
the table.
* delete all the records or rows from a table without any
condition (No Where clause).

5. Drop Command in SQL Server:

eg- DROP TABLE <OBJECT NAME>;


eg- DROP TABLE Student;
Note: When a table is dropped all the dependent constraint which are
associated
with the table also gets dropped. We cannot drop a master table.

# ***What are the differences between Delete and Truncate Command in SQL Server?***

#Delete

* It is a DML command.
* By using the delete command we can delete a specific record from the table.
* Delete supports WHERE clause.
* It is a temporary deletion (It means a row containing 8 rows if we delete
it next row will be from 9 because it support rollback)
* Delete supports rollback transactions for restoring the deleted data.
* Delete command will not reset identity property.

#Truncate

* It is a DDL command
* But it is not possible with truncate command.
* It is a permanent deletion. (It means a row containing 8 rows if we delete
it. the next row will be from 1 because it does not support rollback)
* Truncate does not support the WHERE clause.
* Truncate doesn’t support rollback transaction so that we cannot restore the
deleted information.
But it will reset the identity property.

# Data Types in Sql Server:

1. Integer data types


2. Decimal data types
3. Money / currency data types
4. Date and Time data types
5. Character data types
6. Binary data types
7. Special data types

1. Integer data types (TinyInt(byte),SmallInt(short),Int(int),BigInt(long)).

2. Decimal data types (Decimal (P, S),Numeric (P, S))


* Precision (P): Maximum number of digits that we can store both to the
left side and right side of the decimal point.
* Scale (S):maximum number of decimal digits that we can store to the
right of the decimal point.
* The default scale is 0.
* The default value of precision is 18.
Example: 285.21 // Here Precision - 5 and Scale - 2.

4. SQL Server Date and Time data types: (Date, Time, DateTime)
* Date - This data type will accept date format information only. The
default format of the date data type is ‘YYYY/MM/DD’.
* Time - It allows time format information only. The default
format of the time data type is ‘hh:mm:ss.ms’.
* DateTime - It allows date and time format information. The default
format of DateTime data type is ‘YYYY/MM/DD hh:mm: ss.ms’.

5. Character Data Types in SQL Server:


a) Non Unicode data types: char (Size), varchar (size/max), Text. // It
occupy 1 byte per character. // It support only English data only
b) Unicode data types: nchar(size), nvarchar(size), ntext. // It
occupy 2 byte per character. // It support universal data
* char() - static data type.
* varchar() - dynamic data type.
* nchar(Size) - static data type.
* Nvarchar(size/max) - dynamic data type.

# What is a Constraint in SQL Server?

SQL Server Constraint as a property that can be assigned to a column or


columns of a table.
The SQL Server Constraints are mainly used to maintain data integrity.

# What are the different types of SQL Server Constraints available?

SQL Server supports six types of constraints for maintaining data integrity.
They are as follows

1. Default Constraint
2. UNIQUE KEY constraint
3. NOT NULL constraint
4. CHECK KEY constraint
5. PRIMARY KEY constraint
6. FOREIGN KEY constraint.

# Creating Constraint with own name:

Note: You should define the constraint name while creating the table.
If you have not specified the constraint name while creating the table,
then the SQL server will give a random name to that constraint which is
not user-friendly.

eg- CREATE TABLE customer


(
Id INT CONSTRAINT cid_unique UNIQUE,
NAME VARCHAR(30),
Emailid VARCHAR(100) CONSTRAINT email_unique UNIQUE
)

Note: We cannot impose NOT NULL constraint in table level.


It is possible only for the rest of the four constraints.

# Imposing Constraint in SQL Server:

1. Imposing constraints on Column level (Not Null, Unique, Primary Key,


Foreign key, Default)
2. Imposing constraints on Table level (Unique, Primary Key, Foreign key,
Default)

# What are Composite Constraints in SQL Server?

Whenever a constraint is created based on more than one column then it is


called Composite Constraints in SQL Server.
eg- CREATE TABLE BranchDetails
(
City VARCHAR(50),
Branchcode VARCHAR(10),
Branchlocation VARCHAR (30),
CONSTRAINT city_bc_unique UNIQUE(City, Branchcode)
)

1. Default Constraint in SQL Server?

The Default constraint in SQL Server is used to fill the column with a
default value
that is defined during the creation of a table if the user does not supply
any value while inserting the data.

Note: IDENTITY and timestamp columns can’t be associated with the default
constraint.

CREATE TABLE Employee (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Mumbai',
DateOfBirth date DEFAULT GETDATE(),
Salary DECIMAL (18, 2) DEFAULT 5000.00
)

2. UNIQUE Constraint in SQL Server?

UNIQUE constraint is used to avoid duplicate values but it accepts a single


NULL value in that column.

Syntax: CREATE TABLE<TABLE NAME>(<COLUMN NAME><DATA TYPE><CONSTRAINTKEY>……)

eg- CREATE TABLE Customer


(
Id INT UNIQUE,
NAME VARCHAR(30) UNIQUE,
Emailid VARCHAR(100) UNIQUE
)

eg- INSERT customer VALUES (NULL, NULL, NULL)--ALLOWED


INSERT customer VALUES (11, 'BB', 'pranayakumar7@gmail.com')--ALLOWED
INSERT customer VALUES (NULL, NULL, NULL) -- NOT ALLOWED

3. NOT NULL Constraint in SQL Server?

When you want a column not to accept NULL then you need to apply the NOT NULL
constraint to that column.
That means this constraint is used to avoid NULL values but it accepted
duplicate values into a column.

CREATE TABLE customer


(
id INT NOT NULL,
name VARCHAR(30) NOT NULL,
mobno CHAR(10) NOT NULL
)

eg- INSERT customer VALUES (101, 'AA', '1111111111')--ALLOWED


INSERT customer VALUES (101, 'AA', '2222222222')--ALLOWED
INSERT customer VALUES (NULL, NULL, NULL)--NOTALLOWED
4. Check Constraint in SQL Server?

Check Constraint enforces the valid entries for a given column value by
restricting the type of the value, the format of the data, or the range of
possible values.

eg- CREATE TABLE Employee


(
Emp_id INT NOT NULL CHECK(Emp_id BETWEEN 0 AND 1000),
Emp_name VARCHAR(30) NOT NULL,
Entered_date DATETIME NOT NULL CHECK(Entered_date <=
CURRENT_TIMESTAMP),
Dept_no INT CHECK(Dept_no > 0 AND Dept_no < 100)
)

5. What is Primary Key in SQL Server?

* The Primary Key in SQL Server is the combination of Unique and Not Null
Constraint.
* A table should contain only 1 Primary Key which can be either on a single
or multiple columns i.e. the composite primary key.
* A table should have a primary key to uniquely identify each record.

eg- CREATE TABLE Branches


(
Bcode INT PRIMARY KEY,
Bname VARCHAR(40)
)

# Composite Primary key in SQL Server:

eg- CREATE TABLE BranchDetails


(
City VARCHAR(40),
Bcode INT,
Bloc VARCHAR(30),
PRIMARY KEY(City, Bcode)
)

Note: The primary key is also called a candidate key.


Note: primary key column doesn’t allow NULL values whereas the unique key
column allows only one NULL value.

6. What is a Foreign Key Constraint in SQL Server?

* A foreign key in one TABLE points to a primary key or unique key in another
table.
* The foreign key constraints are used to enforce referential integrity.

a) How to Create Foreign Key Constraint in SQL Server?

a) We require two tables for binding with each other and those two
tables must have a common column for linking the tables.
b) The common column that is present in both the tables need not have
the same name but their data type must be the same.
c) The common column that is present under the parent table or master
table is known as the reference key column and moreover,
the reference key column should not contain any duplicate values.
So we need to impose either UNIQUE or PRIMARY key constraint on that column.
d) If we impose the primary key constraint on the reference key column
that column will also be the identity column of the table.
e) The common column which is present in the child or detailed table is
known as the Foreign key column and
we need to impose a Foreign key constraint on the column which
refers to the reference key column of the master table.

b) Creating PRIMARY KEY and FOREIGN KEY relation on two tables?

* Column Level

eg- CREATE TABLE Employee


(
Eid INT PRIMARY KEY,
Ename VARCHAR(30),
Salary MONEY,
Dno INT FOREIGN KEY REFERENCES Dept(Dno)
)

* Table Level

eg- CREATE TABLE Employee


(
Empid INT,
Ename VARCHAR(40),
Job VARCHAR(30),
Salary MONEY,
Deptno INT,
CONSTRAINT deptno_fk FOREIGN KEY (Deptno) REFERENCES
Dept(Dno)
)

c) Rules for foreign key:

Rule1: Cannot insert a value into the foreign key column provided that
value is
not existing in the reference key column of the parent (master)
table.

Rule2: Cannot update the reference key value of a parent table provided
that the value
has a corresponding child record in the child table without
addressing what to do with the child records.

Rule3: Cannot delete a record from the parent table provided that
records reference key value
has child record in the child table without addressing what to do
with the child record.

d) How to add Constraint to an existing table?

* Alter table ForeignKeyTable add constraint


ForeignKeyTable_ForiegnKeyColumn_FK FOREIGN KEY
(ForiegnKeyColumn) references PrimaryKeyTable (PrimaryKeyColumn).

Note: Before adding the primary key constraint to the table first we
need to make the column NOT NULL and later add a primary key to that column.
Case1: Adding a primary key constraint on an existing column in the
table.

* ALTER TABLE EMP ADD CONSTRAINT X PRIMARY KEY (EMPID)

Case2: Adding a unique constraint to an existing column in the table.

* ALTER TABLE EMP ADD CONSTRAINT Y UNIQUE (ENAME);

Case3: Adding CHECK constraint to an existing column.

* ALTER TABLE EMP ADD CONSTRAINT z CHECK (SALARY > 8000)

Case4: Adding a FOREIGN KEY constraint to an existing column.

* ALTER TABLE DEP ADD CONSTRAINT Q FOREIGN KEY (EID) REFERENCES


EMP(EMPID)

e) How to remove constraints from an existing table?

Syntax - ALTER TABLE<TABLENAME> DROP CONSTRAINT<KEY VARIABLE NAME>

eg- ALTER TABLE EMP DROP CONSTRAINT Y


eg- ALTER TABLE EMP DROP CONSTRAINT Z

Note: While dropping the primary key constraint we first need to drop
the foreign key and then only we can delete the primary key.

# What are Cascading Referential Integrity Constraints in SQL Server?

The Cascading Referential Integrity Constraints in SQL Server are the foreign
key constraints
that tell SQL Server to perform certain actions whenever a user attempts to
delete or update
a primary key to which an existing foreign keys point.

# What are the Actions Performed By SQL Server?

1. SET NULL:
If a user tries to delete or update statement(s) that will affect rows
in the foreign key table,
then those values will be set to NULL when the primary key record is
deleted or updated in the Primary key table.
The important thing that we need to keep in mind that the foreign key
columns affected must allow NULL values.

2. CASCADE:
If a user tries to delete the statement(s) which will affect the rows
in the foreign key table,
then those rows will be deleted when the primary key record is deleted.
Similarly, if an update statement
affects rows in the foreign key table, then those rows will be updated
with the value from the primary key record after it has been updated.

3. SET DEFAULT:
If a delete or update statement affects rows in a foreign key table,
then all rows containing
those foreign keys are set to the default value. All foreign key
columns in the related table must have default constraints defined on them.
4. NO ACTION:
This is the default action that SQL Server performs. This specifies
that if an update or deletes statement
affects rows in foreign key tables, then the action will be denied and
rolled back. An error message will be raised.

# Example of Cascading Referential Integrity Constraints:

<column> <datatype> <constraint name> REFERENCES <master table name>


(<primary key column>)
on delete { No ACTION / cascade / Set Null / Default }
on update { No ACTION / cascade / Set Null / Default }

eg- CREATE TABLE [Person](


[Id] [int] PRIMARY KEY,
[Name] [varchar](100) NOT NULL,
[Email] [varchar](100) NOT NULL,
[GenderID] [int] CONSTRAINT FK_Person_GenderID FOREIGN KEY
REFERENCES dbo.Gender(Id)
ON DELETE CASCADE
ON UPDATE CASCADE
)

# What is Identity in SQL Server?

The Identity in SQL Server is a property that can be applied to a column of a


table whose value is automatically created by the server.
So, whenever you marked a column as identity, then that column will be filled
in an auto-increment way by SQL Server.
That means as a user we cannot insert a value manually into an identity
column.

Syntax: IDENTITY [(seed,increment)]

Arguments:
Seed: Starting value of a column. The default value is 1.
Increment: It specifies the incremental value that is added to the identity
column value of the previous row. The default value is 1.

eg- Create Table Person


(
PersonId int identity(1, 1),
Name nvarchar(20)
)

eg- CREATE TABLE Person


(
PersonId int,
Name nvarchar(20)
)
GO

ALTER TABLE Person


DROP COLUMN PersonId;
GO

ALTER TABLE Person


ADD PersonId INT IDENTITY(1,1);
GO

# Select Statement in SQL Server : The Select Statement in SQL Server is used to
returns records in the form of a result set from one or more tables or views.
Generally, the Select Statement retrieves the data in the form of rows from
one or more database tables or views.

1. Syntax - SELECT Column_List FROM Table_Name

* If you want to select all the columns of a table or view then you can also
use “*”, but for better performance use the column list instead of using “*”.
*

You might also like