(c) 2006 National Academy for Software Development - http://academy.devbg.org 1 Релационни Релационни бази бази от от данни данни и Microsoft SQL Server 2005 Microsoft SQL Server 2005 Светлин Светлин Наков Наков Национална Национална академия академия по по разработка разработка на на софтуер софтуер academy.devbg.org Теория Теория и практика практика Съдържание Съдържание Съдържание 1. Национална академия по разработка на софтуер (НАРС) 2. Релационни бази от данни • Таблици, връзки, E/R диаграми, нормализация, съхранени процедури, тригери, изгледи, транзакции 3. Работа с езика SQL • Извличане на данни, съединения, агрегатни функции, групиране • Вмъкване, промяна, изтриване 1. 1. Национална Национална академия академия по по разработка разработка на на софтуер софтуер ( НАРС НАРС) 2. 2. Релационни Релационни бази бази от от данни данни • Таблици Таблици, , връзки връзки, , E/R E/R диаграми диаграми, , нормализация нормализация, , съхранени съхранени процедури процедури, , тригери тригери, , изгледи изгледи, , транзакции транзакции 3. 3. Работа Работа с езика езика SQL SQL • Извличане Извличане на на данни данни, , съединения съединения, , агрегатни агрегатни функции функции, , групиране групиране • Вмъкване Вмъкване, , промяна промяна, , изтриване изтриване За лектора За За лектора лектора • Светлин Наков • Носител на наградата “Джон Атанасов” на Президента на България • Автор на 3 книги и над 20 статии • 15 години опит с програмирането • 8 от тях професионално • Директор направление обучение в Национална академия по разработка на софтуер • Преподавател във ФМИ на СУ • Светлин Светлин Наков Наков • Носител Носител на на наградата наградата “Джон Джон Атанасов Атанасов” на на Президента Президента на на България България • Автор Автор на на 3 3 книги книги и над над 20 20 статии статии • 15 15 години години опит опит с програмирането програмирането • 8 8 от от тях тях професионално професионално • Директор Директор направление направление обучение обучение в Национална Национална академия академия по по разработка разработка на на софтуер софтуер • Преподавател Преподавател във във ФМИ ФМИ на на СУ СУ Национална Национална академия академия по по разработка разработка на на софтуер софтуер ( НАРС НАРС) Какво е НАРС? Какво Какво е НАРС НАРС? • Национална академия по разработка на софтуер (НАРС) • Практическо обучение за софтуерни инженери • Курсове за начинаещи и напреднали • Специалности Java и .NET • Гарантирана работа по специалността • Безплатно! • http://academy.devbg.org • Национална Национална академия академия по по разработка разработка на на софтуер софтуер ( НАРС НАРС) • Практическо Практическо обучение обучение за за софтуерни софтуерни инженери инженери • Курсове Курсове за за начинаещи начинаещи и напреднали напреднали • Специалности Специалности Java Java и .NET .NET • Гарантирана Гарантирана работа работа по по специалността специалността • Безплатно Безплатно! • http://academy.devbg.org http://academy.devbg.org Курсовете за начинаещи Курсовете Курсовете за за начинаещи начинаещи • Курсове за начинаещи –6 седмици • Въведение в програмирането с C# и Java • Не се изискват предварителни знания • Обхващат основите на програмирането • Масиви, цикли, структури от данни • Вход / изход, елементи от ООП • Успешно завършилите продължават в следващите нива • Безплатно! • Курсове Курсове за за начинаещи начинаещи – 6 6 седмици седмици • Въведение Въведение в програмирането програмирането с C# C# и Java Java • Не Не се се изискват изискват предварителни предварителни знания знания • Обхващат Обхващат основите основите на на програмирането програмирането • Масиви Масиви, , цикли цикли, , структури структури от от данни данни • Вход Вход / / изход изход, , елементи елементи от от ООП ООП • Успешно Успешно завършилите завършилите продължават продължават в следващите следващите нива нива • Безплатно Безплатно!
22
Embed
Intro To RDBMS And SQL Server 2005 - Svetlin Nakov
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
(c) 2006 National Academy for Software Development - http://academy.devbg.org 1
РелационниРелационни базибази отот данниданни ииMicrosoft SQL Server 2005Microsoft SQL Server 2005
44ХардСофтХардСофт АДАД22BulkSoft Inc.BulkSoft Inc.
33
11
towntown_id_id
СпутникСпутник АДАД
МентеМенте ООДООД
companycompany
22МоскваМосква33ПловдивПловдив
New YorkNew YorkСофияСофия
towntown
44
2211
idid
11
3311
countcountry_idry_id
T_COMPANYT_COMPANY T_TOWNT_TOWN
332211idid
САЩСАЩРусияРусияБългарияБългарияcountrycountry
T_COUNTRYT_COUNTRY
CREATE VIEW V_BG_COMPANY ASCREATE VIEW V_BG_COMPANY ASSELECT SELECT T_COMPANY.id AS id,T_COMPANY.id AS id,T_COMPANY.company AS companyT_COMPANY.company AS company
FROM T_COMPANY INNER JOIN FROM T_COMPANY INNER JOIN (T_TOWN INNER JOIN T_COUNTRY ON(T_TOWN INNER JOIN T_COUNTRY ONT_TOWN.country_id=T_COUNTRY.id)T_TOWN.country_id=T_COUNTRY.id)ON T_COMPANY.town_id=T_TOWN.idON T_COMPANY.town_id=T_TOWN.id
• Тригерите (triggers) са процедури на нивобаза, които се активират при някаквоусловие, например:• при добавяне на запис• при промяна на запис• при изтриване на запис
• Тригерите могат да извършватдопълнителна обработка на данните• промяна на данните при добавяне• поддръжка на логове и история
AS AS UPDATE Company SET Name = Name + ' Ltd.'UPDATE Company SET Name = Name + ' Ltd.'WHERE Id = (SELECT Id FROM Inserted)WHERE Id = (SELECT Id FROM Inserted)
• Транзакциите са последователности отдействия (заявки към базата данни), коитосе изпълняват атомарно:• или се изпълняват всичките действиязаедно (като едно цяло)
• или никое от действията не се изпълняваизобщо
• Пример:• Банково прехвърляне на пари от еднасметка в друга (теглене + внасяне)
• Ако тегленето или внасянето на паритепропадне, пропада цялата операция
BEGIN TRANSACTIONBEGIN TRANSACTIONUPDATE UPDATE AccountAccount set balance = balance set balance = balance -- @ammount@ammountWHERE id = @from_accWHERE id = @from_accIF @@rowcount <> 1 BEGINIF @@rowcount <> 1 BEGIN
• A relational database:• Can be accessed and modified by
executing Structured Query Language (SQL) statements• Uses a set of operations to extract
subset of the data• Contains a collection of tables
• Relationships are defined between the tables
•• A relational database:A relational database:•• Can be accessed and modified by Can be accessed and modified by
executing executing SStructured tructured QQuery uery LLanguage (SQL) statementsanguage (SQL) statements•• Uses a set of operations to extract Uses a set of operations to extract
subset of the datasubset of the data
•• Contains a collection of tablesContains a collection of tables•• Relationships are defined between Relationships are defined between
the tablesthe tables
Communicating with a DBCommunicating with a DBCommunicating with a DB
SQL statement isSQL statement issent to the databasesent to the database
SQL statement isSQL statement isenteredentered
SELECT Name SELECT Name FROM DepartmentFROM Department
SalesSalesEngineeringEngineering
MarketingMarketing……
NameName
The result is returnedThe result is returned(usually as a table)(usually as a table)
Database Database
(c) 2006 National Academy for Software Development - http://academy.devbg.org 11
SQL and TSQL and T--SQLSQLIntroductionIntroduction
What is SQL?What is SQL?What is SQL?
• Structured Query Language (SQL)• Declarative language for query and
manipulation of relational data• SQL consists of:
• Data Manipulation Language (DML)• SELECT, INSERT, UPDATE, DELETE
• Data Definition Language (DDL)• CREATE, DROP, ALTER• GRANT, REVOKE
•• Structured Query Language (SQL)Structured Query Language (SQL)•• Declarative language for query and Declarative language for query and
manipulation of relational datamanipulation of relational data
•• SQL consists of:SQL consists of:•• Data Manipulation Language (DML)Data Manipulation Language (DML)
INSERT INTO Project(Name, StartDate)INSERT INTO Project(Name, StartDate)VALUES('Introduction to SQL Course', '1/1/2006')VALUES('Introduction to SQL Course', '1/1/2006')
SELECT *SELECT * FROM ProjectFROM Project WHERE StartDate = '1/1/2006'WHERE StartDate = '1/1/2006'
DELETE FROMDELETE FROM ProjectProjectWHERE StartDate = '1/1/2006'WHERE StartDate = '1/1/2006'
What is T-SQL?What is TWhat is T--SQL?SQL?
• T-SQL is an extension to the standard SQL language• The standard language in MS SQL Server
database• Supports if statements, loops, exceptions
• Like the high-level procedural programming languages
• Used for writing procedures, functions, triggers, etc.
•• TT--SQL is an extension to the standard SQL is an extension to the standard SQL languageSQL language•• The standard language in MS SQL Server The standard language in MS SQL Server
databasedatabase•• Supports if statements, loops, exceptionsSupports if statements, loops, exceptions
•• Like the highLike the high--level procedural level procedural programming languagesprogramming languages
•• Used for writing procedures, functions, Used for writing procedures, functions, triggers, etc.triggers, etc.
DECLARE emps CURSOR FORDECLARE emps CURSOR FORSELECT EmployeeID, FirstName, LastName FROM SELECT EmployeeID, FirstName, LastName FROM EEmployeemployee
OPEN empsOPEN empsFETCH NEXT FROM emps INTO @EmpId, @EmpFName, @EmpLNameFETCH NEXT FROM emps INTO @EmpId, @EmpFName, @EmpLNameWHILE (@@FETCH_STATUS = 0) BEGINWHILE (@@FETCH_STATUS = 0) BEGINPRINT CAST(@EmpId AS VARCHAR(10)) + PRINT CAST(@EmpId AS VARCHAR(10)) + '' ''+ @EmpFName ++ @EmpFName + ' '' ' + @EmpLName+ @EmpLName
FETCH NEXT FROM emps INTO @EmpId, @EmpFName, @EmpLNameFETCH NEXT FROM emps INTO @EmpId, @EmpFName, @EmpLNameENDENDCLOSE empsCLOSE empsDEALLOCATE empsDEALLOCATE emps
GOGO
The NASD The NASD Database SchemaDatabase Schema
E/R DiagramE/R Diagram
(c) 2006 National Academy for Software Development - http://academy.devbg.org 12
The NASD Database Schema in SQL ServerThe NASD Database The NASD Database Schema in SQL ServerSchema in SQL Server
• SELECT identifies what columns• FROM identifies which table•• SELECT identifies what columnsSELECT identifies what columns•• FROM identifies which tableFROM identifies which table
(c) 2006 National Academy for Software Development - http://academy.devbg.org 13
The NULL ValueThe The NULLNULL ValueValue
• A NULL is a value that is unavailable, unassigned, unknown, or inapplicable• Not the same as zero or a blank space
• Arithmetic expressions containing a NULLvalue are evaluated to NULL
•• A A NULLNULL is a value that is unavailable, is a value that is unavailable, unassigned, unknown, or inapplicableunassigned, unknown, or inapplicable•• Not the same as zero or a blank spaceNot the same as zero or a blank space
•• Arithmetic expressions containing a Arithmetic expressions containing a NULLNULLvalue are evaluated to value are evaluated to NULLNULL
SELECT LastName, ManagerID FROM EmployeeSELECT LastName, ManagerID FROM Employee
11300300NULLNULLManagerIDManagerID
WangWangDuffyDuffySSááncheznchezLastNameLastName
NULL is displayed as empty space or as NULLNULLNULL is displayed as is displayed as
empty space or as empty space or as NULLNULL
Column AliasColumn AliasColumn Alias
• Renames a column heading• Useful with calculations• Immediately follows the column name
• There is an optional AS keyword• Double quotation marks if contains spaces
•• Renames a column headingRenames a column heading•• Useful with calculationsUseful with calculations•• Immediately follows the column nameImmediately follows the column name
•• There is an optional There is an optional ASAS keywordkeyword•• Double quotation marks if contains spacesDouble quotation marks if contains spaces
SELECT FirstName, LastName, Salary,SELECT FirstName, LastName, Salary,Salary*0.2 Salary*0.2 ASAS Bonus FROM EmployeeBonus FROM Employee
• Concatenates columns or character strings to other columns
• Is represented by plus sign “+”• Creates a resultant column that is a
character expression
•• Concatenates columns or character strings Concatenates columns or character strings to other columns to other columns
•• Is represented by plus sign Is represented by plus sign ““++””
•• Creates a resultant column that is a Creates a resultant column that is a character expressioncharacter expressionSELECT FirstName SELECT FirstName ++ ' ' ' ' ++ LastName AS [Full Name],LastName AS [Full Name],EmployeeID as [No.] FROM EmployeeEmployeeID as [No.] FROM Employee
Literal Character StringsLiteral Character StringsLiteral Character Strings
• A literal is a character, a number, or a date included in the SELECT list
• Date and character literal values must be enclosed within single quotation marks
• Each character string is output once for each row returned
•• A literal is a character, a number, or a date A literal is a character, a number, or a date included in the included in the SELECTSELECT listlist
•• Date and character literal values must be Date and character literal values must be enclosed within single quotation marksenclosed within single quotation marks
•• Each character string is output once for each Each character string is output once for each row returnedrow returnedSELECT FirstName + '''s last name is ' +SELECT FirstName + '''s last name is ' +LastName AS [Our Employees] FROM EmployeeLastName AS [Our Employees] FROM Employee
Roberto's last name is TamburelloRoberto's last name is TamburelloKevin's last name is BrownKevin's last name is BrownGuy's last name is GilbertGuy's last name is GilbertOur Our EmployeesEmployees
• The default display of queries is all rows, including duplicate rows
• Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause
•• The default display of queries is all rows, The default display of queries is all rows, including duplicate rowsincluding duplicate rows
•• Eliminate duplicate rows by using the Eliminate duplicate rows by using the DISTINCTDISTINCT keyword in the keyword in the SELECTSELECT clauseclause
SELECT DepartmentIDSELECT DepartmentIDFROM FROM EmployeeEmployee 22
SELECT LastName, SELECT LastName, SalarySalary FROM FROM EmployeeEmployeeWHEREWHERE SalarySalary <= <= 2000020000
(c) 2006 National Academy for Software Development - http://academy.devbg.org 14
• Using BETWEEN operator to specify a range:
• Using IN / NOT IN operators to specify a set of values:
• Using LIKE operator to specify a pattern:
•• Using Using BETWEENBETWEEN operator to specify a range:operator to specify a range:
•• Using Using ININ / / NOT INNOT IN operators to specify a operators to specify a set of values:set of values:
•• Using Using LIKELIKE operator to specify a pattern:operator to specify a pattern:
Other Comparison ConditionsOther Comparison Other Comparison ConditionsConditions
SELECT LastName, SELECT LastName, SalarySalary FROM FROM EmployeeEmployeeWHERE WHERE SalarySalary BETWEENBETWEEN 2000020000 ANDAND 2200022000
SELECT FirstName, LastName, ManagerID FROM SELECT FirstName, LastName, ManagerID FROM EmployeeEmployee WHERE ManagerID WHERE ManagerID ININ (1(10909, , 3, 163, 16))
SELECT FirstName FROM SELECT FirstName FROM EmployeeEmployeeWHERE FirstName WHERE FirstName LIKELIKE 'S%''S%'
• Checking for NULL value:
• Note: COLUMN=NULL is always false!• Using OR and AND operators:
•• Checking for Checking for NULLNULL value:value:
•• Note: Note: COLUMN=NULLCOLUMN=NULL is always false!is always false!•• Using Using OROR and and ANDAND operators:operators:
Other Comparison Conditions (2)Other Comparison Other Comparison Conditions (2)Conditions (2)
SELECT LastName FROM SELECT LastName FROM EmployeeEmployeeWHERE ManagerID WHERE ManagerID IS NULLIS NULL
SELECT FirstName, LastName FROM EmployeeSELECT FirstName, LastName FROM EmployeeWHERE Salary >= 20000 WHERE Salary >= 20000 ANDAND LastName LIKE 'C%'LastName LIKE 'C%'
SELECT LastName FROM EmployeeSELECT LastName FROM EmployeeWHERE ManagerID IS NOT NULLWHERE ManagerID IS NOT NULL
OROR LastName LIKE '%so_'LastName LIKE '%so_'
Sorting with ORDER BYSorting with Sorting with ORDER BYORDER BY
• Sort rows with the ORDER BY clause•ASC: ascending order, default•DESC: descending order
•• Sort rows with the Sort rows with the ORDER BYORDER BY clauseclause•• ASCASC: ascending order, default: ascending order, default•• DESCDESC: descending order: descending order
SELECT LastName, SELECT LastName, HireDate FROM HireDate FROM EmployeeEmployeeORDER BYORDER BY HireDateHireDate
(c) 2006 National Academy for Software Development - http://academy.devbg.org 15
Types of JoinsTypes of JoinsTypes of Joins
• Inner joins• Left outer join• Right outer• Full outer join
•• Inner joinsInner joins•• Left outer joinLeft outer join•• Right outerRight outer•• Full outer joinFull outer join
INNER JOIN with ON ClauseINNER JOININNER JOIN with with ONON ClauseClause
• To specify arbitrary conditions or specify columns to join, the ON clause is used• Such JOIN is called also INNER JOIN
•• To specify arbitrary conditions or specify To specify arbitrary conditions or specify columns to join, the columns to join, the ONON clause is usedclause is used•• Such Such JOINJOIN is called also is called also INNER JOININNER JOIN
SELECT e.EmployeeID, e.LastName, e.DepartmentID, SELECT e.EmployeeID, e.LastName, e.DepartmentID, d.DepartmentID, d.Name AS DepartmentNamed.DepartmentID, d.Name AS DepartmentName
FROM FROM EEmployee e mployee e INNER JOININNER JOIN DDepartment d epartment d
INNER vs. OUTER JoinsINNERINNER vs. vs. OUTEROUTER JoinsJoins
• The join of two tables returning only matched rows is an inner join
• A join between two tables that returns the results of the inner join as well as unmatched rows from the left (or right) table is a left (or right) outer join
• A join between two tables that returns the results of an inner join as well as the results of a left and right join is a full outer join
•• The join of two tables returning only The join of two tables returning only matched rows is an matched rows is an inner joininner join
•• A join between two tables that returns A join between two tables that returns the results of the inner join as well as the results of the inner join as well as unmatched rows from the left (or right) unmatched rows from the left (or right) table is a table is a leftleft (or (or rightright) ) outer joinouter join
•• A join between two tables that returns A join between two tables that returns the results of an inner join as well as the the results of an inner join as well as the results of a left and right join is a results of a left and right join is a full full outer joinouter join
FROM employee e FROM employee e FULL OUTER JOINFULL OUTER JOIN employee memployee mONON e.ManagerID = m.EmployeeIDe.ManagerID = m.EmployeeID
GilbertGilbert11NULLNULL………………
HartwigHartwig1717NULLNULL
………………
………………BrownBrown1616GilbertGilbert
33
NULLNULLMgrIDMgrID
TamburelloTamburello
NULLNULLMgrLastNameMgrLastName
CraciumCracium
SanchezSanchezEmpLastNameEmpLastName
Three-Way JoinsThreeThree--Way JoinsWay Joins
• A three-way join is a join of three tables•• A threeA three--way join is a join of three tablesway join is a join of three tablesSELECT e.FirstName, e.LastName,SELECT e.FirstName, e.LastName,
t.Name as Town, a.AddressTextt.Name as Town, a.AddressTextFROM Employee eFROM Employee e
• You can apply additional conditions in the WHERE clause:
•• You can apply additional conditions in the You can apply additional conditions in the WHEREWHERE clause:clause:SELECT e.EmployeeID, e.LastName, e.DepartmentID, SELECT e.EmployeeID, e.LastName, e.DepartmentID,
d.DepartmentID, d.Name AS DepartmentNamed.DepartmentID, d.Name AS DepartmentNameFROM FROM EEmployee e mployee e
INNER JOIN INNER JOIN DDepartment d epartment d ON e.DepartmentID = d.DepartmentIDON e.DepartmentID = d.DepartmentID
(SELECT MAX(Salary) FROM Employee)(SELECT MAX(Salary) FROM Employee)
SELECT FirstName, LastName, DepartmentID, SalarySELECT FirstName, LastName, DepartmentID, SalaryFROM EmployeeFROM EmployeeWHERE DepartmentID IN WHERE DepartmentID IN
(SELECT DepartmentID FROM Department(SELECT DepartmentID FROM DepartmentWHERE Name='Sales')WHERE Name='Sales')
(c) 2006 National Academy for Software Development - http://academy.devbg.org 17
Nested SELECT Statements With Table AliasesNested Nested SELECTSELECT Statements Statements With Table AliasesWith Table Aliases
• We can refer tables from the main SELECT in the nested SELECT by aliases
• Example: Get the maximal salary for each department and the name of the employee that gets it
•• We can refer tables from the main We can refer tables from the main SELECTSELECT in the nested in the nested SELECTSELECT by aliasesby aliases
•• Example: Get the maximal salary for Example: Get the maximal salary for each department and the name of the each department and the name of the employee that gets itemployee that gets it
SELECT FirstName, LastName, DepartmentID, SalarySELECT FirstName, LastName, DepartmentID, SalaryFROM FROM Employee eEmployee eWHERE Salary = WHERE Salary =
(SELECT MAX(Salary) FROM Employee (SELECT MAX(Salary) FROM Employee WHERE DepartmentID = WHERE DepartmentID = e.DepartmentIDe.DepartmentID))
ORDER BY DepartmentIDORDER BY DepartmentID
• Using the EXISTS operator in SELECTstatements• Find all employees with managers from
the first department
•• Using the Using the EXISTSEXISTS operator in operator in SELECTSELECTstatementsstatements•• Find all employees with managers from Find all employees with managers from
the first departmentthe first department
Using the EXISTS OperatorUsing the Using the EXISTSEXISTS OperatorOperator
(c) 2006 National Academy for Software Development - http://academy.devbg.org 18
MIN() and MAX() FunctionsMIN()MIN() and and MAX()MAX() FunctionsFunctions
• You can use MIN() and MAX() for any data type (int, datetime, varchar, ...)
• Displaying the first and last employee's name in alphabetical order:
•• You can use You can use MIN()MIN() and and MAX()MAX() for any for any data type (data type (intint, , datetimedatetime, , varcharvarchar, ...), ...)
•• Displaying the first and last employee's Displaying the first and last employee's name in alphabetical order:name in alphabetical order:
FROM EmployeeFROM EmployeeWHERE DepartmentID = 16WHERE DepartmentID = 16
22AllCountAllCount
11MgrCountMgrCount
Group Functions in Nested QueriesGroup Functions in Nested Group Functions in Nested QueriesQueries
• For each department display the earliest hired employee
•• For each department display the earliest For each department display the earliest hired employeehired employeeSELECT e.FirstName, e.LastName, e.HireDate, d.NameSELECT e.FirstName, e.LastName, e.HireDate, d.NameFROM Employee e FROM Employee e
JOIN Department dJOIN Department dON e.DepartmentID = d.DepartmentIDON e.DepartmentID = d.DepartmentID
WHERE e.HireDate = WHERE e.HireDate = (SELECT MIN(HireDate) FROM Employee (SELECT MIN(HireDate) FROM Employee WHERE DepartmentID = d.DepartmentID)WHERE DepartmentID = d.DepartmentID)
The GROUP BY StatementThe The GROUP BYGROUP BY StatementStatement
• We can divide rows in a table into smaller groups by using the GROUP BY clause
• The syntax:
• The <group_by_expression> is a list of columns
•• We can divide rows in a table into smaller We can divide rows in a table into smaller groups by using the groups by using the GROUP BYGROUP BY clauseclause
•• The syntax:The syntax:
•• The The <<group_by_expression>group_by_expression> is a list of is a list of columnscolumns
SELECT <SELECT <columns>columns>, <, <group_function(column)>group_function(column)>FROM <FROM <table>table>[WHERE <[WHERE <condition>condition>]][GROUP BY[GROUP BY <<group_by_expression>group_by_expression>]][ORDER BY[ORDER BY <<columnscolumns>>
(c) 2006 National Academy for Software Development - http://academy.devbg.org 19
The GROUP BY StatementThe The GROUP BYGROUP BY StatementStatement
• Example of grouping data:
• The GROUP BY column does not have to be in the SELECT list
•• Example of grouping data:Example of grouping data:
•• The The GROUP BYGROUP BY column does not have to column does not have to be in the be in the SELECTSELECT listlist
SELECT DepartmentID, SUM(Salary) as SalariesCostSELECT DepartmentID, SUM(Salary) as SalariesCostFROM EmployeeFROM EmployeeGROUP BY DepartmentIDGROUP BY DepartmentID
Grouping by Several Columns – ExampleGrouping by Several Grouping by Several Columns Columns –– ExampleExample
• Example of grouping data by several columns:
•• Example of grouping data by several Example of grouping data by several columns:columns:SELECT DepartmentID, JobTitle, SELECT DepartmentID, JobTitle,
SUM(Salary) as Salaries, COUNT(*) as CountSUM(Salary) as Salaries, COUNT(*) as CountFROM EmployeeFROM EmployeeGROUP BY DepartmentID, JobTitleGROUP BY DepartmentID, JobTitle
• When using groups we can select only columns listed in the GROUP BY and grouping functions over the other columns
• Can not select columns not listed in the GROUP BY clause
• Can not apply group functions over the columns in the GROUP BY clause
•• When using groups we can select only When using groups we can select only columns listed in the columns listed in the GROUP BYGROUP BY and and grouping functions over the other columnsgrouping functions over the other columns
•• Can not select columns not listed in the Can not select columns not listed in the GROUP BYGROUP BY clauseclause
•• Can not apply group functions over the Can not apply group functions over the columns in the columns in the GROUP BYGROUP BY clauseclause
SELECT DepartmentID, JobTitle, SELECT DepartmentID, JobTitle, SUM(Salary) AS Cost, MIN(HireDate) as StartDateSUM(Salary) AS Cost, MIN(HireDate) as StartDate
FROM EmployeeFROM EmployeeGROUP BY DepartmentID, JobTitleGROUP BY DepartmentID, JobTitle
Using GROUP BY with HAVING ClauseUsing Using GROUP BYGROUP BY with with HAVINGHAVING ClauseClause
• HAVING works like WHERE but is used for the grouping functions
•• HAVINGHAVING works like works like WHEREWHERE but is used for but is used for the grouping functionsthe grouping functionsSELECT DepartmentID, COUNT(EmployeeID) asSELECT DepartmentID, COUNT(EmployeeID) as
Count, AVG(Salary) AverageSalaryCount, AVG(Salary) AverageSalaryFROM EmployeeFROM EmployeeGROUP BY DepartmentIDGROUP BY DepartmentIDHAVING COUNT(EmployeeID) BETWEEN 3 AND 5HAVING COUNT(EmployeeID) BETWEEN 3 AND 5
(c) 2006 National Academy for Software Development - http://academy.devbg.org 20
Using Grouping Functions and Table JoinsUsing Grouping Functions Using Grouping Functions and Table Joinsand Table Joins
• We can apply grouping function on columns from joined tables
•• We can apply grouping function on We can apply grouping function on columns from joined tablescolumns from joined tablesSELECT COUNT(*) AS EmpCount, d.Name AS DeptNameSELECT COUNT(*) AS EmpCount, d.Name AS DeptNameFROM Employee e FROM Employee e
JOIN Department dJOIN Department dON e.DepartmentID = d.DepartmentIDON e.DepartmentID = d.DepartmentID
WHERE e.HireDate BETWEEN '1999WHERE e.HireDate BETWEEN '1999--22--1' AND '20021' AND '2002--1212--31'31'GROUP BY d.NameGROUP BY d.NameHAVING COUNT(*) > 5HAVING COUNT(*) > 5ORDER BY EmpCount DESCORDER BY EmpCount DESC
FinanceFinance8888
9595EmpCountEmpCount
Information ServicesInformation Services
ProductionProductionDeptNameDeptName
SQL LanguageSQL LanguageInserting Data in TablesInserting Data in Tables
Inserting DataInserting DataInserting Data
• INSERT command• INSERT INTO <table> VALUES (<values>)
• INSERT INTO <table>(<columns>) VALUES (<values>)
• INSERT INTO <table> SELECT <values>
•• INSERTINSERT commandcommand•• INSERT INTO <table> VALUES (<values>)INSERT INTO <table> VALUES (<values>)
•• INSERT INTO <table>(<columns>) VALUES INSERT INTO <table>(<columns>) VALUES (<values>)(<values>)
•• INSERT INTO <table> SELECT <values>INSERT INTO <table> SELECT <values>
INSERT INTO EmployeeProjectINSERT INTO EmployeeProjectVALUES (229, 25)VALUES (229, 25)
INSERT INTO Project(Name, StartDate)INSERT INTO Project(Name, StartDate)VALUES ('New project', GETDATE())VALUES ('New project', GETDATE())
INSERT INTO Project(Name, StartDate)INSERT INTO Project(Name, StartDate)SELECT Name + ' Restructuring', GETDATE()SELECT Name + ' Restructuring', GETDATE()FROM DepartmentFROM Department
SQL LanguageSQL LanguageUpdating Data in TablesUpdating Data in Tables
Updating DataUpdating DataUpdating Data
• UPDATE command• UPDATE <table> SET <column=expression> WHERE <condition>
• Note: Don't forget the WHERE clause!
•• UPDATEUPDATE commandcommand•• UPDATE <table> SET UPDATE <table> SET <column=expression> WHERE <condition><column=expression> WHERE <condition>
•• Note: Don't forget the WHERE clause!Note: Don't forget the WHERE clause!
• COALESCE(<value>,<default_value>) –converts NULL values to given default value
•• COALESCECOALESCE(<value>,<default_value>)(<value>,<default_value>) ––converts converts NULLNULL values to given default valuevalues to given default value
SELECT Name AS [Project Name], SELECT Name AS [Project Name], COALESCE(EndDate, GETDATE())COALESCE(EndDate, GETDATE()) AS [End Date]AS [End Date]
SELECT LastName, LEN(LastName) AS LastNameLen,SELECT LastName, LEN(LastName) AS LastNameLen,UPPER(LastName) AS UpperLastNameUPPER(LastName) AS UpperLastName
---- 112 is the ISO formatting style YYYYMMDD112 is the ISO formatting style YYYYMMDD
Combining Functions UseCombining Functions UseCombining Functions Use
• We can combine functions to achieve more complex behavior
•• We can combine functions to achieve We can combine functions to achieve more complex behaviormore complex behaviorSELECT Name AS [Project Name], SELECT Name AS [Project Name],
COALESCE(CONVERT(nvarchar(50), EndDate), COALESCE(CONVERT(nvarchar(50), EndDate), 'Not Finished') AS [Date Finished]'Not Finished') AS [Date Finished]
FROM ProjectFROM Project
Jun 1 2003 12:00AMJun 1 2003 12:00AMHL Mountain Front WheelHL Mountain Front Wheel