Top Banner
Introduction to SQL Server 2005 Module 2
42
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Module02

Introduction to SQL Server 2005

Module 2

Page 2: Module02

• Introduction to Database Engine• Concepts of Database• Concepts of Tables• Data Integrity & Its implementation• Constraints• Introduction to Rules & Defaults• DML Commands

– Insert – Update– Delete

Learning Objectives

Page 3: Module02

At the end of this section, you should be able to:• What is a Database Engine?• What is a Database & How to create it?• How to work with Tables?• What is Data Integrity?• How is Data integrity implemented?• Work with Constraints• Work with Rules & Defaults

• Execute DML Commands – Insert – Update– Delete

Module 2 : Agenda

Page 4: Module02

Introduction to Database Engine

• Database Engine is the core service for storing, processing and securing data.

• It maintains the relationships between the stored data.

• It helps in the translation the data to information.

• It provides controlled access- While logging in SQL Server Management studio, we can select the server type as database engine.

• It facilitates rapid transaction processing to meet the requirements of the most demanding data consuming applications within the enterprise.

• The Database Engine provides rich support for sustaining high availability.

Page 5: Module02

• The SQL Server Database stores the data pertaining to a particular Business.

• Each SQL Server has two types of Databases. – System Databases (master,model,tempdb,msdb)– User Databases (pubs, northwind, and databases

specific to an application or a business)• SQL Server uses T-SQL statements to work with databases

like storing, maintaining and querying.

Introduction to SQL Server Database

Page 6: Module02

Overview of Database Objects

• SQL Server Database contains the following objects– Tables

– Views

– Indexes

– Stored Procedures

– User Defined Functions

– Rules

– Defaults

– User Defined Data Types

Page 7: Module02

System Database

Database Description

master This database holds a special set of tables (system tables) that keeps track of the system as a whole

model This database forms a template for any new database that you create.

Msdb is where the SQL Agent process stores any system tasks

tempdb It is the key working area for your server

Page 8: Module02

User Database

Database Description

pubs This database provides a consistent place for training and experimentation

Northwind This database, like pubs, is a training database.

Adventure works This is a companion sample database that can be installed with Microsoft SQL Server 2005. The database schema was designed to showcase SQL Server 2005 features.

Page 9: Module02

Database Files

• Database files help in administrative tasks such as backup and restore operations.

• There are two types of database files:• Primary data file: It is the starting point of the database. It points to

other files in the database. Any database will have one primary data file. .mdf is the recommended file name extension.

• Log files: Log information used to recover the database is present in log files. There should be at least one or more log file for each database. .ldf is the recommended file name.

Page 10: Module02

Structured Query Language

• SQL is a high level language • Developed by IBM in late 1970’s• SQL has 4 sublanguages :

DDL DML TCL DCL

CREATE SELECT COMMIT GRANT

ALTER INSERT ROLLBACK REVOKE

DROP UPDATE SAVEPOINT

DELETE

Page 11: Module02

Data Definition Language (DDL)

• DDL is a language used by a database management system which allows users to define the database and its objects, specifying data types, structures and constraints on the data.

• The set of relations in a database must be specified to the system by means of data definition language.

• Database schema is specified by a set of definitions expressed by a data-definition language.

Page 12: Module02

Data Manipulation Language (DML)

• It is a language that enables users to access or manipulate data as organized by the appropriate data model.

• DML Manipulation commands are the most frequently used SQL commands.

• They are used to manipulate the data of the existing objects like tables.

Page 13: Module02

Transaction Control Language(TCL)

• We can use SQL to control transactions.

• Transactions are– Collection of operations that form a single logical unit of work.

– All changes made to the database can be referred to as a Transaction.

– Transaction changes can be made permanent to a database only if they are committed.

– Transactions operations executed between the begin and end of the

Transaction.• A Transaction can be defined as a Sequence of operations performed

together as a Single logical unit of work.• A single unit of work must possess the four properties called ACID.

• Automicity• consistency• Isolation• Durability

Page 14: Module02

Guidelines in writing SQL Statements

• SQL statements are not case-sensitive

• SQL statements can be on one or more lines

• SQL statements are optionally ended with a semicolon

• Keywords cannot be abbreviated or split across lines

• Clauses are usually placed on separate lines

• Indents are used to enhance readability

• Keywords are typically entered in uppercase; all other words such as table name and columns are entered in Pascal case

Page 15: Module02

Transact- SQL

• SQL Server uses T-SQL and MySQL Languages

• T-SQL is an extension of SQL. For instance:– Summary calculation– Stored Procedures– Exception Handling– User Defined Functions– Triggers– Cursors

• A SQL command execution returns the number of rows affected.

Page 16: Module02

To Create & Use Database

• Database creation syntax : Create database <Database_Name>

Go

