Sunteți pe pagina 1din 17

Contents

1. SQL Commands (DDL, DML, TCL, DCL):.........................................................1


a) Data Definition Language (DDL).................................................................1
b)

Data Manipulation Language (DML)........................................................1

c) Transaction Control Language (TCL)..........................................................1


d)

Data Control Language (DCL)...................................................................2

2. Table:.................................................................................................................. 2
a) Create Table................................................................................................... 2
b)

Change the table name............................................................................. 2

c) Drop table....................................................................................................... 2
d)

Get all table in the database....................................................................2

3. Column............................................................................................................... 3
a) Add Column.................................................................................................... 3
b)

Rename Column Name...............................................................................3

c) Drop Column................................................................................................... 3
d)

Change DataType of Column.....................................................................3

4. Database............................................................................................................ 3
a) Create Database............................................................................................ 3
b)

Rename Database...................................................................................... 3

c) Drop Database............................................................................................... 3
d)

All Stored Procedures in Database..........................................................3

e) All Tables in Database...................................................................................3


f)

All Views in the Database............................................................................3

g) Find a column in a Database in more than one Table.............................3


5. Constraints........................................................................................................ 4
a) NOT NULL........................................................................................................ 4
b)

CHECK........................................................................................................... 4

c) UNIQUE KEY.................................................................................................... 4
d)

PRIMARY KEY............................................................................................... 4

e) Foreign Key..................................................................................................... 4
f)

Candidate Key................................................................................................ 4

g) Alternate Key................................................................................................. 5

h)

Composite Key............................................................................................ 5

i)

Surrogate Key................................................................................................ 5

j)

Supper Key..................................................................................................... 5

6. View.................................................................................................................... 5
7. Triggers.............................................................................................................. 5
8. Joins.................................................................................................................... 8
a) Type of Joins:.................................................................................................. 8
b)

Inner Join:.................................................................................................... 9

c) Outer Join:....................................................................................................... 9
d)

Left Outer Join:......................................................................................... 10

e) Right Outer Join:.......................................................................................... 10


f)

Full Outer Join.............................................................................................. 11

g) Cross Join:..................................................................................................... 11
h)

Self-Join...................................................................................................... 12

Points of Interest...................................................................................... 12

9. Unions............................................................................................................... 13
10.

Index.............................................................................................................. 14

SQL CREATE INDEX Syntax.........................................................................14

SQL CREATE UNIQUE INDEX Syntax..........................................................14

CREATE INDEX Example..............................................................................15

DROP INDEX Syntax for MS SQL Server:..................................................15

Difference between Clustered Index and Non-Clustered Index...........15

When should indexes be avoided?...........................................................16

1. SQL Commands (DDL, DML, TCL, DCL):


SQL commands are instructions used to communicate with the database to perform
specific task that work with data. SQL commands can be used not only for searching
the database but also to perform various other functions like, for example, you can
create tables, add data to tables, or modify data, drop the table, set permissions for
users.
SQL commands are grouped into four major categories depending on their
functionality:

a) Data Definition Language (DDL)


Data Definition Language (DDL) statements are used to define the database
structure or schema. Some examples:

CREATE - to create objects in the database


ALTER - alters the structure of the database
DROP - delete objects from the database
COMMENT - add comments to the data dictionary
RENAME - rename an object
TRUNCATE - remove all records from a table, including all spaces allocated
for the records are removed

b) Data Manipulation Language (DML)


Data Manipulation Language (DML) statements are used for managing data
within schema objects. Some examples:

c)

SELECT - retrieve data from the a database


INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
LOCK TABLE - control concurrency

Transaction Control Language (TCL)

Transaction Control (TCL) statements are used to manage the changes made by
DML statements. It allows statements to be grouped together into logical
transactions.

COMMIT - save work done


ROLLBACK - restore database to original since the last COMMIT
SAVEPOINT - identify a point in a transaction to which you can later roll back
SET TRANSACTION - Change transaction options like isolation level and what
rollback segment to use

d) Data Control Language (DCL)


It is used to create roles, permissions, and referential integrity as well it is used to
control access to database by securing it.
These SQL commands are used for providing security to database objects.
These commands are:

GRANT - gives user's access privileges to database


REVOKE - withdraw access privileges given with the GRANT command

2. Table:
A table is a collection of related data held in a structured format within a database. It
consists of fields (columns), and rows

a) Create Table
CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

b) Change the table name

EXEC sp_rename 'Sales.SalesTerritory', 'SalesTerr';


ALTER TABLE oldtable RENAME TO newtable

c) Drop table

Drop Table TableName

d) Get all table in the database

Select * from Sys.Objects where type=U


Select * from sys.tables

3. Column
a) Add Column

ALTER TABLE Students ADD subject Varchar(50)

b) Rename Column Name

EXEC sp_RENAME 'TableName.Subject' , 'Subjects', 'COLUMN'

c) Drop Column

ALTER TABLE TableName DROP COLUMN subject

d) Change DataType of Column

ALTER TABLE TableName alter COLUMN Age VarChar(20)

