SlideShare a Scribd company logo
Introduction to SQL Server 2005  Module 2
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
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
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.
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
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
System Database It is the key working area for your server tempdb is where the SQL Agent process stores any system tasks Msdb  This database forms a template for any new database that you create. model This database holds a special set of tables (system tables) that keeps track of the system as a whole master Description Database
User Database 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. Adventure works  This database, like pubs, is a training database. Northwind This database provides a consistent place for training and experimentation pubs Description Database
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.
Structured Query Language SQL is a high level language  Developed by IBM in late 1970’s SQL has 4 sublanguages :  REVOKE GRANT DCL DELETE SAVEPOINT UPDATE DROP ROLLBACK INSERT ALTER COMMIT  SELECT CREATE TCL DML DDL
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.
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.
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
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 typicall y entered in uppercase; all other words such as table name and columns are entered in Pascal case
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.
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
Data Types Accepts an argument that determines size and precision Varies Approx. Numeric Float Monetary units from -214,748.3648 to +214,748.3647 4 Money SmallMoney Monetary units from -263 to 263 plus precision to 4 decimal places. 8 Money Money Fixed Precision and Scale from -10 38 -1 to 10 38 -1.  Varies Decimal/Numeric Decimal or Numeric 0 to 255 1 Integer TinyInt Whole Numbers (Small Range) 2 Integer SmallInt Whole Numbers 4 Integer Int Range is from -2 63  to 2 63 -1 8 Integer Bigint For storing binary values 1 Integer Bit Description Size in Bytes Class Data Type Name
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}]}
Create Table - Example CREATE TABLE [Categories]( [CategoryID] [int], [CategoryName] [nvarchar](15), [Description] [ntext], CONSTRAINT [PK_Categories] PRIMARY KEY ( [CategoryID] ASC ) )
Delete Table Table Deletion Syntax: drop table <table_name> Table deletion Example drop table  categories
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
Type of Constraints Not Null Check Unique Primary Key Referential Integrity Constraint (Foreign Key)
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 )
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
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')
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 data insert into uniqueconstraint values ('1214','ss',getdate() )
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.
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)
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 (123456 7 8,'sss',1,getdate(),1)
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. Example create default location as 'unknown' sp_bindefault location, 'dept.location' insert into dept(deptno,dname) values (2,'HR') select * from dept
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
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 .
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’)
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%’
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 comparison operators
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 Updating Rows in a Table update dept  set deptno=10  where location= ‘ unknown ’
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)
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
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 Deleting Rows in a Table Delete from  dept where  deptno=10
Use sub queries in DELETE statements to delete rows in a table based on values from another table Deleting Rows Based on Another Table DELETE   FROM   Employees WHERE   DeptId   = ( SELECT   DeptId   FROM   Departments   WHERE  DeptType = ‘CST’)
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.
Questions & Comments

More Related Content

PPTX
Chapter 1 introduction to sql server
PPTX
SQL for interview
PPTX
What is SQL Server?
ODP
Ms sql-server
PPTX
Sql Basics And Advanced
PDF
Sql 2009
PPTX
PPTX
Data concepts
Chapter 1 introduction to sql server
SQL for interview
What is SQL Server?
Ms sql-server
Sql Basics And Advanced
Sql 2009
Data concepts

What's hot (20)

PPT
Sql server T-sql basics ppt-3
PPTX
T-SQL Overview
PPTX
SQL Commands
PPTX
Database Architecture
PDF
Sql a practical introduction
PDF
Sql commands
PPTX
Intro to T-SQL - 1st session
PDF
Database Systems - Introduction to SQL (Chapter 3/1)
DOCX
SQL Differences SQL Interview Questions
PDF
Using T-SQL
PPTX
Database COMPLETE
PPTX
Sql commands
PPT
Sql intro & ddl 1
DOCX
Oracle 11g SQL Overview
PPTX
Getting Started with MySQL I
DOCX
Types of sql commands by naveen kumar veligeti
PDF
Database Fundamental
PDF
SQL Overview
DOC
Database queries
Sql server T-sql basics ppt-3
T-SQL Overview
SQL Commands
Database Architecture
Sql a practical introduction
Sql commands
Intro to T-SQL - 1st session
Database Systems - Introduction to SQL (Chapter 3/1)
SQL Differences SQL Interview Questions
Using T-SQL
Database COMPLETE
Sql commands
Sql intro & ddl 1
Oracle 11g SQL Overview
Getting Started with MySQL I
Types of sql commands by naveen kumar veligeti
Database Fundamental
SQL Overview
Database queries
Ad

