Академический Документы
Профессиональный Документы
Культура Документы
Creating data
Variables
Operators
Compound
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
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
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
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 .
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