 Developed in the early 1970 (SEQual)
 ANSI-SQL defined by the American National Standards
Institute
 Microsoft implementation is T-SQL, or Transact SQL
 Other implementations include PL/SQL and IBM’s SQL
Procedural Language.
 DML – Data Manipulation Language
 DCL – Data Control Language
 DDL – Data Definition Language
 TCL - Transactional Control Language
 DQL - Data Query Language (Select)
A data type determines the type of data that can be stored in a
database column. The most commonly used data types are:
1. Alphanumeric: data types used to store characters, numbers, special
characters, or nearly any combination.
2. Numeric
3. Date and Time
Executing queries occurs when in a query session by:
Selecting the Execute Icon
Pressing the F5 key
Note:
Select the Database Before Executing Query or write
Use Keyword + DB Name on top of the Query
• The use of a beginning /* and ending */ creates comments
• The double dash comments to the end of line
/*
This is a comment
*/
--This is a comment
• Comments are statements about the meaning of the code
• When used, there is no execution performed on the text
There are two ways to comment code using T-SQL:
 Recall that a batch is a series of one or more
statements submitted and executed at the
same time
 Example:
delete sales
where stor_id = "5023"
and ord_num = "AB-123-DEF-425-1Z3"
delete salesdetail
where stor_id = "5023"
and ord_num = "AB-123-DEF-425-1Z3"
select * from sales
where stor_id = "5023"
select * from salesdetail
where stor_id = "5023"
go
Data Definition Language
 Create Table
 Alter Table
 Drop Table
CREATE TABLE [table_name]
("column 1" "data_type",
"column 2" "data_type", ... )
Syntax:
Example
CREATE TABLE Employee
(ID int Primary Key,
FName char(50) Not Null,
LName char(50),
Address char(50),
Birth_Date date);
Drop Table “Table_Name”
Syntax:
Example
Drop Table Employee
ALTER TABLE table_name ADD column_name datatype
ALTER TABLE table_name DROP column_name
Syntax:
Example
ALTER TABLE employee ADD City varchar(30)
Modifying Data in Tables
 Inserting Data into Tables
 Deleting Data from Tables
 Updating Data in Tables
INSERT [INTO] table_or_view [(column_list)] data_values
• The INSERT statement adds one or more new rows to a table
• INSERT inserts data_values as one or more rows into the specified
table_or_view
• column_list is a list of column names used to specify the columns for
which data is supplied
INSERT Syntax:
Using a Simple INSERT Statement
INSERT INTO Production.UnitMeasure
VALUES (N'F2', N'Square Feet', GETDATE());
INSERT INTO Production.UnitMeasure
VALUES (N'F2', N'Square Feet', GETDATE()),
(N'Y2', N'Square Yards', GETDATE());
Inserting Multiple Rows of Data (Row Constructor)
INSERT INTO MyTable (PriKey, Description)
SELECT ForeignKey, Description
FROM SomeView
INSERT dbo.SomeTable
EXECUTE SomeProcedure ”predefined procedure”
INSERT using SELECT
INSERT using EXECUTE
DELETE table_or_view
FROM table_sources
WHERE search_condition
• The DELETE statement removes one or more rows in a table or view
• DELETE removes rows from the table_or_view parameter that meet
the search condition
• table_sources can be used to specify additional tables or views that
can be used by the WHERE clause
DELETE Syntax:
DELETE FROM SomeTable;
DELETE FROM SomeTable
WHERE SomeColumn IN
(Subquery Definition);
DELETE with no WHERE clause
DELETE using a Subquery
DELETE FROM Sales.SalesPerson;
DELETE FROM
Sales.SalesPersonQuotaHistory
WHERE SalesPersonID IN
(SELECT SalesPersonID
FROM Sales.SalesPerson
WHERE SalesYTD >
2500000.00);
TRUNCATE TABLE HumanResources.JobCandidate;
TRUNCATE TABLE
[ { database_name.[ schema_name ]. | schema_name . } ]
table_name
[ ; ]
You cannot use TRUNCATE TABLE on tables that
are referenced by a FOREIGN KEY constraint
TRUNCATE TABLE Syntax
TRUNCATE TABLE Example
• Fewer locks are typically used
• Less transaction log space is used
TRUNCATE TABLE has the following advantages over DELETE:
DELETE FROM Sales.SalesPerson;
TRUNCATE TABLE Sales.SalesPerson;
UPDATE table_or_view
SET column_name = expression
FROM table_sources
WHERE search_condition
• The UPDATE statement changes data values in one, many, or all
rows of a table
• An UPDATE statement referencing a table or view can change the
data in only one base table at a time
• UPDATE has three major clauses:
• SET – comma-separated list of columns to be updated
• FROM – supplies values for the SET clause
• WHERE – specifies a search condition for the SET clause
UPDATE Syntax:
UPDATE SomeTable
SET Column = Value
UPDATE SomeTable
SET Column = Value
WHERE SearchExpression
Simple UPDATE Statement
UPDATE with a WHERE clause
UPDATE Sales.SalesPerson
SET Bonus = 6000;
UPDATE Production.Product
SET Color = N’Metallic Red’
WHERE Name LIKE N’Road-250%’
AND Color = N’Red’;
UPDATE Sales.SalesPerson
SET Bonus = Bonus * 2;
UPDATE SomeTable
SET Column = Value
FROM SomeSubquery
UPDATE using a Subquery
UPDATE Sales.SalesPerson
SET SalesYTD = SalesYTD + SubTotal
FROM Sales.SalesPerson AS sp
JOIN Sales.SalesOrderHeader AS so
ON sp.BusinessEntityID = so.SalesPersonID
AND so.OrderDate = (SELECT MAX(OrderDate)
FROM Sales.SalesOrderHeader
WHERE SalesPersonID =
sp.BusinessEntityID);
SalesYTD
--------------
677558.4653
4557045.0459
Before
SalesYTD
--------------
721382.488
4593234.5123
After
Data Query Language
25
 Used for queries on single or multiple tables
 Clauses of the SELECT statement:
 SELECT
 List the columns (and expressions) that should be returned from the query
 FROM
 Indicate the table(s) or view(s) from which data will be obtained
 WHERE
 Indicate the conditions under which a row will be included in the result
 GROUP BY
 Indicate columns to group the results
 HAVING
 Indicate the conditions under which a group will be included
 ORDER BY
 Sorts the result according to specified columns
26
SQL statement processing
order
Displays All Columns in the Employee Table
USE AdventureWorks2012;
GO
SELECT *
FROM HumanResources.Employee
Displays Only FirstName, LastName and JobTitle Columns
USE AdventureWorks2012;
GO
SELECT FirstName, LastName, JobTitle
FROM HumanResources.Employee
 Retrieving Specific Rows in a Table
 Filtering Data by Using Comparison Operators
 Filtering Data by Using String Comparisons
 Filtering Data by Using Logical Operators
 Retrieving a Range of Values
 Retrieving a List of Values