Viewers also liked (20)

PDF
Multidimensional model programming
PPTX
Alasql - база данных SQL на JavaScript (MoscowJS)
PPTX
SQL Server 2008 Spatial Data - Getting Started
PDF
Multi-thematic spatial databases
PPTX
Alasql.js - SQL сервер на JavaScript
PPT
SQL Server 2008 for Developers
PPT
Module01
PPT
Module08
PPT
SQL Server 2008 for .NET Developers
DOC
Css introduction
PPT
Module03
PPTX
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
PPTX
Sql server ___________session3-normailzation
PDF
5 tsssisu sql_server_2012
PDF
High Performance Front-End Development
PPT
Module05
PDF
Transact sql data definition language - ddl- reference
PPT
Module07
PPTX
Sql Server Data Tools - Codenamed JUNEAU
PPT
Module06
Multidimensional model programming
Alasql - база данных SQL на JavaScript (MoscowJS)
SQL Server 2008 Spatial Data - Getting Started
Multi-thematic spatial databases
Alasql.js - SQL сервер на JavaScript
SQL Server 2008 for Developers
Module01
Module08
SQL Server 2008 for .NET Developers
Css introduction
Module03
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
Sql server ___________session3-normailzation
5 tsssisu sql_server_2012
High Performance Front-End Development
Module05
Transact sql data definition language - ddl- reference
Module07
Sql Server Data Tools - Codenamed JUNEAU
Module06
Ad

Similar to Module02 (20)

PDF
Lecture on DBMS & MySQL.pdf v. C. .
PPT
PPTX
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
PPTX
Structured Query Language (SQL) _ Edu4Sure Training.pptx
PDF
SQL Complete Tutorial. All Topics Covered
PPTX
05 Create and Maintain Databases and Tables.pptx
PPTX
Database Basics
PPTX
MS SQL - Database Programming Concepts by RSolutions
PDF
CS3481_Database Management Laboratory .pdf
PDF
DBMS Interview Questions PDF By ScholarHat
PDF
Introduction to sq lite
PPT
Db1 lecture4
PPTX
PDF
CS121Lec04.pdf
PPT
Unit4_Lecture-sql.ppt and data science relate
PDF
Introduction to SQL..pdf
PPTX
Unit 2 Chap 4 SQL DDL.pptx
PPS
05 qmds2005 session07
PDF
SQL for data scientist And data analysist Advanced
Lecture on DBMS & MySQL.pdf v. C. .
SQL _UNIT_DBMS_PRESENTSTATION_SQL _UNIT_DBMS_PRESENTSTATION
Structured Query Language (SQL) _ Edu4Sure Training.pptx
SQL Complete Tutorial. All Topics Covered
05 Create and Maintain Databases and Tables.pptx
Database Basics
MS SQL - Database Programming Concepts by RSolutions
CS3481_Database Management Laboratory .pdf
DBMS Interview Questions PDF By ScholarHat
Introduction to sq lite
Db1 lecture4
CS121Lec04.pdf
Unit4_Lecture-sql.ppt and data science relate
Introduction to SQL..pdf
Unit 2 Chap 4 SQL DDL.pptx
05 qmds2005 session07
SQL for data scientist And data analysist Advanced

Recently uploaded (20)

PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Cell Types and Its function , kingdom of life
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Business Ethics Teaching Materials for college
PDF
Complications of Minimal Access Surgery at WLH
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Institutional Correction lecture only . . .
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
Final Presentation General Medicine 03-08-2024.pptx
01-Introduction-to-Information-Management.pdf
Microbial disease of the cardiovascular and lymphatic systems
Cell Types and Its function , kingdom of life
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Pharma ospi slides which help in ospi learning
Microbial diseases, their pathogenesis and prophylaxis
Pharmacology of Heart Failure /Pharmacotherapy of CHF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Business Ethics Teaching Materials for college
Complications of Minimal Access Surgery at WLH
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Institutional Correction lecture only . . .
FourierSeries-QuestionsWithAnswers(Part-A).pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
O5-L3 Freight Transport Ops (International) V1.pdf