4. Database
A database is a collection of information that is organized so that it can easily be
accessed, managed, and updated.

a) Create Database

Create DATABASE TestDB

b) Rename Database
USE master
GO
ALTER DATABASE TestDB1
Modify Name = TestDB
GO

c) Drop Database

Drop Database TestDB

d) All Stored Procedures in Database

Select * from Sys.Procudures

e) All Tables in Database

select * from Sys.Tables


select * from INFORMATION_SCHEMA.TABLES

f) All Views in the Database

select * from INFORMATION_SCHEMA.VIEWS

g) Find a column in a Database in more than one Table

select * from INFORMATION_SCHEMA.Columns where Column_Name like


'%RuleID%'

5. Constraints
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is
aborted by the constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE
statement) or after the table is created (inside the ALTER TABLE statement).

a) NOT NULL
Indicates that a column cannot store NULL value

b) CHECK
Ensures that the value in a column meets a specific condition

c) UNIQUE KEY
Ensures that each row for a column must have a unique value, and unique key
does allow a NULL value.

d) PRIMARY KEY
A Primary Key is a column or a combination of columns that uniquely identify a
record. Only one Candidate Key can be Primary Key. Primary Key does not allow
the NULL values.
A table can contain only one primary key constraint.
A primary key cannot exceed 16 columns and a total key length of 900
bytes.
The index generated by a primary key constraint cannot cause the number
of indexes on the table to exceed 999 non-clustered indexes and 1
clustered index.
If clustered or non-clustered is not specified for a primary key constraint,
clustered is used if there no clustered index on the table.
All columns defined within a primary key constraint must be defined as not
null. If null ability is not specified, all columns participating in a primary
key constraint have their null ability set to not null.
If a primary key is defined on a CLR user-defined type column, the
implementation of the type must support binary ordering.

e) Foreign Key
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

f) Candidate Key
A Candidate Key can be any column or a combination of columns that can qualify
as unique key in database. There can be multiple Candidate Keys in one table.
Each Candidate Key can qualify as Primary Key

g) Alternate Key
Any candidate key which is not selected as a primary key is called Alternate Key.

h) Composite Key
A key that is composed of more than one column is called Composite Key.

i) Surrogate Key
A surrogate key is a key which contains the numeric values, an Identity Key in SQL
Server is a surrogate key, it can be a primary key, it is very fast for comparison
purpose because it takes less time for comparison.

6. View
A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the
data as if the data were coming from one single table.
Example: 1
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
We can query the view above as follows:
SELECT * FROM [Current Product List]
Example: 2
CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName
We can query the view above as follows:
SELECT * FROM [Current Product List]

7. Triggers
Triggers are a special kind of stored procedure that fires automatically; they are
executed when an event occurs in the database server. We can create Data
Manipulation Language (DML) triggers and Data Definition Language (DDL) triggers in
SQL Server 2012.
When the user wants to modify data using a DML event then the DML trigger is
executed. In other words, a DML trigger is used for INSERT, DELETE and UPDATE
statements of a table or view.
When the user attempts to perform an operation using DDL then the DDL trigger is
executed. In other words, a DDL trigger is executed for CREATE, ALTER and DROP
statements of a table or view.
There are three types of triggers in SQL Server 2012:

AFTER Trigger

INSTEAD OF Trigger

FOR Trigger

Statement that create vendors_info table in SQL Server 2012


createtable vendors_info
(
Vendorid int,
Vendorname varchar(15),
Vendorcity varchar(15),
Vendorstate varchar(15)
)
Statements that insert data in vendors_info table in SQL Server 2012
insertinto
insertinto
insertinto
insertinto
insertinto

vendors_info
vendors_info
vendors_info
vendors_info
vendors_info

values
values
values
values
values

(20,'vipendra','noida','up')
(21,'deepak','lucknow','up')
(22,'rahul','kanpur','up')
(23,'malay','delhi','delhi')
(24,'mayank','noida','up')

A Statement that is used to fetch data from vendors_info table in SQL


Server 2012

A Statement that is used to create a trigger in SQL Server 2012


This trigger is executed for INSERT and UPDATE statements and it converts the
name of the vendor city to uppercase:
CREATETRIGGER vendor_trigger
ON vendors_info
AFTER INSERT,UPDATE
AS
UPDATE dbo.vendors_info
SET vendorcity =UPPER(vendorcity)
WHEREvendorid IN(SELECT vendorid FROM INSERTED)
Statement that inserts data into the vendors_info table and uses a
trigger in SQL Server 2012
INSERTINTO dbo.vendors_info
(vendorid ,
vendorname ,
vendorcity ,
vendorstate
)
VALUES ( 25, -- vendorid - int
'neha' ,-- vendorname - varchar(15)
'lucknow' ,-- vendorcity - varchar(15)
'up' -- vendorstate - varchar(15)
)
A Statement that is used to fetch data from the vendors_info table after
using a trigger in SQL Server 2012
In this table we saw that, before using the trigger, the vendorcity name is in lower
case but after creating the trigger, the vendorcity name is updated to use all upper
case.

8. Joins
Joins are used to get data from two or more tables based on relationship between
some of the columns in tables