Simple WHERE clause
WHERE Clause Using a Predicate
USE ITI;
GO
SELECT *
FROM Student
WHERE Age >20
USE ITI;
GO
SELECT *
FROM Instructor
WHERE Salary IS NULL;
Type Operators
• Arithmetic operators
• +, -, *, /, %
Vacation + SickLeave AS 'Total PTO'
• Assignment operator
• =
SET @MyCounter = 1
• Comparison operators
• =, <, >, <>, !, >=, <=
IF (@MyProduct <> 0) …
• Logical operators
• AND, OR, NOT
WHERE Department = ‘Sales' AND
(Shift = 'Evening' OR Shift = 'Night')
• String concatenation
operator
• +
SELECT LastName + ', ' + FirstName
AS Moniker
 Comparison operators test whether two expressions are the
same.
 Comparison operators return a Boolean value of TRUE,
FALSE, or UNKNOWN.
Scalar Comparison Operators
=, <>, >, >=, <, <=, !=
USE AdventureWorks2012;
GO
SELECT FirstName, LastName, MiddleName
FROM Person.Person
WHERE ModifiedDate >= ‘01/01/2004’
 String Comparisons are used for data types of text, ntext, char,
nchar, varchar, and nvarchar
 Predicates are available for full or partial match comparisons
WHERE LastName LIKE ‘Johns%n’
WHERE FREETEXT(Description, ‘Johnson’)
WHERE LastName = ‘Johnson’
WHERE CONTAINS(LastName, ‘Johnson’)
•Logical operators are used to combine conditions in a statement
Returns only rows with first name of ‘John’ and last name of ‘Smith’
Returns all rows with first name of ‘John’ and all rows with last name of
‘Smith’
Returns all rows with first name of ‘John’ and last name not equal to
‘Smith’
WHERE FirstName = ‘John’ OR LastName = ‘Smith’
WHERE FirstName = ‘John’ AND NOT LastName = ‘Smith’
WHERE FirstName = ‘John’ AND LastName = ‘Smith’
~ (Bitwise Not)
*(Multiply), /(Division), %(Modulo)
Comparisons
=, >, <, >=, <=, <>, !=, !>, !<
+(Positive), -(Negative), +(Add), (+Concatenate),
-(Subtract), ^(Bitwise Exclusive OR), |(Bitwise OR)
NOT
AND
ALL, ANY, BETWEEN, IN, LIKE, OR, SOME
=(Assignment)
BETWEEN tests for data values within a range of values.
BETWEEN uses the same logic as >= AND <=
SELECT *
FROM Student
WHERE age BETWEEN 25 AND 30
SELECT *
FROM Student
WHERE age>=25 AND age<=30
SELECT SalesOrderID, OrderQty, ProductID, UnitPrice
FROM Sales.SalesOrderDetail
WHERE ProductID IN (750, 753, 765, 770)
IN tests a column’s values against a list of possible values.
IN uses the same logic as multiple comparisons with the OR
predicate between them
SELECT SalesOrderID, OrderQty, ProductID, UnitPrice
FROM Sales.SalesOrderDetail
WHERE ProductID = 750 OR ProductID = 753
OR ProductID = 765 OR ProductID = 770
Comparing NULL to any other value returns UNKNOWN
A NULL value cannot be included in a calculation.
NULL values are not equal
NULL is not a zero (0) value or an empty string
NULL is an UNKNOWN value
The special SPARSE keyword can be used to conserve space
in columns that allow NULL values.
Use IS NULL to test for NULL values in an argument.
ISNULL() returns a given value if the column value is NULL
NULLIF() returns NULL if both specified expressions are equal
COALESCE() returns the first non NULL expression among its arguments,
similar to a CASE statement
select Nullif(st_age,dept_id) from Student
where St_Id=7
SELECT CAST(COALESCE(hourly_wage * 40 * 52, salary,
commission * num_sales) AS money) AS 'Total Salary'
FROM wages
SELECT ISNULL(st_fname,’ ’)
FROM Student;
 Sorting Data
 Eliminating Duplicate Rows
 Labeling Columns in Result Sets
 Using String Literals
 Using Expressions
SELECT LastName, FirstName, MiddleName
FROM Person.Person
ORDER BY LastName, FirstName
SELECT DISTINCT LastName, FirstName, MiddleName
FROM Person.Person
ORDER BY LastName, FirstName
 Aliases are used to create custom column headers in the result
set display.
 You can rename actual or derived columns
 The optional AS clause can be added to make the statement
more readable.
 Both statements below are equivalent
SELECT salary*12 as [annual salary]
From instructor
SELECT (LastName + ‘, ‘ + FirstName + ‘ ‘ +
ISNULL(SUBSTRING(MiddleName, 1, 1), ‘ ‘)) AS Name
FROM Person.Person
ORDER BY LastName, FirstName, MiddleName
 String Literals:
 Are constant values.
 Can be inserted into derived columns to format data.
 Can be used as alternate values in functions, such as the
ISNULL() function.
 Using mathematical expressions in SELECT and WHERE
clauses
 Using functions in expressions
SELECT Name, ProductNumber, ListPrice AS OldPrice, (ListPrice *
1.1) AS NewPrice
FROM Production.Product
WHERE SellEndDate < GETDATE()
SELECT Name, ProductNumber, ListPrice AS OldPrice, (ListPrice *
1.1) AS NewPrice
FROM Production.Product
WHERE ListPrice > 0 AND (ListPrice/StandardCost) > .8
 Querying Multiple Tables by Using Joins
 Applying Joins for Typical Reporting Needs
 Combining and Limiting Result Sets
 Fundamentals of Joins
 Categorizing Statements by Types of Joins
 Joining Data Using Inner Joins
 Joining Data Using Outer Joins
 Joining Data Using Cross Joins
 Identifying the Potential Impact of a Cartesian
Product
• Select Specific Columns from Multiple Tables
• JOIN keyword specifies that tables are joined and how to join them
• ON keyword specifies join condition
FROM first_table join_type second_table
[ON (join_condition)]
Joins:
Simplified JOIN Syntax:
• Query Two or More Tables to Produce a Result Set
• Use Primary and Foreign Keys as join conditions
• Use columns common to specified tables to join tables
 Inner Join
 Includes equi-joins and natural joins
 Use comparison operators to match rows
 Outer Join
 Includes left, right, or full outer joins
 Cross Join
 Also called Cartesian products
 Self Join
 Refers to any join used to join a table to itself
• Is defined as all possible combinations of rows in all tables
A Cartesian Product:
• Results in a rowset containing the number of rows in the first table
times the number of rows in the second
• Can result in huge result sets that take several hours to complete!



SELECT DISTINCT p1.ProductSubcategoryID, p1.ListPrice
FROM Production.Product p1
INNER JOIN Production.Product p2
ON p1.ProductSubcateogoryID = p2.ProductSubcategoryID
AND p1.ListPrice <> p2.ListPrice
WHERE p1.ListPrice < $15 AND p2.ListPrice < $15
ORDER BY ProductSubcategoryID
• The same Operators and Predicates used for Inner Joins can be used for
Not-Equal Joins
ProductSubcateogoryID ListPrice
-----------------------------------
23 8.99
23 9.50
...
(8 row(s) affected)
Result Set:
 Using Equal Operator not satisfy all join conditions.
 Display employees information ( name , salary , title) with salary grade