Module02

  • 1. Introduction to SQL Server 2005 Module 2
  • 2. 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
  • 3. 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
  • 4. 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.
  • 5. 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
  • 6. 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
  • 7. System Database It is the key working area for your server tempdb is where the SQL Agent process stores any system tasks Msdb This database forms a template for any new database that you create. model This database holds a special set of tables (system tables) that keeps track of the system as a whole master Description Database
  • 8. User Database 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. Adventure works This database, like pubs, is a training database. Northwind This database provides a consistent place for training and experimentation pubs Description Database
  • 9. 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.
  • 10. Structured Query Language SQL is a high level language Developed by IBM in late 1970’s SQL has 4 sublanguages : REVOKE GRANT DCL DELETE SAVEPOINT UPDATE DROP ROLLBACK INSERT ALTER COMMIT SELECT CREATE TCL DML DDL
  • 11. 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.
  • 12. 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.
  • 13. 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
  • 14. 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 typicall y entered in uppercase; all other words such as table name and columns are entered in Pascal case
  • 15. 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.
  • 16. 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
  • 17. Data Types Accepts an argument that determines size and precision Varies Approx. Numeric Float Monetary units from -214,748.3648 to +214,748.3647 4 Money SmallMoney Monetary units from -263 to 263 plus precision to 4 decimal places. 8 Money Money Fixed Precision and Scale from -10 38 -1 to 10 38 -1. Varies Decimal/Numeric Decimal or Numeric 0 to 255 1 Integer TinyInt Whole Numbers (Small Range) 2 Integer SmallInt Whole Numbers 4 Integer Int Range is from -2 63 to 2 63 -1 8 Integer Bigint For storing binary values 1 Integer Bit Description Size in Bytes Class Data Type Name
  • 18. 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}]}
  • 19. Create Table - Example CREATE TABLE [Categories]( [CategoryID] [int], [CategoryName] [nvarchar](15), [Description] [ntext], CONSTRAINT [PK_Categories] PRIMARY KEY ( [CategoryID] ASC ) )
  • 20. Delete Table Table Deletion Syntax: drop table <table_name> Table deletion Example drop table categories
  • 21. 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
  • 22. Type of Constraints Not Null Check Unique Primary Key Referential Integrity Constraint (Foreign Key)
  • 23. 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 )
  • 24. 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
  • 25. 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')
  • 26. 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 data insert into uniqueconstraint values ('1214','ss',getdate() )
  • 27. 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.
  • 28. 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)
  • 29. 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 (123456 7 8,'sss',1,getdate(),1)
  • 30. 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. Example create default location as 'unknown' sp_bindefault location, 'dept.location' insert into dept(deptno,dname) values (2,'HR') select * from dept
  • 31. 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
  • 32. 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 .
  • 33. 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’)
  • 34. 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%’
  • 35. 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 comparison operators
  • 36. 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 Updating Rows in a Table update dept set deptno=10 where location= ‘ unknown ’
  • 37. 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)
  • 38. 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
  • 39. 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 Deleting Rows in a Table Delete from dept where deptno=10
  • 40. Use sub queries in DELETE statements to delete rows in a table based on values from another table Deleting Rows Based on Another Table DELETE FROM Employees WHERE DeptId = ( SELECT DeptId FROM Departments WHERE DeptType = ‘CST’)
  • 41. 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.