a) Type of Joins:

Inner Join
Outer Join
o Left Outer Join
o Right Outer Join
o Full Outer Join
Self-Join
Cross Join

Employee Table:

Department Table:

b) Inner Join:
The join that displays only the rows that have a match in both the joined tables is
known as inner join.
Select
e1.Username,
e1.FirstName,
e1.LastName,
e2.DepartmentName
From Employee e1 Inner JoinDepartments e2 on e1.DepartID=e2.id

Output:

c) Outer Join:
Outer join returns all the rows of both tables whether it has matched or not.

We have three types of outer join:


o
o
o

Left outer join


Right outer join
Full outer join

d) Left Outer Join:


Left join displays all the rows from first table and matched rows from second.
SELECT
*
FROM Employee e1
LEFT OUTER JOINDepartments e2
ON e1.DepartID = e2.id

Output:

e) Right Outer Join:


Right outer join displays all the rows of second table and matched rows from first
table.
SELECT
*
FROM Employee e1
RIGHT OUTER JOIN Departments e2
ON e1.DepartID = e2.id

Output:

f) Full Outer Join


Full outer join returns all the rows from both tables whether it has been matched
or not.
SELECT
*
FROM Employee e1
FULL OUTER JOIN Departments e2
ON e1.DepartID = e2.id

Output:

g) Cross Join:
Cross Join that produces Cartesian product of the tables that are involved in the
join. The size of a Cartesian product is the number of the rows in the first table
multiplied by the number of rows in the second table like this.

SELECT
*
FROM Employee
Cross Join Departments e2

h) Self-Join
Joining the table itself called self-join. Self-join is used to retrieve the records
having some relation or similarity with other records in the same table.
Here, we need to use aliases for the same table to set a self-join between single
table and retrieve records satisfying the condition in where clause.

SELECT
e1.Username,
e1.FirstName,
e1.LastName fromEmployee e1
Inner Join Employee e2 on e1.id=e2.DepartID
Output:

Interesting Point:
Here, I have taken one example of self-join in this scenario where manager name
can be retrieved by manager-id with reference of employee id from one table.
Here, I have created one table employees like that:

If I have to retrieve manager name from manager id, then it can be


possible by Self join:

Select
E1.empName as ManagerName,
E2.empName as EmpName
from employees e1
inner join employees e2
on e1.id=e2.managerid
Result:

9. Unions
The SQL UNION operator combines the result of two or more SELECT statements.
Union & Union ALL:
Notice that each SELECT statement within the UNION must have the same number
of columns. The columns must also have similar data types. Also, the columns in
each SELECT statement must be in the same order.
Note: The UNION operator selects only distinct values by default. To allow duplicate
values, use the ALL keyword with UNION.

SELECT City FROM Customers


UNION
SELECT City FROM Suppliers
ORDER BY City;

SELECT City FROM Customers


UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

10.

Index
Indexes allow the database application to find data fast; without reading the
whole table.
So, an index can be created in a table to find data more quickly and
efficiently.
The users cannot see the indexes; they are just used to speed up
searches/queries.
Note: Updating a table with indexes takes more time than updating a table
without (because the indexes also need an update). So you should only
create indexes on columns (and tables) that will be frequently searched
against.

SQL CREATE INDEX Syntax


Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name ON table_name (column_name)

SQL CREATE UNIQUE INDEX Syntax


Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name ON table_name (column_name)
Note: The syntax for creating indexes varies amongst different databases.
Therefore: Check the syntax for creating indexes in your database.

CREATE INDEX Example


The SQL statement below creates an index named "PIndex" on the
"LastName" column in the "Persons" table:
CREATE INDEX PIndex ON Persons (LastName)
If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:
CREATE INDEX PIndex ON Persons (LastName, FirstName)

DROP INDEX Syntax for MS SQL Server:


DROP INDEX table_name.index_name

Difference between Clustered Index and NonClustered Index


Clustered Index
Only one per table

Faster to read than non-clustered as data is physically


stored in index order

Non Clustered Index


Can be used many times per table

Quicker for insert and update operations than a clustered


index

Both types of index will improve performance when select data


with fields that use the index but will slow down update and
insert operations.
The difference is that, Clustered index is unique for any
given table and we can have only one clustered index on a

table. The leaf level of a clustered index is the actual data and
the data is resorted in case of clustered index. Whereas in nonclustered index the leaf level is actually a pointer to the data
in rows so we can have as many non-clustered indexes as we
can on the
Clustered index is super-fast for searches, and slows down deletes
and update to data. If you have a primary key on your table, it is a
clustered index by default, so if you want to have another clustered
index, your primary key needs to be marked NOT clustered.

When should indexes be avoided?


Although indexes are intended to enhance a database's performance, there
are times when they should be avoided. The following guidelines indicate
when the use of an index should be reconsidered:

Indexes should not be used on small tables.

Tables that have frequent, large batch update or insert operations.

Indexes should not be used on columns that contain a high number of


NULL values.

Columns that are frequently manipulated should not be indexed.

S-ar putea să vă placă și