for each employee.
SELECT e. name, e. salary, j.grade
FROM employees e, job_ grades j
WHERE e. salary
BETWEEN j.lowest_ sal AND j. highest_ sal;
 Combining Result Sets by Using the UNION Operator
 Limiting Result Sets by Using the EXCEPT and INTERSECT
Operators
 Identifying the Order of Precedence of UNION, EXCEPT, and
INTERSECT
 Limiting Result Sets by Using the TOP and TABLESAMPLE
Operators
 Categorizing Statements that Limit Result Sets
SELECT * FROM testa
UNION ALL
SELECT * FROM testb;
The number and order of columns must be the same
in all queries and all data types must be compatible
• UNION combines the results of two or more queries into a single result set
that includes all the rows that belong to all queries in the union
columna columnb
------------------
100 test
100 test
...
(8 row(s) affected)
Result Set:
SELECT ProductID
FROM Production.Product
EXCEPT
SELECT ProductID
FROM Production.WorkOrder
SELECT ProductID
FROM Production.Product
INTERSECT
SELECT ProductID
FROM Production.WorkOrder
• EXCEPT returns any distinct values from the query to the left of the EXCEPT operand
that are not also returned from the right query
• INTERSECT returns any distinct values that are returned by both the query on the left
and right sides of the INTERSECT operand
EXCEPT Example:
INTERSECT Example:
EXCEPT, INTERSECT, and UNION are evaluated in the context of the following
precedence:
Expressions in parentheses
1
The INTERSECT operand
2
EXCEPT and UNION evaluated from Left to Right based on
their position in the expression
3
 Find the names of employees whose working
location = giza
Select name
from Employee
where Dno in
( select Dnumber from dept
where location=‘giza’)
 Display department name with the highest paid employee
 1- Highest Salary
 2- Deptno for this Employee
 3- Department name
SELECT dname FROM dept
WHERE deptno = (SELECT deptno FROM emp
WHERE sal = (SELECT MAX(sal) FROM EMP));
 Find the names of employees whose salary is
greater than the salary of the employees in
department 5
Select Lname , Fname
From employee
Where salary > All ( select salary
from employee where Dno=5)
 Check if the result of correlated subquery is empty
 The EXISTS condition is considered "to be met" if the subquery returns at
least one row.
Display suppliers information who have orders.
SELECT *
FROM suppliers
WHERE EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);
 Retrieve the name of employees who have no dependents
Select name
From employee
Where Not Exists ( select * from dependent where ssn=Essn)
DELETE FROM suppliers
WHERE Not EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);
COUNT , SUM , MAX, MIN and AVG
 Find the sum of salaries of all employees , the maximum, the
minimum salary, and the average salary
Select Sum(salary) , Max(salary), Min(salary), Avg(salary)
from Employees
Find the total number of employees in the company?
Find the number of employees in the research department?
Note : Group Functions ignore Null values in the columns
Apply aggregate functions to a subgroups of tuples
For each department retrieve the department number , the
number of employees in the department, and their average
salary
Select dno , count(*) , avg(salary)
From employee Group by dno
 For each project on which more than two employees work,
retrieve the project number, the project name , and the
number of employees who work on the project
Select pnumber, pname ,count(works_on.pno)
From project , Works_on
Where Pnumber = Pno
Group by pnumber, pname
Having count(*) > 2
Grant Revoke
- Grant Select on table employees to
Ahmed;
- Grant All on Table department to
Mary, Ahmed;
- Grant Select on table employees to
Ahmed with grant Option;
-Revoke update on Table department
From Mary;
- Revoke All on Table department
From Mary, Ahmed;
Note: Example in the notes
ANSI SQL URL : http://www.w3schools.com/SQL/sql_join.asp
MS SQL URL :
http://msdn.microsoft.com/en-us/library/bb264565.aspx