Editor's Notes

  • #5: Faculty Notes : 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 into 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. In Microsoft SQL Server 2005, a Database Engine information worker is a domain expert who understands the relationships between the data stored in a database and is able to translate the data into business information. Information workers rarely interact directly with primary online transaction processing (OLTP) databases, instead they use the applications that are associated with the database. When information workers interact directly with databases it is typically to run ad-hoc queries or reports against secondary reporting databases, or to work with smaller databases that are distributed with workgroup or personal applications. A database in Microsoft SQL Server 2005 is made up of a collection of tables that contain data and other objects that are defined to support the activities performed with the data. These objects include views, indexes, stored procedures, and triggers. Before you can create objects within the database, you must create the database and also understand how to change the settings and the configuration of the database. This includes tasks such as expanding or shrinking the database, or specifying the files that are used to create the database.
  • #6: Database : The database holds all facts about all the entities. Database allows user for storing and maintaining the data. Transaction Log : Transactions logs are an important part of protecting your data .By keeping track of operations in a log, the database server makes it possible to recover from a wide range of disaster. The two types of Database in SQL Server are : System Databases : System Database are the database used to store the information about SQL Server itself and used for its operations. User Databases : Users Databases are the database created and maintained by the user.
  • #7: Faculty Notes : Tables - Tables are the objects in the database that actually store the data. Because all other objects in the database depend on their existence, tables can be considered the building blocks of the database. Views - View is an object of a database which contains the query. View when selected it executes the query and extracts the data from the base table. Indexes - Indexes improves the database performance. Indexes help to locate a row in a table directly in a data page instead of going through all the data pages. Stored Procedure - Stored Procedure is a name given to set of T-SQL statements. It includes control structures, looping add return values and so on. User Defined Functions - A function is a grouping of Transact SQL statements that can be reused. SQL server has a large number of built in functions, but these may not meet User needs. For this reason SQL Server gives an ability to create own function called user defined function to perform any task. Rules - Rules provide another means of enforcing domain and user defined integrity rules within user database. Defaults - Defaults are used to fill in the data in the columns if the user does not supply a value. User Defined Data Types - User Defined data Types are based on the system data types. They can be used when several tables must store the same type of data in a column and user must ensure that these columns have exactly the same data type, length, and null ability.
  • #8: pubs This database provides a consistent place for training and experimentation Northwind This database, like pubs, is a training database
  • #9: is where the SQL Agent process stores any system tasks
  • #10: Each database consists of at least two files: one is a primary data file (by default, with the .mdf extension), the other is a log file (by default, with the .ldf extension). There are also optional secondary data files (by default, with the .ndf extension). A database can have only one primary data file, zero or more secondary data files, and one or more log files. Each database file can be used by only one database. When SQL Server is functioning and operating, the database engine keeps track of almost every change that takes place within the database by making entries into the transaction log(.ldf) so that it can be used later if needed.
  • #14: Faculty Notes: Automicity: Automicity states that either all the data modifications are performed aor none of them are performed. Consistency : Consistency is a state in which all the data is in a consistent state after transaction is completed successfully All the rules in a relational database must be applied to the transaction modifications to maintain complete data integrity Isolation : If two transaction are in progress at once for example two users at different computers might be modifying the same table the transaction is isolated from the other. Durability : Durability states that any changes in data by a completed transaction remains permanently in effect in system Hence ,any change in data due to a completed transaction persists even in the event of a system failure This is ensured by the concept of backing up and restoring transaction logs.
  • #15: Faculty Notes: Review the points on this slide.
  • #17: Faculty Notes :
  • #19: Faculty Notes: Table is an object in the database. A table is collection of rows and columns associated with individual data item. For the above syntax : table_name - The name of the new table. Table names must comply with the rules for identifiers. The table_name must be unique within the database. A table_name can contain a maximum of 128 characters. column_name - The name of a column in the table. Column names must comply with the rules for identifiers and must be unique in the table. data_type - Specifies the column data type. DEFAULT- Specifies the value provided for the column when a value is not explicitly supplied during an insert action. DEFAULT definitions can be applied to any column, except those defined by the IDENTITY property. DEFAULT definitions are removed when the table is dropped. A constant value can be used as a default. IDENTITY - Indicates that the new column is an identity column. When a new row is added to the table, SQL Server Compact Edition provides a unique, incremental value for the column. Identity columns are generally used in conjunction with PRIMARY KEY constraints to serve as the unique row identifier for the table. The IDENTITY property can be assigned only to int columns. Only one identity column can be created per table. Bound defaults and DEFAULT constraints cannot be used with an identity column. You must specify both the seed and increment or neither. If neither is specified, the default is (1,1). seed - The value used for the first row that is loaded into the table. increment - The incremental value added to the identity value of the previous row that is loaded. ROWGUIDCOL - Indicates that the new column is a row global unique identifier column. Only one uniqueidentifier column per table can be designated as the ROWGUIDCOL column. The ROWGUIDCOL property can be assigned only to a uniqueidentifier column. ROWGUIDCOL automatically generates values for new rows inserted into the table. CONSTRAINT - An optional keyword indicating the beginning of a PRIMARY KEY , UNIQUE , or FOREIGN KEY constraint definition. Constraints are special properties that enforce data integrity and create special types of indexes for the table and its columns. constraint_name - The name of a constraint. The constraint_name is optional and must be unique within a database. If a constraint_name is not specified, SQL Server Compact Edition generates a constraint name. NULL | NOT NULL - Keywords that specify whether null values are permitted in the column. NULL is not strictly a constraint but can be specified in the same manner as NOT NULL . PRIMARY KEY - A constraint that enforces entity integrity for a particular column or columns using a unique index. Only one PRIMARY KEY constraint can be created per table. UNIQUE - A constraint that provides entity integrity for a particular column or columns using a unique index. Columns in a UNIQUE constraint can be NULL , but only one NULL value is allowed per column. A table can have multiple UNIQUE constraints. Note: SQL Server Compact Edition can use indexes to enforce PRIMARY KEY and UNIQUE constraints. We recommend that you do not rely on this behavior nor try to modify any indexes that are created as part of a constraint. FOREIGN KEY...REFERENCES -A constraint that provides referential integrity for the data in the column. FOREIGN KEY constraints require that each value in the column exists in the specified column in the referenced table. ref_table - The name of the table referenced by the FOREIGN KEY constraint. ( ref_column [ ,... n ] ) - A column, or list of columns, from the table referenced by the FOREIGN KEY constraint. ON DELETE {CASCADE | NO ACTION} , Specifies what action happens to a row in the table that is created when that row has a referential relationship and the referenced row is deleted from the parent table. The default is NO ACTION . If CASCADE is specified, a row is deleted from the referencing table when the corresponding referenced row is deleted from the parent table. If NO ACTION is specified, SQL Server Compact Edition returns an error and the delete action on the referenced row in the parent table is rolled back. ON UPDATE {CASCADE | NO ACTION} Specifies what action happens to a row in the table that is created when that row has a referential relationship, and the referenced row is updated in the parent table. The default is NO ACTION . If CASCADE is specified, the row is updated in the referencing table when the corresponding referenced row is updated in the parent table. If NO ACTION is specified, SQL Server Compact Edition returns an error and the update action on the referenced row in the parent table is rolled back. column - A column or list of columns, in parentheses, used in table constraints to indicate the columns used in the constraint definition.
  • #20: Faculty Notes : In the above example, Dbo – schema/owner of the database
  • #28: Faculty Notes : Insert the following records in the given order : insert into emp values (1,&apos;sss&apos;,1,getdate(),1) insert into dept values (1,‘ LKM’ , ’MDC &apos;) insert into emp values (1,&apos;sss&apos;,1,getdate(),1)
  • #30: Faculty Notes : Like operator is using 8 characters. You can drop the rule with following command Drop rule sapid
  • #31: Faculty Notes : We are inserting partial date in the above query.
  • #33: Faculty Notes: The INSERT statement allows you to insert a single record or multiple records into a table.
  • #34: Faculty Notes: Note that the order of the values should correspond to the order of the columns.
  • #35: Faculty Notes: This is like a Bulk insert. Demo an INSERT statement in SQL Query Analyzer
  • #36: Faculty Notes: Define UPDATE The UPDATE statement is used to modify the data in a table. Is used to update one or more columns in a row
  • #37: Faculty Notes: The above update statement updates (changes) the Department Id of the employee whose Employee Id is 113 to Department Id 70
  • #38: Faculty Notes: The above Update command uses sub queries to update Department Id and Job Id of the employee The first subquery fetches Department Id value of employee whose Employee Id is 100 and assigns it to Department Id in the Select statement The Second subquery fetches Job Id value of employee whose Employee Id is 200 and assigns it to Job Id in the where clause of the Select statement Note: In sub queries always remember the select statement for the sub query should generate only one row of one column i.e. a single value
  • #39: Faculty Notes: Define DELETE The DELETE statement is used to delete rows in a table. Is used to delete one or more rows NOTE: Be cautious while using this statement as this may delete all records from a table accidentally, especially without the WHERE condition.
  • #40: Faculty Notes: The above Delete statement will delete employee whose employee Id is 113
  • #41: Faculty Notes: The above Delete statement is using a sub query to delete records from employee table It deletes employees of Dept Id whose value is generated from the sub query for the Department Type ‘CST’ Note: In sub queries always remember the select statement for the sub query should generate only one row of one column i.e. a single value
  • #42: Faculty Notes: Review the key points on the slide. The key points should be used to summarize the content covered throughout this presentation.