• Example:Create database MyDB

Go

• Use database syntax:Use database <Database_Name>

Go

• Example : Use MyDB

go

Page 17: Module02

Data TypesData Type

NameClass Size in

BytesDescription

Bit Integer 1 For storing binary values

Bigint Integer 8 Range is from -263 to 263-1

Int Integer 4 Whole Numbers

SmallInt Integer 2 Whole Numbers (Small Range)

TinyInt Integer 1 0 to 255

Decimal or Numeric

Decimal/Numeric Varies Fixed Precision and Scale from -1038-1 to 1038-1.

Money Money 8 Monetary units from -263 to 263 plus precision to 4 decimal places.

SmallMoney Money 4 Monetary units from -214,748.3648 to +214,748.3647

Float Approx. Numeric Varies Accepts an argument that determines size and precision

Page 18: Module02

Create Tables Syntax :CREATE TABLE table_name(

{< column_definition >|< table_constraint >}[ ,...n ])

<column_definition>::={columnname datatype}[{ DEFAULT constant_expression | [IDENTITY[( seed,increment)]]}] [ROWGUIDCOL][<column_constraint>[ ...n ] ]

<column_constraint>::=[CONSTRAINT constraint_name]

{[NULL|NOT NULL]|[PRIMARY KEY|UNIQUE]|REFERENCES ref_table[(ref_column)][ON DELETE {CASCADE|NO ACTION}][ON UPDATE {CASCADE|NO ACTION}]}

<table_constraint>::=[CONSTRAINT constraint_name]

{[{PRIMARY KEY|UNIQUE} {(column[,...n])}]| FOREIGN KEY(column [ ,...n])REFERENCES ref_table[(ref_column[ ,...n ] )] [ON DELETE{CASCADE|NO ACTION}][ON UPDATE{CASCADE|NO ACTION}]}

Page 19: Module02

Create Table - Example

CREATE TABLE [Categories](

[CategoryID] [int],

[CategoryName] [nvarchar](15),

[Description] [ntext],

CONSTRAINT [PK_Categories] PRIMARY KEY

(

[CategoryID] ASC

))

Page 20: Module02

Delete Table

• Table Deletion Syntax:drop table <table_name>

• Table deletion Exampledrop table categories

Page 21: Module02

Data Integrity

• Data integrity refers to the correctness and completeness of data within a database.

• To enforce this we restrict the data values that users can insert, delete or update in the database.

• T-SQL mechanisms to enforce data integrity:– Rules– Defaults– Indexes– Triggers

• These mechanisms satisfy:– No null value requirement– Check validity of the data entered– Uniqueness of the data– Referential integrity

Page 22: Module02

Type of Constraints

• Not Null

• Check

• Unique

• Primary Key

• Referential Integrity Constraint (Foreign Key)

Page 23: Module02

Constraint – Not Null

• Null is not Zero or a blank

• Null implies no entry or value unknown

• We identify columns which accept null and which should not be null.

• Create table with Not Null constraint :

CREATE TABLE [Categories](

[CategoryID] [int] NOT NULL,

[CategoryName] [nvarchar](15) NOT NULL

)

Page 24: Module02

Constraint – Check

• Check constraint limits the values of data inserted into columns.

• This constraint is useful for applications that check a limited and specific range of values.

• We use Check constraint for the data integrity when specific values are to be checked.

• It’s a condition that the value must pass before it is inserted into the table. The search condition includes : – With IN a list of constant expressions– With BETWEEN a range of constant expressions– With LIKE wild characters

Page 25: Module02

Constraint – Check (Continued)

• Example : create table mytab(

[id] char(4) check (id in ('1234','5432','6000')

or id like '60[0-9][0-9]'),

[name] varchar(10))

• After creating this table issue the following commands :insert into mytab values ('1234','sss')

insert into mytab values ('1233','sss')

insert into mytab values ('6034','sss')

Page 26: Module02

Constraint – Unique

• Unique Constraint ensures no duplication of values in the rows for the constraint applied column.

• This constraint creates unique indexes to enforce data integrity.• Example :

create table uniqueconstraint

(

[id] char(4),

[name] varchar(20),

date datetime,

unique clustered (id,[name]))

• Issue the following commands to insert datainsert into uniqueconstraint values ('1214','ss',getdate())

Page 27: Module02

Constraint – Primary & Foreign Key

• Primary Key constraint behaves like Unique Constraint – difference is it applies Not NULL constraint as well.

• Foreign key constraint or referential integrity refers to the methods used to manage the relationships between tables.

• With Foreign Key constraint, when we create a table we can define constraints to ensure that the data inserted into a particular column has matching values in another table.

• Three types of references:– References to another table– References from another table– Self reference.

Page 28: Module02

Constraint – Primary & Foreign Key • Example :