asdasdasdasdsadasdasdasdasdsadasdasdasdsadsadasd

  • 2.
     Developed inthe early 1970 (SEQual)  ANSI-SQL defined by the American National Standards Institute  Microsoft implementation is T-SQL, or Transact SQL  Other implementations include PL/SQL and IBM’s SQL Procedural Language.
  • 3.
     DML –Data Manipulation Language  DCL – Data Control Language  DDL – Data Definition Language  TCL - Transactional Control Language  DQL - Data Query Language (Select)
  • 4.
    A data typedetermines the type of data that can be stored in a database column. The most commonly used data types are: 1. Alphanumeric: data types used to store characters, numbers, special characters, or nearly any combination. 2. Numeric 3. Date and Time
  • 5.
    Executing queries occurswhen in a query session by: Selecting the Execute Icon Pressing the F5 key Note: Select the Database Before Executing Query or write Use Keyword + DB Name on top of the Query
  • 6.
    • The useof a beginning /* and ending */ creates comments • The double dash comments to the end of line /* This is a comment */ --This is a comment • Comments are statements about the meaning of the code • When used, there is no execution performed on the text There are two ways to comment code using T-SQL:
  • 7.
     Recall thata batch is a series of one or more statements submitted and executed at the same time  Example: delete sales where stor_id = "5023" and ord_num = "AB-123-DEF-425-1Z3" delete salesdetail where stor_id = "5023" and ord_num = "AB-123-DEF-425-1Z3" select * from sales where stor_id = "5023" select * from salesdetail where stor_id = "5023" go
  • 8.
  • 9.
     Create Table Alter Table  Drop Table
  • 10.
    CREATE TABLE [table_name] ("column1" "data_type", "column 2" "data_type", ... ) Syntax: Example CREATE TABLE Employee (ID int Primary Key, FName char(50) Not Null, LName char(50), Address char(50), Birth_Date date);
  • 11.
  • 12.
    ALTER TABLE table_nameADD column_name datatype ALTER TABLE table_name DROP column_name Syntax: Example ALTER TABLE employee ADD City varchar(30)
  • 13.
  • 14.
     Inserting Datainto Tables  Deleting Data from Tables  Updating Data in Tables
  • 15.
    INSERT [INTO] table_or_view[(column_list)] data_values • The INSERT statement adds one or more new rows to a table • INSERT inserts data_values as one or more rows into the specified table_or_view • column_list is a list of column names used to specify the columns for which data is supplied INSERT Syntax:
  • 16.
    Using a SimpleINSERT Statement INSERT INTO Production.UnitMeasure VALUES (N'F2', N'Square Feet', GETDATE()); INSERT INTO Production.UnitMeasure VALUES (N'F2', N'Square Feet', GETDATE()), (N'Y2', N'Square Yards', GETDATE()); Inserting Multiple Rows of Data (Row Constructor) INSERT INTO MyTable (PriKey, Description) SELECT ForeignKey, Description FROM SomeView INSERT dbo.SomeTable EXECUTE SomeProcedure ”predefined procedure” INSERT using SELECT INSERT using EXECUTE
  • 17.
    DELETE table_or_view FROM table_sources WHEREsearch_condition • The DELETE statement removes one or more rows in a table or view • DELETE removes rows from the table_or_view parameter that meet the search condition • table_sources can be used to specify additional tables or views that can be used by the WHERE clause DELETE Syntax:
  • 18.
    DELETE FROM SomeTable; DELETEFROM SomeTable WHERE SomeColumn IN (Subquery Definition); DELETE with no WHERE clause DELETE using a Subquery DELETE FROM Sales.SalesPerson; DELETE FROM Sales.SalesPersonQuotaHistory WHERE SalesPersonID IN (SELECT SalesPersonID FROM Sales.SalesPerson WHERE SalesYTD > 2500000.00);
  • 19.
    TRUNCATE TABLE HumanResources.JobCandidate; TRUNCATETABLE [ { database_name.[ schema_name ]. | schema_name . } ] table_name [ ; ] You cannot use TRUNCATE TABLE on tables that are referenced by a FOREIGN KEY constraint TRUNCATE TABLE Syntax TRUNCATE TABLE Example
  • 20.
    • Fewer locksare typically used • Less transaction log space is used TRUNCATE TABLE has the following advantages over DELETE: DELETE FROM Sales.SalesPerson; TRUNCATE TABLE Sales.SalesPerson;
  • 21.
    UPDATE table_or_view SET column_name= expression FROM table_sources WHERE search_condition • The UPDATE statement changes data values in one, many, or all rows of a table • An UPDATE statement referencing a table or view can change the data in only one base table at a time • UPDATE has three major clauses: • SET – comma-separated list of columns to be updated • FROM – supplies values for the SET clause • WHERE – specifies a search condition for the SET clause UPDATE Syntax:
  • 22.
    UPDATE SomeTable SET Column= Value UPDATE SomeTable SET Column = Value WHERE SearchExpression Simple UPDATE Statement UPDATE with a WHERE clause UPDATE Sales.SalesPerson SET Bonus = 6000; UPDATE Production.Product SET Color = N’Metallic Red’ WHERE Name LIKE N’Road-250%’ AND Color = N’Red’; UPDATE Sales.SalesPerson SET Bonus = Bonus * 2;
  • 23.
    UPDATE SomeTable SET Column= Value FROM SomeSubquery UPDATE using a Subquery UPDATE Sales.SalesPerson SET SalesYTD = SalesYTD + SubTotal FROM Sales.SalesPerson AS sp JOIN Sales.SalesOrderHeader AS so ON sp.BusinessEntityID = so.SalesPersonID AND so.OrderDate = (SELECT MAX(OrderDate) FROM Sales.SalesOrderHeader WHERE SalesPersonID = sp.BusinessEntityID); SalesYTD -------------- 677558.4653 4557045.0459 Before SalesYTD -------------- 721382.488 4593234.5123 After
  • 24.
  • 25.
    25  Used forqueries on single or multiple tables  Clauses of the SELECT statement:  SELECT  List the columns (and expressions) that should be returned from the query  FROM  Indicate the table(s) or view(s) from which data will be obtained  WHERE  Indicate the conditions under which a row will be included in the result  GROUP BY  Indicate columns to group the results  HAVING  Indicate the conditions under which a group will be included  ORDER BY  Sorts the result according to specified columns
  • 26.
  • 27.
    Displays All Columnsin the Employee Table USE AdventureWorks2012; GO SELECT * FROM HumanResources.Employee Displays Only FirstName, LastName and JobTitle Columns USE AdventureWorks2012; GO SELECT FirstName, LastName, JobTitle FROM HumanResources.Employee
  • 28.
     Retrieving SpecificRows in a Table  Filtering Data by Using Comparison Operators  Filtering Data by Using String Comparisons  Filtering Data by Using Logical Operators  Retrieving a Range of Values  Retrieving a List of Values
  • 29.
    Simple WHERE clause WHEREClause Using a Predicate USE ITI; GO SELECT * FROM Student WHERE Age >20 USE ITI; GO SELECT * FROM Instructor WHERE Salary IS NULL;
  • 30.
    Type Operators • Arithmeticoperators • +, -, *, /, % Vacation + SickLeave AS 'Total PTO' • Assignment operator • = SET @MyCounter = 1 • Comparison operators • =, <, >, <>, !, >=, <= IF (@MyProduct <> 0) … • Logical operators • AND, OR, NOT WHERE Department = ‘Sales' AND (Shift = 'Evening' OR Shift = 'Night') • String concatenation operator • + SELECT LastName + ', ' + FirstName AS Moniker
  • 31.
     Comparison operatorstest whether two expressions are the same.  Comparison operators return a Boolean value of TRUE, FALSE, or UNKNOWN. Scalar Comparison Operators =, <>, >, >=, <, <=, != USE AdventureWorks2012; GO SELECT FirstName, LastName, MiddleName FROM Person.Person WHERE ModifiedDate >= ‘01/01/2004’
  • 32.
     String Comparisonsare used for data types of text, ntext, char, nchar, varchar, and nvarchar  Predicates are available for full or partial match comparisons WHERE LastName LIKE ‘Johns%n’ WHERE FREETEXT(Description, ‘Johnson’) WHERE LastName = ‘Johnson’ WHERE CONTAINS(LastName, ‘Johnson’)
  • 33.
    •Logical operators areused to combine conditions in a statement Returns only rows with first name of ‘John’ and last name of ‘Smith’ Returns all rows with first name of ‘John’ and all rows with last name of ‘Smith’ Returns all rows with first name of ‘John’ and last name not equal to ‘Smith’ WHERE FirstName = ‘John’ OR LastName = ‘Smith’ WHERE FirstName = ‘John’ AND NOT LastName = ‘Smith’ WHERE FirstName = ‘John’ AND LastName = ‘Smith’
  • 34.
    ~ (Bitwise Not) *(Multiply),/(Division), %(Modulo) Comparisons =, >, <, >=, <=, <>, !=, !>, !< +(Positive), -(Negative), +(Add), (+Concatenate), -(Subtract), ^(Bitwise Exclusive OR), |(Bitwise OR) NOT AND ALL, ANY, BETWEEN, IN, LIKE, OR, SOME =(Assignment)
  • 35.
    BETWEEN tests fordata values within a range of values. BETWEEN uses the same logic as >= AND <= SELECT * FROM Student WHERE age BETWEEN 25 AND 30 SELECT * FROM Student WHERE age>=25 AND age<=30
  • 36.
    SELECT SalesOrderID, OrderQty,ProductID, UnitPrice FROM Sales.SalesOrderDetail WHERE ProductID IN (750, 753, 765, 770) IN tests a column’s values against a list of possible values. IN uses the same logic as multiple comparisons with the OR predicate between them SELECT SalesOrderID, OrderQty, ProductID, UnitPrice FROM Sales.SalesOrderDetail WHERE ProductID = 750 OR ProductID = 753 OR ProductID = 765 OR ProductID = 770
  • 37.
    Comparing NULL toany other value returns UNKNOWN A NULL value cannot be included in a calculation. NULL values are not equal NULL is not a zero (0) value or an empty string NULL is an UNKNOWN value The special SPARSE keyword can be used to conserve space in columns that allow NULL values. Use IS NULL to test for NULL values in an argument.
  • 38.
    ISNULL() returns agiven value if the column value is NULL NULLIF() returns NULL if both specified expressions are equal COALESCE() returns the first non NULL expression among its arguments, similar to a CASE statement select Nullif(st_age,dept_id) from Student where St_Id=7 SELECT CAST(COALESCE(hourly_wage * 40 * 52, salary, commission * num_sales) AS money) AS 'Total Salary' FROM wages SELECT ISNULL(st_fname,’ ’) FROM Student;
  • 39.
     Sorting Data Eliminating Duplicate Rows  Labeling Columns in Result Sets  Using String Literals  Using Expressions
  • 40.
    SELECT LastName, FirstName,MiddleName FROM Person.Person ORDER BY LastName, FirstName
  • 41.
    SELECT DISTINCT LastName,FirstName, MiddleName FROM Person.Person ORDER BY LastName, FirstName
  • 42.
     Aliases areused to create custom column headers in the result set display.  You can rename actual or derived columns  The optional AS clause can be added to make the statement more readable.  Both statements below are equivalent SELECT salary*12 as [annual salary] From instructor
  • 43.
    SELECT (LastName +‘, ‘ + FirstName + ‘ ‘ + ISNULL(SUBSTRING(MiddleName, 1, 1), ‘ ‘)) AS Name FROM Person.Person ORDER BY LastName, FirstName, MiddleName  String Literals:  Are constant values.  Can be inserted into derived columns to format data.  Can be used as alternate values in functions, such as the ISNULL() function.
  • 44.
     Using mathematicalexpressions in SELECT and WHERE clauses  Using functions in expressions SELECT Name, ProductNumber, ListPrice AS OldPrice, (ListPrice * 1.1) AS NewPrice FROM Production.Product WHERE SellEndDate < GETDATE() SELECT Name, ProductNumber, ListPrice AS OldPrice, (ListPrice * 1.1) AS NewPrice FROM Production.Product WHERE ListPrice > 0 AND (ListPrice/StandardCost) > .8
  • 45.
     Querying MultipleTables by Using Joins  Applying Joins for Typical Reporting Needs  Combining and Limiting Result Sets
  • 46.
     Fundamentals ofJoins  Categorizing Statements by Types of Joins  Joining Data Using Inner Joins  Joining Data Using Outer Joins  Joining Data Using Cross Joins  Identifying the Potential Impact of a Cartesian Product
  • 47.
    • Select SpecificColumns from Multiple Tables • JOIN keyword specifies that tables are joined and how to join them • ON keyword specifies join condition FROM first_table join_type second_table [ON (join_condition)] Joins: Simplified JOIN Syntax: • Query Two or More Tables to Produce a Result Set • Use Primary and Foreign Keys as join conditions • Use columns common to specified tables to join tables
  • 48.
     Inner Join Includes equi-joins and natural joins  Use comparison operators to match rows  Outer Join  Includes left, right, or full outer joins  Cross Join  Also called Cartesian products  Self Join  Refers to any join used to join a table to itself
  • 49.
    • Is definedas all possible combinations of rows in all tables A Cartesian Product: • Results in a rowset containing the number of rows in the first table times the number of rows in the second • Can result in huge result sets that take several hours to complete!   
  • 50.
    SELECT DISTINCT p1.ProductSubcategoryID,p1.ListPrice FROM Production.Product p1 INNER JOIN Production.Product p2 ON p1.ProductSubcateogoryID = p2.ProductSubcategoryID AND p1.ListPrice <> p2.ListPrice WHERE p1.ListPrice < $15 AND p2.ListPrice < $15 ORDER BY ProductSubcategoryID • The same Operators and Predicates used for Inner Joins can be used for Not-Equal Joins ProductSubcateogoryID ListPrice ----------------------------------- 23 8.99 23 9.50 ... (8 row(s) affected) Result Set:
  • 51.
     Using EqualOperator not satisfy all join conditions.  Display employees information ( name , salary , title) with salary grade for each employee. SELECT e. name, e. salary, j.grade FROM employees e, job_ grades j WHERE e. salary BETWEEN j.lowest_ sal AND j. highest_ sal;
  • 52.
     Combining ResultSets by Using the UNION Operator  Limiting Result Sets by Using the EXCEPT and INTERSECT Operators  Identifying the Order of Precedence of UNION, EXCEPT, and INTERSECT  Limiting Result Sets by Using the TOP and TABLESAMPLE Operators  Categorizing Statements that Limit Result Sets
  • 53.
    SELECT * FROMtesta UNION ALL SELECT * FROM testb; The number and order of columns must be the same in all queries and all data types must be compatible • UNION combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union columna columnb ------------------ 100 test 100 test ... (8 row(s) affected) Result Set:
  • 54.
    SELECT ProductID FROM Production.Product EXCEPT SELECTProductID FROM Production.WorkOrder SELECT ProductID FROM Production.Product INTERSECT SELECT ProductID FROM Production.WorkOrder • EXCEPT returns any distinct values from the query to the left of the EXCEPT operand that are not also returned from the right query • INTERSECT returns any distinct values that are returned by both the query on the left and right sides of the INTERSECT operand EXCEPT Example: INTERSECT Example:
  • 55.
    EXCEPT, INTERSECT, andUNION are evaluated in the context of the following precedence: Expressions in parentheses 1 The INTERSECT operand 2 EXCEPT and UNION evaluated from Left to Right based on their position in the expression 3
  • 56.
     Find thenames of employees whose working location = giza Select name from Employee where Dno in ( select Dnumber from dept where location=‘giza’)
  • 57.
     Display departmentname with the highest paid employee  1- Highest Salary  2- Deptno for this Employee  3- Department name SELECT dname FROM dept WHERE deptno = (SELECT deptno FROM emp WHERE sal = (SELECT MAX(sal) FROM EMP));
  • 58.
     Find thenames of employees whose salary is greater than the salary of the employees in department 5 Select Lname , Fname From employee Where salary > All ( select salary from employee where Dno=5)
  • 59.
     Check ifthe result of correlated subquery is empty  The EXISTS condition is considered "to be met" if the subquery returns at least one row. Display suppliers information who have orders. SELECT * FROM suppliers WHERE EXISTS (select * from orders where suppliers.supplier_id = orders.supplier_id);
  • 60.
     Retrieve thename of employees who have no dependents Select name From employee Where Not Exists ( select * from dependent where ssn=Essn)
  • 61.
    DELETE FROM suppliers WHERENot EXISTS (select * from orders where suppliers.supplier_id = orders.supplier_id);
  • 62.
    COUNT , SUM, MAX, MIN and AVG  Find the sum of salaries of all employees , the maximum, the minimum salary, and the average salary Select Sum(salary) , Max(salary), Min(salary), Avg(salary) from Employees Find the total number of employees in the company? Find the number of employees in the research department? Note : Group Functions ignore Null values in the columns
  • 63.
    Apply aggregate functionsto a subgroups of tuples For each department retrieve the department number , the number of employees in the department, and their average salary Select dno , count(*) , avg(salary) From employee Group by dno
  • 64.
     For eachproject on which more than two employees work, retrieve the project number, the project name , and the number of employees who work on the project Select pnumber, pname ,count(works_on.pno) From project , Works_on Where Pnumber = Pno Group by pnumber, pname Having count(*) > 2
  • 65.
    Grant Revoke - GrantSelect on table employees to Ahmed; - Grant All on Table department to Mary, Ahmed; - Grant Select on table employees to Ahmed with grant Option; -Revoke update on Table department From Mary; - Revoke All on Table department From Mary, Ahmed; Note: Example in the notes
  • 66.
    ANSI SQL URL: http://www.w3schools.com/SQL/sql_join.asp MS SQL URL : http://msdn.microsoft.com/en-us/library/bb264565.aspx

