Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.



Published on

Published in: Education
  • Be the first to comment

  • Be the first to like this


  1. 1. Introduction to SQL Server 2005 Module 2
  2. 2. <ul><li>Introduction to Database Engine </li></ul><ul><li>Concepts of Database </li></ul><ul><li>Concepts of Tables </li></ul><ul><li>Data Integrity & Its implementation </li></ul><ul><li>Constraints </li></ul><ul><li>Introduction to Rules & Defaults </li></ul><ul><li>DML Commands </li></ul><ul><ul><li>Insert </li></ul></ul><ul><ul><li>Update </li></ul></ul><ul><ul><li>Delete </li></ul></ul>Learning Objectives
  3. 3. <ul><li>At the end of this section, you should be able to: </li></ul><ul><li>What is a Database Engine? </li></ul><ul><li>What is a Database & How to create it? </li></ul><ul><li>How to work with Tables? </li></ul><ul><li>What is Data Integrity? </li></ul><ul><li>How is Data integrity implemented? </li></ul><ul><li>Work with Constraints </li></ul><ul><li>Work with Rules & Defaults </li></ul><ul><li>Execute DML Commands </li></ul><ul><ul><li>Insert </li></ul></ul><ul><ul><li>Update </li></ul></ul><ul><ul><li>Delete </li></ul></ul>Module 2 : Agenda
  4. 4. Introduction to Database Engine <ul><li>Database Engine is the core service for storing, processing and securing data. </li></ul><ul><li>It maintains the relationships between the stored data. </li></ul><ul><li>It helps in the translation the data to information. </li></ul><ul><li>It provides controlled access- While logging in SQL Server Management studio, we can select the server type as database engine. </li></ul><ul><li>It facilitates rapid transaction processing to meet the requirements of the most demanding data consuming applications within the enterprise. </li></ul><ul><li>The Database Engine provides rich support for sustaining high availability. </li></ul>
  5. 5. <ul><li>The SQL Server Database stores the data pertaining to a particular Business. </li></ul><ul><li>Each SQL Server has two types of Databases. </li></ul><ul><ul><li>System Databases (master,model,tempdb,msdb) </li></ul></ul><ul><ul><li>User Databases (pubs, northwind, and databases specific to an application or a business) </li></ul></ul><ul><li>SQL Server uses T-SQL statements to work with databases like storing, maintaining and querying. </li></ul>Introduction to SQL Server Database
  6. 6. Overview of Database Objects <ul><li>SQL Server Database contains the following objects </li></ul><ul><ul><li>Tables </li></ul></ul><ul><ul><li>Views </li></ul></ul><ul><ul><li>Indexes </li></ul></ul><ul><ul><li>Stored Procedures </li></ul></ul><ul><ul><li>User Defined Functions </li></ul></ul><ul><ul><li>Rules </li></ul></ul><ul><ul><li>Defaults </li></ul></ul><ul><ul><li>User Defined Data Types </li></ul></ul>
  7. 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. 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. 9. Database Files <ul><ul><li>Database files help in administrative tasks such as backup and restore operations. </li></ul></ul><ul><ul><li>There are two types of database files: </li></ul></ul><ul><ul><li>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. </li></ul></ul><ul><ul><li>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. </li></ul></ul>
  10. 10. Structured Query Language <ul><li>SQL is a high level language </li></ul><ul><li>Developed by IBM in late 1970’s </li></ul><ul><li>SQL has 4 sublanguages : </li></ul>REVOKE GRANT DCL DELETE SAVEPOINT UPDATE DROP ROLLBACK INSERT ALTER COMMIT SELECT CREATE TCL DML DDL
  11. 11. Data Definition Language (DDL) <ul><li>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. </li></ul><ul><li>The set of relations in a database must be specified to the system by means of data definition language. </li></ul><ul><li>Database schema is specified by a set of definitions expressed by a data-definition language. </li></ul>
  12. 12. Data Manipulation Language (DML) <ul><li>It is a language that enables users to access or manipulate data as organized by the appropriate data model. </li></ul><ul><li>DML Manipulation commands are the most frequently used SQL commands. </li></ul><ul><li>They are used to manipulate the data of the existing objects like tables. </li></ul>
  13. 13. Transaction Control Language(TCL) <ul><li>We can use SQL to control transactions. </li></ul><ul><li>Transactions are </li></ul><ul><ul><li>Collection of operations that form a single logical unit of work. </li></ul></ul><ul><ul><li>All changes made to the database can be referred to as a Transaction. </li></ul></ul><ul><ul><li>Transaction changes can be made permanent to a database only if they are committed. </li></ul></ul><ul><ul><li>Transactions operations executed between the begin and end of the Transaction . </li></ul></ul><ul><li>A Transaction can be defined as a Sequence of operations performed together as a Single logical unit of work. </li></ul><ul><li>A single unit of work must possess the four properties called ACID. </li></ul><ul><ul><ul><li>Automicity </li></ul></ul></ul><ul><ul><ul><li>consistency </li></ul></ul></ul><ul><ul><ul><li>Isolation </li></ul></ul></ul><ul><ul><ul><li>Durability </li></ul></ul></ul>
  14. 14. Guidelines in writing SQL Statements <ul><li>SQL statements are not case-sensitive </li></ul><ul><li>SQL statements can be on one or more lines </li></ul><ul><li>SQL statements are optionally ended with a semicolon </li></ul><ul><li>Keywords cannot be abbreviated or split across lines </li></ul><ul><li>Clauses are usually placed on separate lines </li></ul><ul><li>Indents are used to enhance readability </li></ul><ul><li>Keywords are typicall y entered in uppercase; all other words such as table name and columns are entered in Pascal case </li></ul>
  15. 15. Transact- SQL <ul><li>SQL Server uses T-SQL and MySQL Languages </li></ul><ul><li>T-SQL is an extension of SQL. For instance: </li></ul><ul><ul><li>Summary calculation </li></ul></ul><ul><ul><li>Stored Procedures </li></ul></ul><ul><ul><li>Exception Handling </li></ul></ul><ul><ul><li>User Defined Functions </li></ul></ul><ul><ul><li>Triggers </li></ul></ul><ul><ul><li>Cursors </li></ul></ul><ul><li>A SQL command execution returns the number of rows affected. </li></ul>
  16. 16. To Create & Use Database <ul><li>Database creation syntax : </li></ul><ul><ul><ul><ul><li>Create database <Database_Name> </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Go </li></ul></ul></ul></ul><ul><li>Example: </li></ul><ul><ul><ul><ul><li>Create database MyDB </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Go </li></ul></ul></ul></ul><ul><li>Use database syntax: </li></ul><ul><ul><ul><ul><li>Use database <Database_Name> </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Go </li></ul></ul></ul></ul><ul><li>Example : </li></ul><ul><ul><ul><ul><li>Use MyDB </li></ul></ul></ul></ul><ul><ul><ul><ul><li>go </li></ul></ul></ul></ul>
  17. 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. 18. Create Tables Syntax : <ul><li>CREATE TABLE table_name( </li></ul><ul><li>{< column_definition >|< table_constraint >}[ ,...n ]) </li></ul><ul><li><column_definition>::={columnname datatype}[{ DEFAULT constant_expression | [IDENTITY[( seed,increment)]]}] [ROWGUIDCOL][<column_constraint>[ ...n ] ] </li></ul><ul><li><column_constraint>::=[CONSTRAINT constraint_name] </li></ul><ul><li>{[NULL|NOT NULL]|[PRIMARY KEY|UNIQUE]|REFERENCES ref_table[(ref_column)][ON DELETE {CASCADE|NO ACTION}][ON UPDATE {CASCADE|NO ACTION}]} </li></ul><ul><li><table_constraint>::=[CONSTRAINT constraint_name] </li></ul><ul><li>{[{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}]} </li></ul>
  19. 19. Create Table - Example <ul><li>CREATE TABLE [Categories]( </li></ul><ul><li>[CategoryID] [int], </li></ul><ul><li>[CategoryName] [nvarchar](15), </li></ul><ul><li>[Description] [ntext], </li></ul><ul><li>CONSTRAINT [PK_Categories] PRIMARY KEY </li></ul><ul><li>( </li></ul><ul><li>[CategoryID] ASC </li></ul><ul><li>) ) </li></ul>
  20. 20. Delete Table <ul><li>Table Deletion Syntax: </li></ul><ul><ul><ul><ul><li>drop table <table_name> </li></ul></ul></ul></ul><ul><li>Table deletion Example </li></ul><ul><ul><ul><ul><li>drop table categories </li></ul></ul></ul></ul>
  21. 21. Data Integrity <ul><li>Data integrity refers to the correctness and completeness of data within a database. </li></ul><ul><li>To enforce this we restrict the data values that users can insert, delete or update in the database. </li></ul><ul><li>T-SQL mechanisms to enforce data integrity: </li></ul><ul><ul><li>Rules </li></ul></ul><ul><ul><li>Defaults </li></ul></ul><ul><ul><li>Indexes </li></ul></ul><ul><ul><li>Triggers </li></ul></ul><ul><li>These mechanisms satisfy: </li></ul><ul><ul><li>No null value requirement </li></ul></ul><ul><ul><li>Check validity of the data entered </li></ul></ul><ul><ul><li>Uniqueness of the data </li></ul></ul><ul><ul><li>Referential integrity </li></ul></ul>
  22. 22. Type of Constraints <ul><li>Not Null </li></ul><ul><li>Check </li></ul><ul><li>Unique </li></ul><ul><li>Primary Key </li></ul><ul><li>Referential Integrity Constraint (Foreign Key) </li></ul>
  23. 23. Constraint – Not Null <ul><li>Null is not Zero or a blank </li></ul><ul><li>Null implies no entry or value unknown </li></ul><ul><li>We identify columns which accept null and which should not be null. </li></ul><ul><li>Create table with Not Null constraint : </li></ul><ul><ul><ul><li>CREATE TABLE [Categories]( </li></ul></ul></ul><ul><ul><ul><li>[CategoryID] [int] NOT NULL, </li></ul></ul></ul><ul><ul><ul><li>[CategoryName] [nvarchar](15) NOT NULL </li></ul></ul></ul><ul><ul><ul><li>) </li></ul></ul></ul>
  24. 24. Constraint – Check <ul><li>Check constraint limits the values of data inserted into columns. </li></ul><ul><li>This constraint is useful for applications that check a limited and specific range of values. </li></ul><ul><li>We use Check constraint for the data integrity when specific values are to be checked. </li></ul><ul><li>It’s a condition that the value must pass before it is inserted into the table. The search condition includes : </li></ul><ul><ul><li>With IN a list of constant expressions </li></ul></ul><ul><ul><li>With BETWEEN a range of constant expressions </li></ul></ul><ul><ul><li>With LIKE wild characters </li></ul></ul>
  25. 25. Constraint – Check (Continued) <ul><li>Example : </li></ul><ul><ul><ul><li>create table mytab( </li></ul></ul></ul><ul><ul><ul><li>[id] char(4) check (id in ('1234','5432','6000') </li></ul></ul></ul><ul><ul><ul><li>or id like '60[0-9][0-9]'), </li></ul></ul></ul><ul><ul><ul><li>[name] varchar(10)) </li></ul></ul></ul><ul><li>After creating this table issue the following commands : </li></ul><ul><ul><ul><li>insert into mytab values ('1234','sss') </li></ul></ul></ul><ul><ul><ul><li>insert into mytab values ('1233','sss') </li></ul></ul></ul><ul><ul><ul><li>insert into mytab values ('6034','sss') </li></ul></ul></ul>
  26. 26. Constraint – Unique <ul><li>Unique Constraint ensures no duplication of values in the rows for the constraint applied column. </li></ul><ul><li>This constraint creates unique indexes to enforce data integrity. </li></ul><ul><li>Example : </li></ul><ul><ul><ul><ul><li>create table uniqueconstraint </li></ul></ul></ul></ul><ul><ul><ul><ul><li>( </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[id] char(4), </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[name] varchar(20), </li></ul></ul></ul></ul><ul><ul><ul><ul><li>date datetime, </li></ul></ul></ul></ul><ul><ul><ul><ul><li>unique clustered (id,[name])) </li></ul></ul></ul></ul><ul><li>Issue the following commands to insert data </li></ul><ul><ul><ul><ul><li>insert into uniqueconstraint values ('1214','ss',getdate() ) </li></ul></ul></ul></ul>
  27. 27. Constraint – Primary & Foreign Key <ul><li>Primary Key constraint behaves like Unique Constraint – difference is it applies Not NULL constraint as well. </li></ul><ul><li>Foreign key constraint or referential integrity refers to the methods used to manage the relationships between tables. </li></ul><ul><li>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. </li></ul><ul><li>Three types of references: </li></ul><ul><ul><li>References to another table </li></ul></ul><ul><ul><li>References from another table </li></ul></ul><ul><ul><li>Self reference. </li></ul></ul>
  28. 28. Constraint – Primary & Foreign Key <ul><li>Example : </li></ul><ul><ul><ul><ul><li>CREATE TABLE Dept( </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[DeptNo] [int] primary key, </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[Dname] [nchar](10), </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[Location] [nchar](10)) </li></ul></ul></ul></ul><ul><ul><ul><ul><li>CREATE TABLE [Emp]( </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[EmpNo] [int] primary key, </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[Ename] [nchar](10) , </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[MgrId] [int], </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[DOJ] [datetime] , </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[DeptNo] [int] references Dept(DeptNo)) </li></ul></ul></ul></ul><ul><li>Insert the following records in the given order : </li></ul><ul><ul><ul><ul><ul><li>insert into emp values (1,'sss',1,getdate(),1) </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>insert into dept values (1, ’LKM’ , ’MDC ') </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>insert into emp values (1,'sss',1,getdate(),1) </li></ul></ul></ul></ul></ul>
  29. 29. Rules <ul><li>A Rule lest the user specify what can or can not be entered into a particular column. </li></ul><ul><li>To Create a rule </li></ul><ul><ul><li>Create Rule </li></ul></ul><ul><ul><li>Bind the rule to a column by using sp_bindrule. </li></ul></ul><ul><ul><li>Test the rule by inserting data. </li></ul></ul><ul><li>Example: </li></ul><ul><ul><ul><li>create rule sapid as @id like ’1_ _ _ _ _ _ _’ </li></ul></ul></ul><ul><ul><ul><li>sp_bindrule sapid, ‘emp.empno’ </li></ul></ul></ul><ul><ul><li>insert into emp values (1234568,'sss',1,getdate(),1) </li></ul></ul><ul><ul><li>insert into emp values (123456 7 8,'sss',1,getdate(),1) </li></ul></ul>
  30. 30. Defaults <ul><li>Default is a values that is automatically inserted if the used does not enter any data. </li></ul><ul><li>To create a Default: </li></ul><ul><ul><li>Define the default </li></ul></ul><ul><ul><li>Bind the default to desired table column using sp_bindefault </li></ul></ul><ul><ul><li>Test the bound default by inserting data. </li></ul></ul><ul><li>Example </li></ul><ul><ul><ul><ul><li>create default location as 'unknown' </li></ul></ul></ul></ul><ul><ul><ul><ul><li>sp_bindefault location, 'dept.location' </li></ul></ul></ul></ul><ul><ul><ul><ul><li>insert into dept(deptno,dname) values (2,'HR') </li></ul></ul></ul></ul><ul><ul><ul><ul><li>select * from dept </li></ul></ul></ul></ul>
  31. 31. Working with IDENTITY column <ul><li>Identity column contains a value for each row, generated automatically, that uniquely identifies the row with the table. </li></ul><ul><li>Identity columns can not be updated and also don't allow nulls. </li></ul><ul><li>Identity columns must have a numeric datatype. </li></ul><ul><li>Example : </li></ul><ul><ul><ul><ul><li>CREATE TABLE [idcheck]( </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[id] [int] IDENTITY(1,1) primary key, </li></ul></ul></ul></ul><ul><ul><ul><ul><li>[name] [nchar](10) </li></ul></ul></ul></ul><ul><ul><ul><ul><li>) </li></ul></ul></ul></ul><ul><ul><ul><ul><li>INSERT INTO [idcheck] ([name]) VALUES ('aaa') </li></ul></ul></ul></ul><ul><li>*Note the value is automatically inserted in id column </li></ul>
  32. 32. INSERT Statement <ul><li>INSERT INTO <table> </li></ul><ul><li>[ (column </li></ul><ul><li>[, column…] ) ] </li></ul><ul><li>VALUES (value </li></ul><ul><li>[, value…] ) </li></ul>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. 33. INSERT Statement (Continued) <ul><li>Inserts a new row containing values for each column </li></ul><ul><li>In Insert clause, list values in the default order of the columns in the table </li></ul><ul><li>Listing of column names is optional, provided you specify all values of ALL columns in correct order corresponding to the table design </li></ul><ul><li>Enclose character and date values within single quotation marks </li></ul><ul><ul><li>INSERT INTO Departments (DepartmentId, </li></ul></ul><ul><ul><li>DepartmentName, CurrentDate) </li></ul></ul><ul><ul><li> VALUES ( 70, </li></ul></ul><ul><ul><li> ‘ Public Relations’, </li></ul></ul><ul><ul><li>‘ 10-OCT-04’) </li></ul></ul>
  34. 34. Inserting Rows from Another Table <ul><li>Write your INSERT statement with a subquery </li></ul><ul><li>Do not use the VALUES clause </li></ul><ul><li>Match the number of columns in the INSERT clause to those in the subquery </li></ul><ul><ul><li>INSERT INTO SalesReps ( Id, </li></ul></ul><ul><ul><li>Name, </li></ul></ul><ul><ul><li>Salary) </li></ul></ul><ul><ul><li> SELECT EmployeeId, </li></ul></ul><ul><ul><li> LastName, </li></ul></ul><ul><ul><li> Salary </li></ul></ul><ul><ul><li>FROM Employees </li></ul></ul><ul><ul><li>WHERE JobId LIKE ‘%REP%’ </li></ul></ul>
  35. 35. UPDATE Statement <ul><li>UPDATE table </li></ul><ul><li>SET column = value </li></ul><ul><li> [,column = value, …] </li></ul><ul><li>[WHERE condition] </li></ul>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. 36. <ul><li>Specific row or rows are modified if you specify the WHERE clause </li></ul><ul><li>All rows in the table are modified if you omit the WHERE clause </li></ul>Updating Rows in a Table update dept set deptno=10 where location= ‘ unknown ’
  37. 37. <ul><li>Use sub queries in UPDATE statements to update rows in a table based on values from another table </li></ul>Updating Rows Based on Another Table <ul><ul><li>UPDATE CopyEmp </li></ul></ul><ul><ul><li>SET DepartmentId = ( SELECT DepartmentId </li></ul></ul><ul><ul><li> FROM Employees </li></ul></ul><ul><ul><li> WHERE EmpId =100) </li></ul></ul><ul><ul><li>WHERE JobId = ( SELECT JobId </li></ul></ul><ul><ul><li> FROM Employees </li></ul></ul><ul><ul><li> WHERE EmpId = 200) </li></ul></ul>
  38. 38. DELETE Statement <ul><li>DELETE [FROM] table </li></ul><ul><li>[WHERE condition] </li></ul>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. 39. <ul><li>A specific row or specific rows are deleted if you specify the WHERE clause </li></ul><ul><li>All rows in the table are deleted if you omit the WHERE clause </li></ul>Deleting Rows in a Table Delete from dept where deptno=10
  40. 40. <ul><li>Use sub queries in DELETE statements to delete rows in a table based on values from another table </li></ul>Deleting Rows Based on Another Table <ul><ul><li>DELETE FROM Employees </li></ul></ul><ul><ul><li>WHERE DeptId = ( SELECT DeptId </li></ul></ul><ul><ul><li> FROM Departments </li></ul></ul><ul><ul><li> WHERE DeptType = ‘CST’) </li></ul></ul>
  41. 41. Key Points <ul><li>SQL is an industry standard language for updating to, and getting information from, a database. </li></ul><ul><li>The basic and most common SQL statements are: SELECT, INSERT, UPDATE, DELETE. </li></ul>
  42. 42. Questions & Comments