CREATE TABLE Dept(

[DeptNo] [int] primary key,

[Dname] [nchar](10),

[Location] [nchar](10))

CREATE TABLE [Emp](

[EmpNo] [int] primary key,

[Ename] [nchar](10) ,

[MgrId] [int],

[DOJ] [datetime] ,

[DeptNo] [int] references Dept(DeptNo))

• Insert the following records in the given order : insert into emp values (1,'sss',1,getdate(),1)

insert into dept values (1,’LKM’,’MDC')

insert into emp values (1,'sss',1,getdate(),1)

Page 29: Module02

Rules

• A Rule lest the user specify what can or can not be entered into a particular column.

• To Create a rule– Create Rule– Bind the rule to a column by using sp_bindrule.– Test the rule by inserting data.

• Example: create rule sapid as @id like ’1_ _ _ _ _ _ _’

sp_bindrule sapid, ‘emp.empno’

insert into emp values (1234568,'sss',1,getdate(),1)

insert into emp values (12345678,'sss',1,getdate(),1)

Page 30: Module02

Defaults

• Default is a values that is automatically inserted if the used does not enter any data.

• To create a Default:– Define the default– Bind the default to desired table column using sp_bindefault– Test the bound default by inserting data.

• Examplecreate default location as 'unknown'

sp_bindefault location, 'dept.location'

insert into dept(deptno,dname) values (2,'HR')

select * from dept

Page 31: Module02

Working with IDENTITY column

• Identity column contains a value for each row, generated automatically, that uniquely identifies the row with the table.

• Identity columns can not be updated and also don't allow nulls.

• Identity columns must have a numeric datatype.

• Example : CREATE TABLE [idcheck](

[id] [int] IDENTITY(1,1) primary key,

[name] [nchar](10)

)

INSERT INTO [idcheck] ([name]) VALUES ('aaa')

*Note the value is automatically inserted in id column

Page 32: Module02

INSERT Statement

INSERT INTO <table>

[ (column

[, column…] ) ]

VALUES (value

[, value…] )

table is the name of the table

column is the name of the column in the table to populate

value is the corresponding value for the column

Note: This statement with the VALUES clause adds only one row at a time to a table.

Page 33: Module02

INSERT Statement (Continued)

• Inserts a new row containing values for each column

• In Insert clause, list values in the default order of the columns in the table

• Listing of column names is optional, provided you specify all values of ALL columns in correct order corresponding to the table design

• Enclose character and date values within single quotation marks

INSERT INTO Departments (DepartmentId,

DepartmentName, CurrentDate)

VALUES ( 70, ‘Public Relations’,

‘10-OCT-04’)

Page 34: Module02

Inserting Rows from Another Table

• Write your INSERT statement with a subquery

• Do not use the VALUES clause

• Match the number of columns in the INSERT clause to those in the subquery

INSERT INTO SalesReps ( Id,Name,Salary)

SELECT EmployeeId,

LastName,

Salary

FROM Employees

WHERE JobId LIKE ‘%REP%’

Page 35: Module02

UPDATE Statement

UPDATE table

SET column = value

[,column = value, …]

[WHERE condition]

table is the name of the table

column name of the column in the table to populate

value corresponding value for the column

condition identifies the rows to be updated and is composed of column names, expressions, constraints, sub-queries, and comparisonoperators

Page 36: Module02

• Specific row or rows are modified if you specify the WHERE clause

• All rows in the table are modified if you omit the WHERE clause

update dept

set deptno=10

where location=‘unknown’

Updating Rows in a Table

Page 37: Module02

• Use sub queries in UPDATE statements to update rows in a table based on values from another table

Updating Rows Based on Another Table

UPDATE CopyEmp

SET DepartmentId = (SELECT DepartmentId

FROM Employees

WHERE EmpId =100)

WHERE JobId = (SELECT JobId

FROM Employees

WHERE EmpId = 200)

Page 38: Module02

DELETE Statement

DELETE [FROM] table

[WHERE condition]

table is the name of the table

condition identifies the rows to be deleted and is composed of column names, expressions, constraints, sub-queries, and comparison operators

Page 39: Module02

• A specific row or specific rows are deleted if you specify the WHERE clause

• All rows in the table are deleted if you omit the WHERE clause

Delete from dept

where deptno=10

Deleting Rows in a Table

Page 40: Module02

• Use sub queries in DELETE statements to delete rows in a table based on values from another table

DELETE FROM Employees

WHERE DeptId = (SELECT DeptId

FROM Departments

WHERE DeptType = ‘CST’)

Deleting Rows Based on Another Table

Page 41: Module02

Key Points

• SQL is an industry standard language for updating to, and getting information from, a database.

• The basic and most common SQL statements are: SELECT, INSERT, UPDATE, DELETE.

Page 42: Module02

Questions & Comments