Editor's Notes

  • #2 ANSI SQL, and compare it to SQL Server T-SQL. History of SQL SQL was developed by IBM in the early 1970s. SQL was adopted as a standard by American National Standards Institute (ANSI) in 1986 and ISO in 1987. Definition of ANSI SQL The process of implementing a standard as defined by ANSI can take some time by vendors. An example is SQL-99. This was defined in 1999. This created an addition known as Common Table Expressions. This was implemented in the SQL Server 2005 version of T-SQL. ANSI SQL is defined by the American National Standards Institute. It is known as SQL/PSM or SQL/Persistent Stored Modules. These standards are considered open standards. Definition of T-SQL, or Transact SQL Microsoft’s implementation of SQL is known as T-SQL. It is the language that is used to create queries for SQL Server. Other implementations of SQL There are other implementations of SQL such as Oracle’s PL/SQL, Procedural Language/SQL and IBM’s SQL Procedural Language.
  • #3  Data Manipulation Language (DML) DML is the category of SQL statements that included changes to the data within the database. These include the UPDATE, DELETE, and INSERT statements. Data Control Language (DCL) DCL is the category of SQL statements that are associated with rights to objects within the database. These include GRANT, REVOKE, and DENY. Data Definition Language (DDL) DDL is the category of SQL statements that are associated with the implementation, changing, or deletion of objects for or within a database. These include CREATE, TRUNCATE, DROP, and ALTER. Transactional Control Language (TCL) TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a database. These include COMMIT, SAVE POINT, ROLLBACK. SQL Select Statements “Data Querying Language” SQL Queries are often considered part of the DML. But when started with a SELECT there are no changes to the data used in the query.
  • #10 On this slide you will learn the basics of the INSERT statement. The INSERT statement adds one or more new rows to a table. In a simplified treatment, INSERT has the following form: INSERT [INTO] table_or_view [(column_list)] data_values The INSERT statement inserts data_values as one or more rows into the specified table or view. column_list is a list of column names, separated by commas, that can be used to specify the columns for which data is supplied. If column_list is not specified, all the columns in the table or view receive data. When column_list does not specify all the columns in a table or view, either the default value, if a default is defined for the column, or NULL is inserted into any column that is not specified in the list. All columns that are not specified in the column list must either allow for null values or have a default value assigned. INSERT statements do not specify values for the following types of columns because the SQL Server Database Engine generates the values for these columns: Columns with an IDENTITY property that generates the values for the column. Columns that have a default that uses the NEWID function to generate a unique GUID value. Computed columns, or columns that are defined as an expression calculated from one or more other columns in the CREATE TABLE statement.
  • #11 On this slide you will learn the basics of the INSERT statement. The INSERT statement adds one or more new rows to a table. In a simplified treatment, INSERT has the following form: INSERT [INTO] table_or_view [(column_list)] data_values The INSERT statement inserts data_values as one or more rows into the specified table or view. column_list is a list of column names, separated by commas, that can be used to specify the columns for which data is supplied. If column_list is not specified, all the columns in the table or view receive data. When column_list does not specify all the columns in a table or view, either the default value, if a default is defined for the column, or NULL is inserted into any column that is not specified in the list. All columns that are not specified in the column list must either allow for null values or have a default value assigned. INSERT statements do not specify values for the following types of columns because the SQL Server Database Engine generates the values for these columns: Columns with an IDENTITY property that generates the values for the column. Columns that have a default that uses the NEWID function to generate a unique GUID value. Computed columns, or columns that are defined as an expression calculated from one or more other columns in the CREATE TABLE statement.
  • #12 On this slide you will learn the basics of the INSERT statement. The INSERT statement adds one or more new rows to a table. In a simplified treatment, INSERT has the following form: INSERT [INTO] table_or_view [(column_list)] data_values The INSERT statement inserts data_values as one or more rows into the specified table or view. column_list is a list of column names, separated by commas, that can be used to specify the columns for which data is supplied. If column_list is not specified, all the columns in the table or view receive data. When column_list does not specify all the columns in a table or view, either the default value, if a default is defined for the column, or NULL is inserted into any column that is not specified in the list. All columns that are not specified in the column list must either allow for null values or have a default value assigned. INSERT statements do not specify values for the following types of columns because the SQL Server Database Engine generates the values for these columns: Columns with an IDENTITY property that generates the values for the column. Columns that have a default that uses the NEWID function to generate a unique GUID value. Computed columns, or columns that are defined as an expression calculated from one or more other columns in the CREATE TABLE statement.
  • #15 On this slide you will learn the basics of the INSERT statement. The INSERT statement adds one or more new rows to a table. In a simplified treatment, INSERT has the following form: INSERT [INTO] table_or_view [(column_list)] data_values The INSERT statement inserts data_values as one or more rows into the specified table or view. column_list is a list of column names, separated by commas, that can be used to specify the columns for which data is supplied. If column_list is not specified, all the columns in the table or view receive data. When column_list does not specify all the columns in a table or view, either the default value, if a default is defined for the column, or NULL is inserted into any column that is not specified in the list. All columns that are not specified in the column list must either allow for null values or have a default value assigned. INSERT statements do not specify values for the following types of columns because the SQL Server Database Engine generates the values for these columns: Columns with an IDENTITY property that generates the values for the column. Columns that have a default that uses the NEWID function to generate a unique GUID value. Computed columns, or columns that are defined as an expression calculated from one or more other columns in the CREATE TABLE statement.
  • #18 DELETE with no WHERE clause DELETE can be used without a WHERE clause to delete all rows of a table without limitation. The example here deletes all rows from the Sales.Salesperson table because no WHERE clause is defined. DELETE using a Subquery The WHERE clause of the DELETE statement can be defined as a subquery in order to delete rows from a base table depending on data stored in another table. The example here deletes rows from the SalesPersonQuotaHistory table based on the year-to-date sales in the SalesPerson table. DELETE using TOP DELETE can be modified with a TOP clause, much like INSERT can, in order to remove some number or percentage of rows from a table. This example deletes 2.5 percent of the rows (27 rows) on the ProductionInventory table.
  • #19  On this slide you will learn how to remove all rows from a table without logging the individual row deletions. TRUNCATE TABLE removes all rows from a table without logging the individual row deletions. TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources. TRUNCATE TABLE Syntax The parameter database_name is the name of the database that the table to be truncated belongs to, schema_name is the name of the schema to which the table belongs, table_name is the name of the table to truncate or from which all rows are removed. You cannot use TRUNCATE TABLE on tables that: Are referenced by a FOREIGN KEY constraint, although you can truncate a table that has a foreign key that references itself. Participate in an indexed view. Are published by using transactional replication or merge replication. For tables with one or more of these characteristics, use the DELETE statement instead.
  • #20 Differences: ----sentax ----result and where ----performane and log ----space and shrink db TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources. Compared to the DELETE statement, TRUNCATE TABLE has the following advantages: Less transaction log space is used The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log. Fewer locks are typically used When the DELETE statement is executed using a row lock, each row in the table is locked for deletion. TRUNCATE TABLE always locks the table and page but not each row. Without exception, zero pages are left in the table After a DELETE statement is executed, the table can still contain empty pages. For indexes, the delete operation can leave empty pages behind. TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes, and so on remain. To remove the table definition in addition to its data, use the DROP TABLE statement. Note to students that if the table to be truncated contains an identity column, the counter for that column is reset to the seed value defined for the column. If no seed was defined, the default value 1 is used. If they want to retain the identity counter for any reason, use DELETE instead.
  • #23 --raise course grade for each student by 10 where course topic is programming update stud_course set grade +=10 from stud_course sc,course c where sc.crs_id=c.crs_id and top_id=(select top_id from topic where top_name='programming') update UPDATE Sales.SalesPerson SET SalesYTD = SalesYTD + SubTotal FROM Sales.SalesPerson AS sp JOIN Sales.SalesOrderHeader AS so ON sp.BusinessEntityID = so.SalesPersonID AND so.OrderDate = (SELECT MAX(OrderDate) FROM Sales.SalesOrderHeader WHERE SalesPersonID = sp.BusinessEntityID);
  • #29 The WHERE clause uses search arguments to filter the data requested in the SELECT statement. Search arguments contain the comparisons and criteria for selecting data. Search arguments are expressed using conditional statements and predicates. Conditional statements include operators such as: =, <, >, <>, <=, >=. Predicates are statements that return a TRUE, FALSE, or UNKNOWN result. These statements include: BETWEEN, CONTAINS, EXISTS, IN, IS [NOT] NULL, and LIKE. Criteria in the WHERE clause can be combined using the NOT, AND, and OR operators. Explain what a search argument is. Make sure to introduce the word predicate. Mention that by using search conditions, performance can be improved by limiting the numbers of rows to be returned.
  • #30 Present an overview of the various types of T-SQL operators. Explain how operators provide various ways of manipulating and comparing information. Arithmetic Operators Are + addition,- subtraction, * multiplication, / division, % integer Used for mathematic functions. Assignment Operators = Assigns the value to a variable. Comparison Operators = equal to, < less than , > greater than, <> not equal to, ! not These can be used in formats such as >= or <= Comparison operators test whether two expressions are the same. Comparison operators can be used on all expressions except expressions of the text, ntext, or image data types. Logical Operators Logical Operators are used to specify how multiple search terms are combined in a search query. Logical operators also create more complicated search expressions from simpler ones, and thus refine your search. The following table shows you how to use each of the available operators. Operate on a single value and then return a single value. Scalar functions can be used wherever an expression is valid. Both terms in the same topic – AND Either term in a topic - OR First term without the second term - NOT String Concatenation String concatenation is done with the + An operator in a string expression that concatenates two or more character or binary strings, columns, or a combination of strings and column names into one expression (a string operator).
  • #31 Describe different comparison operators in a table using the SELECT and COMPARISON operators Comparison operators take a value or set of values and tests to see if they are the same. Using comparison operators you can compare single values against each other (scalar), look in a range or list of values (range). Comparison operators can be included in the WHERE and the HAVING clauses of the statement. The special NOT modifier can be used to reverse the Boolean value returned by a comparison operator.
  • #32 Example Select St_fname,st_lname from Student where st_fname like '_A%' Select St_fname,st_lname from Student where st_fname like '[_]A%' Select St_fname,st_lname from Student where st_fname like '___' select title_id, title from titles where title_id like "MC302[13579]" --Means MC302 + any characters of the following 1,3,5,7,9 select title_id, title from titles where title_id like "MC302[^13579]" --Means MC302 + any characters except the following 1,3,5,7,9 select st_fname from student where st_fname like '[a-h]%‘ Explain the LIKE clause. Explain different types of wildcard characters in a table. Describe different comparison operators in a table using the SELECT, the AND and LIKE operators String comparison operators search for strings and substrings within a text, ntext, char, nchar, varchar, or nvarchar data type. The = operator checks for an exact match between two strings. LIKE combined with a wildcard searches for the search condition argument in the left value string. Note that placing the % sign at the beginning of the criteria may adversely affect query performance by eliminating the possible use of indexes to help with the search. FREETEXT searches for the meaning rather than exact words. If a phrase is passed into FREETEXT, it will break the phrase into the component words to perform the search. Uses “inflectional” forms of the words to search. For instance “drive” is the “inflectional stem” of drives, drove, driving and driven. Uses the thesaurus to search for additional forms and “replacement” words. CONTAINS performs a “fuzzy” search. This is a special predicate specific to full text searches. Looks for a word or phrase. Also uses inflectional forms Also looks for synonyms by using a thesaurus. Can look for a word or phrase within a certain proximity of another word or phrase. When multiple words are used for the search, you can specify a value between 0.0 and 1.0 to give specific words more weight in the search criteria. Emphasize the FREETEXT and CONTAINS both operate only on full-text indexed columns. Mention that there are four different wildcard symbols that can be used: % replaces any string of zero or more characters _ (underscore) replaces any single character [] allows you to specify a list of characters, any of which can be matched [a-f] looks for any of the letters in the sequence a – f [abcdef] also looks for any of the letters in the sequence a – f [^] looks for all characters except those given in the range or set Show partial syntax of a SELECT statement using string comparisons.
  • #34 This slide describes operator precedence in Transact SQL statements. This topic is designed to be a very brief overview of operator precedence. Operator precedence is an important factor to consider when using operators in a Transact SQL statement. Click to advance to each of the items on the screen. Bitwise operators are the first ones that are processed. Then Multiplication, Division, and Modulo. Arithmetic operations are processed next. Next are Comparison operators. NOT operations are then processed. The AND logical operator is processed next. Then the other logical operators. Finally, the equals assignment operator is evaluated. Mention that parentheses are used to change the default precedence in formulas. By using parentheses you are designating those parts of the formula to be evaluated before the default precedence is followed. Also mention that all operators at the same precedence level are evaluated from left to right. REFERENCE Operator Precedence (Transact-SQL) http://go.microsoft.com/fwlink/?LinkID=127286
  • #37 ISNULL() – queries with data that you want to check for NULL values. NULLIF() – queries that you want to offer a more meaningful value in place of the NULL keyword being displayed in the result. COALESCE() – Queries where NULL values may exist and you wish to substitute one of several possibilities into a column of the result set.
  • #38 Use this slide to introduce students to the functions used to work with NULL values using the SELECT statement with the ISNULL function and the COALESCE and CONVERT functions Introduce how there are some functions that can solve problems with NULL values. The ISNULL function assigns a value that will be returned if the argument value is zero. The example above will return 0.00 if the MaxQty column value is NULL. The NULLIF function returns NULL if both arguments are equal. The example above will return the MakeFlag value if both values are different or a NULL value if both values are equal. The COALESCE function tests multiple arguments and returns the first one in the argument list that does not have a NULL value. The example above assumes that an employee can only have one wage type and returns the value of the wage assigned. Mention that AS ‘Max Quantity’, AS ‘Null if Equal’, and AS ‘Total Salary’ makes use of column aliases for readability, and that this will be discussed further in a later lesson. Question: When working with data, which data types would you expect to contain NULL values? How can you determine exactly which columns in your organization's tables are allowed to have NULL values? Possible Answers: Columns that commonly contain NULL values are those of data types: char, nchar, varchar, nvarchar, text, ntext. Numeric columns may contain NULL data, but it is not advisable. The easiest way to check column data types is to check in SQL Server Management Studio. If you do not have access to this tool then requesting the information from IT is a good idea.
  • #40 IORDER BY sorts the result set by a specified column or list of columns. If more than one column is specified sorting will be performed on each column in a nested fashion and in the order listed. Sort order can be specified as ASC (ascending) or DESC (descending) for each column. Mention that ASC (ascending) order is the assumed order if no order is specified. Mention that sorting data can slow down performance as SQL server needs to perform a distinct step. However, indexes will improve performance. REFERENCE ORDER BY Clause (Transact-SQL) http://go.microsoft.com/fwlink/?LinkID=127271 Sorting Rows with ORDER BY http://go.microsoft.com/fwlink/?LinkID=127272
  • #46 --joins --joins is faster than subqueries if the number of tables is smaller --and if there is indexes
  • #48 --Inner join and equi join select st_fname,dept_name from student s inner join department d on s.dept_id=d.dept_id select st_fname,dept_name from student s,department d where s.dept_id=d.dept_id --inner with 3 tables select st_fname,dept_name,ins.ins_name from student s inner join department d on s.dept_id=d.dept_id inner join instructor ins on ins.dept_id=d.dept_id order by ins_name --Outer join ===> left, right and full select st_fname,dept_name from student s left outer join department d on s.dept_id=d.dept_id select st_fname,dept_name from student s right outer join department d on s.dept_id=d.dept_id select st_fname,dept_name from student s full outer join department d on s.dept_id=d.dept_id --Cross join or Cartsian product select st_fname,dept_name from student s cross join department d select st_fname,dept_name from student s , department d --Self join select stud.st_fname,super.st_fname as "supervisor Name" from student super,student stud where super.st_id=stud.st_super
  • #50 You can also join values in two columns that are not equal. The same operators and predicates used for inner joins can be used for not-equal joins. The not-equal join (<>) is rarely used. As a general rule, not-equal joins make sense only when used with a self-join. Note that the expression NOT column_name = column_name is equivalent to column_name <> column_name. This not-equal Transact-SQL join and self-join are used to find the subcategories that have at least two different prices less than $15.
  • #53 UNION combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union. The UNION operation is different from using joins that combine columns from two tables. The following are basic rules for combining the result sets of two queries by using UNION: The number and the order of the columns must be the same in all queries The data types must be compatible This example is a valid UNION expression that returns the all rows from both the testa and testb tables.
  • #54 EXCEPT returns any distinct values from the left query that are not also found on the right query, and is used to exempt members from a result set. INTERSECT returns any distinct values that are returned by both the query on the left and right sides of the INTERSECT operand, and is used to determine which tables share similar data. The basic rules for combining the result sets of two queries that use EXCEPT or INTERSECT are the following: The number and the order of the columns must be the same in all queries The data types must be compatible
  • #55 Use this slide to introduce the order of precedence when using UNION, EXCEPT, and INTERSECT. If EXCEPT or INTERSECT is used together with other operators in an expression, it is evaluated in the context of the following precedence: Expressions in parentheses The INTERSECT operand EXCEPT and UNION evaluated from left to right based on their position in the expression If EXCEPT or INTERSECT is used to compare more than two sets of queries, data type conversion is determined by comparing two queries at a time, and following the previously mentioned rules of expression evaluation. This means that, for example, a subquery contained in a query would be evaluated before other expressions in the same query, then the INTERSECT portion of the query would be evaluated, and finally any EXCEPT or UNION clause would be evaluated. Note to students that using one ORDER BY clause applies only to when using UNION, EXCEPT and INTERSECT in a top-level query and not in a subquery.
  • #57 SELECT dname FROM dept WHERE deptno = (SELECT deptno FROM emp WHERE sal = (SELECT MAX(sal) FROM EMP));
  • #58 All operator Example : We don’t know the values in list We can replace ALL by max aggregate function - Select last_name, salary from employees where salary > (select max ( salary ) from employee where dno=5);
  • #59 The EXISTS condition is considered "to be met" if the subquery returns at least one row. The syntax for the EXISTS condition is: SELECT columns FROM tables WHERE EXISTS ( subquery ); SELECT * FROM suppliers WHERE EXISTS   (select *     from orders     where suppliers.supplier_id = orders.supplier_id);
  • #61  Example #3 - DELETE Statement The following is an example of a delete statement that utilizes the EXISTS condition: DELETE FROM suppliers WHERE EXISTS   (select *     from orders     where suppliers.supplier_id = orders.supplier_id); Example #4 - UPDATE Statement The following is an example of an update statement that utilizes the EXISTS condition: UPDATE suppliers SET supplier_name = ( SELECT customers.name FROM customers WHERE customers.customer_id = suppliers.supplier_id) WHERE EXISTS   ( SELECT customers.name     FROM customers     WHERE customers.customer_id = suppliers.supplier_id); Example #5 - INSERT Statement The following is an example of an insert statement that utilizes the EXISTS condition: INSERT INTO suppliers (supplier_id, supplier_name) SELECT account_no, name FROM suppliers WHERE exists (select * from orders Where suppliers.supplier_id = orders.supplier_id);
  • #62 Find the total number of employees in the company? Find the number of employees in the research department? Select count(*) from employees Find the number of employees in the research department ? Select count(*) from employee , department Where dno=dnumber and dname =‘Research’
  • #66 Oracle SQL URL : beginner-sql-tutorial.com Sybase SQL URL : http://infocenter.sybase.com/help/index.jsp ANSI SQL URL : http://www.w3schools.com/SQL/sql_join.asp MS SQL URL: http://msdn.microsoft.com/en-us/library/bb264565.aspx IBM Informix SQL : IBM Informix implementation http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqlt.doc/sqltmst104.htm