Вы находитесь на странице: 1из 10

Demo

Familiariation inside SQL Server management studio (SSMS)


Using DDL Statements
Creation of new script project in SSMS
Create a datebase using he user interface of SSMS
Creation of table
Template of table
Template explorer
Object eplorer Details (F7)
How to create Constraints
DIffernce of index: Index used to make queries faster.
DDL Triggers are used to perform administrative tasks and enforce business rules that affect
databases (e.g.
Module 2: Basic Transact SQL

Creating data
Variables
Operators
Compound

Data Manipulation Language INSERT


Adds one or more new rows to a table or a vie
For tables with an identity column, it is not required to place the field name in the INSERT
statement not unless you force it
INSERT without IDENTUTY: for example th column name StudentId is IDENTITY so it will not be
Included in the query
INSERT INTO Student
(LastName, FirstName, MiddleInitial, BIthDate, Home Address, ClubMemberID)
VALUES (TYm,Mark,m ,H,
UPDATE
Changes exiting data in one or more columns in a table or view
To update description of a particular record in the Diagnosis table
UPDATE Subject
SET Cost = 312.00
WHERE
DELETE
Removes rows from a table or view
To delete ALL CONTENTS of a table without WHERE clause
DELETE Subject
TO delete with a WHERE condition (FROM Clause is optional)
DELETE FROM Subject
WHERE SubjectID =999
DELETE
Ways to remove records in the table:
DELETE
Is a logged operation that stores transacton in the LOG file of the dbase (row-by-row
logging)

DELETE[FROM]Subject

Truncate Table
Performs minimal logging and re-sets the IDENTITY of the table. It is also faster than DELETE
because it uses fewer resources
TRUNCATE TABLE Subject
DEMO
Inserting data to tables
Updating data in tables
Deleting data from tables
Filtering using EXISTS/NOT EXISTS
-takes the subquery as its own parameter. If the subquery matches with the outer query then it
returns true, otherwise false(no record will show)
SELEC H.First
Day 3: Joints
Mod 4: Querying Multiple Tables by using joins
Primary key and foreign key used to reference
Duplicate foreign key
Automatically Created index when using primary key clustered
Always put first clustered before non-clustered
Intro to joins
Inner join
Outer join
Self join
Cross join
Joins- tables are combined using joins depending on how they are related to each other (e.g. key)
Categories of joins
Inner join uses a comparison operator like = or <> to match rows from two tables based
on the values in common columns from each table. *
Outer join- returns result
Inner join runs faster than outer joins as it only returns matching rows two or more tables.
Ex.
To list the Health Plan and Full Name of enrollees whose first name starts with David
SELECT contains assignment operator =
SELECT E.FIrstName
, E.MiddleName
,E. LastName
,HP.HealthPlanDescription
FROM Enrollee E
INNER JOIN HealthPlan HP
ON E.HealthPlanID = HP.HealthPlanID
WHERE (E.FirstName LIKE David%)
OUTER JOIN
Outer joins return all rows from at least one of the tables or views mentioned in the FROM clause

Left out join when a row in the left table has no matching rows in the right table, the associated
result set row contains null values for all select list columns coming from the right table.
Ex.
SELECT L.Column1
,R.Column2
FROM LEFTTABLE L
LEFT JOIN RIGHTTABLE R
ON L.ID=R.ID
Right outer join is the reverse
FULL OUTER JOIN returns all rows in both the left and right tables. Any time a row has no match
in the other table, the select list columns from the other table contain null values. When there is a
match between the tables, the entire result set row contains data values from the base tables.
Ex.
SELECT L.Column1
, R.Columns2
FROM LEFTTABLE L
FULL JOIN RIGHTTABLE R
ON L.ID =R.ID

Degrades performance of servers- joins


Relational database- speeds up updates, drawback updates all rows not

Outer join- slower than inner join


Self join calls for a table joining itself therefore you are referencing it to its twin table
Ex.
SELECT S.StudentId AS ClubLeaderId
, S.FirstName AS ClubLeader
, S2.StudentId AS MemberId
, S2.LastName AS Member
FROM Student S
JOIN Student S2
ON S.StudentId=S2.ClubMemberId

Cross join does not have a HWERE clause; produces the Cartesian product of the tables
involved in the join. The size of a Cartesian product result set is the numer of rows in the
first table multiplied by the number of rows in the second table.
Be careful using this type of JOIN as this may lead to a serious performance problems 9i.e.
slow running queries, bottleneck)

Ex.
SELECT F.FacilityId
, FT.FacilityTypeDesc
FROM Facility F
CROSS JOIN FacilityType FT
FULL OUTER JOIN

DEMO

SUB.Description subject
S.FirstName Student
INSERT TABLE NAME correct
Delete table correct
Left join and left outer join the same
Full join and full outer join same
Orphan records no relationship

Module 5: Case, Set Operators, Subqueries, Temporary tables


Temporary tables- temporary processing
- Process result set
Case
Set operators
subqueries
Temporary tables
Table variables
Case evaluates a list of conditions and returns one of multiple possible result expressions
Ex.
SELECT
FirstName + + LastName
AS EnrolleeName
, CASE Gender
WHEN F THEN Female
WHEN M THEN Male
Else Unknown
END AS Gender
, Age
FROM Enrollee
Set operators combine results from two or more queries into a single result set
- Union joins two result sets into one. Both result sets should have the same column data
types and count for efficiency.
UNION ALL displays duplicates
UNION selects all distinct record of all result set
Ex.
SELECT Firstname,
Lastname
FROM Household
WHERE Gender = M

UNION
SELECT Firstname,
Lastname

FROM Dependent
WHERE Gender = M
Ex.
SELECT Firstname,
Lastname
FROM Household
WHERE Gender = M
UNION ALL
SELECT Firstname,
Lastname
FROM Dependent
WHERE Gender = M
Set operators growing rows
Joins growing columns
EXCEPT returns any distinct values from the query to the left of the EXCEPT oprand that are not
also returned from the right query
Ex.
SELECT HouseholdId
FROM Household
EXCEPT
SELECT Householdid
FROM Dependent
INTERSECT returns any distinct values that are returned by both the query on the left and right
sides of the INTERSECT operand.
Ex.
SELECT HouseholdId
FROM Household
INTERSECT
SELECT Householdid
FROM Dependent
Subquery is a query that is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or
inside another subquery.

2 types of subquery
1. Scalar
SELECT HH.HouseholdId, HH.Lastname, HH.Firstname,
(SELECT MAX(Dep.DateofBirth)
FROM Dependent Dep

WHERE HH.HouseholdId = Dep.HouseholdId)


AS DepYoungestBdate
FROM Household HH
2. Tabular
SELECT FirstName, LastName, Age
FROM Enrollee
WHER EnrolleeId IN
(SELECT ENrolleeId FROM MedicalClaims)
Correlated Subqueries- is a subquery that contains a reference to a column in the outer query. It
only shows the records matched with the joining fireld of the outer query
Ex.
SELECT EnrolleeId, Lastname, Firstname, Age
FROM Enrollee HH
WHERE Age <
(SELECT MAX(age) DepMaxAge
FROM Enrollee Dep
WHERE HH.EnrolleeId = Dep.HouseholdId)
Try to use JOINS instead of subqueries or correlated. joins slows down
-

SUbqueries occurs in memory so it requires a lot of RAM.


Creating subqueries amy perform heaby loads in the server wherein sometimes you just
needed to break it down to smaller temporary tables.

Temporary tables
When you cfreate queries, sometimes it is needed to be stored in a temp table that needs further
processing
Typical use of temporary tables are for devug purposes or dev stage of your queries
THer are instances that you cannot
2types of temp tables
1. LOCAL (#) visible only to their creators during the same connection to an instance of sql
server as whe the tables were first created or referenced and are deleted after the user
discnoonnects from the instance of SL Server *
Ex. CREATE TABLE #Test (NumID int, Description varchar(20))
2. GLOBAL (##) are visible to any user and nay connection after they are created, and are
deleted when all suers that are referencing the table disconnect from the instance of sql
server
Ex. CREATE TABLE ##Test (NumbID int, Description varchar(20))
Note global temp tables are rarely used

Instance
Temp tables
Warning: it adds bottleneck in the server when you put the result set of your query in this type of
table specially if it holds thouses of data .

You must consider the ff when creating this table:


- Add indexes on the temp tables for large result sets after inserting the data into them
- Limit the number of rows and columns for optimum performance (if not possible, create
indexes)
- Immdediatelydrop the table after all its transaction are finished to free up space and
memory
- Test performance of queries before inserting them to table
Table Variable
- Table variables store a set of records, so naturally the declaration syntax looks vary similar
to a CREATE TABLE statement
- Table var can be used in function, stored procedures, and batches.
- You create a table variable the same way you create any variable: using the declare
statement:
Ex.
DECLARE @TableVar Table ( CustomerID
nchar(5) NOT NULL)
table var provide the benefits:
- Table var behaves like a local var. it has well-defined scope. Is the function,stored
procedure , or batch is declared in.
- Within its scope, a table var can be used like a reg table. It may be applied anywhere a table
or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However,
table cannot be used in the following statement:
SELECT Column1, Column2
INTO @Table_variable
- Table var
-transcio involving table variable last only for the duration of an update on the table var. therefore,
table var require less locking and logging resources
Table var can be referenced by name in the FROM clause of a batch
Ex. SELECT Employee_ID, Department_ID
DEMO
Using case
Using set operators
Using subqueries
<= --- operator
INTERSECT use in isolating data
EXISTS

Mod6: Modifying Data in Tables


Data Manipulation Language (DML)
Transaction

DML INSERT
Adds one or more new rows to a table or view
Not required to place the field name in the INSERT statement not unless you force it
INSERT without IDENTITY:
For example the column name CountryId is IDENTITY so it will not be included in query
INSERT Country (COuntryCd, CountryNm)
VALUES(PH, Philippines)
With forced IDENTITY(COuntryId)value to be inserted
Ex.
SET IDENTITY_INSERT [Country] ON
INSERT INTO [Country] (CountryId, CountryCd, COuntryNm)
SELECT MAX (CountrId) + , PA, PANAMA
FROM [Country]
SET IDENTITY_INSERT [Country] OFF
Output return info from or expressions based on, each row affected by an INSERT, UPDATE,
DELETE statement, Results can be inserted into a table or table variable:
OUTPUT INSERT.[ColumnName]
Ex.
INSERT Treatment (TreatmentID, Description, Additional )
OUTPUT INSERTED.TreatmentID
VALUES(5, Dental Care, Dentist, Orthodontics)
DECLARE @TempInsertRecord Table (TreatmentIDtinyint, Description varchar (100),
AdditionalInformation varchar(100))
INSERT Treatment (TreatmentID, Description, Description, AdditionalInformation)
OUTPUT INSERTED.TreamentID, INSERTED.Description, INSERTED.Additional
UPDATE DML
- Changes existing data in one or more columns in a table
- To update description of a precord in diagnosis table
Ex.
To update with help of two table or more
Using join
UUPDATE F
SET FacilityDescr = Treament Center
FROM Facility F
JOIN FacilityType FT
ON F.FacilityTypeId=FT.FacilityTYpeId
OUTPUT for UPDATE NO UPDATED>[ColumnName]
Uses two operation: deleted (old value) and INSERTED
DML DELTE
Removes rows from table or view

Ex. DELETE Treatment no difference with DELETE FROM Treatment


WHERE Treatment
Ways to remove recor d in table
3. Delete LOGGED OPERATION THAT STORES TRANSACTION IN log FILE OF DBASE (ROW-byrow loggin)
4. DELETE[FROM] Movie
5. Truncate table performs minimal loggin and reset the IDENTITY of table. Also faster than
DELETE because it uses fewer resources
6. Truncate table Movie
Transaction is a single unit of work.
If a transation is successful, all of the data modifications made during the transaction are
committed and become a permanent part of dbase.
Transaction encounters errors and must be canceled or rolled back, then all of the data
modification are erased.
SQL Server operates in following transation modes:
1. Autocommit transaction ex. Activities or exersiceses answered
2. Explicit transaction userdefined or manual
- Server is just preparing transaction
3. Implicit transactions automatic
Autocommit transaction each individual statement is a transaction that is immediately
committed.
Ex.
INSERT Treatment (TreatmentID, Description, AdditionalInformation)
VALUES(5, Rehabilitation
EXPLICIT Transaction each transaction is explicityly started with the BEGIN TRANSACTION
statement and explicity ended with COMMIT or ROLLBACK statement.
Ex.
BEGIN Transaction
INSERT Treatment (TreatmentID,Description, AdditionalInformation
VALUES(5, Rehabilititation, Orthopedic)
COMMIT TRANSACTION [or ROLLBACK TRANSACTION]
Implicit transactions new transaction is implicitly started when the prior transaction completes,
buty each transction is explicityly completed with a COMMIT or ROLLBACK statement
Ex.
SET IMPLICIT_TRANSACTIONS ON;
INSERT Treatment (TreatmentID, Description,
GO- signals the end of a batch of Transact SQL statements to the SQL Server utilities
1. USE HEalthCareCUstom
GO

2. DECLARE @Test varchar (50)


SET @Test = The Last Airbender
SELECT @Test
GO ends execution
SELECT @Test ----error will occur
GO
Best practice when developing queries -

Вам также может понравиться