Introduction to SQL, Part II                              (with Microsoft SQL Server)Svetlin NakovManager Technical Traine...
Table of Contents1.   Nested SELECT Statements2.   Aggregating Data      Group Functions and GROUP BY3.   Microsoft SQL S...
SQL LanguageNested SELECT Statements
Nested SELECT Statements SELECT statements can be nested in the where clause  SELECT FirstName, LastName, Salary  FROM Em...
Nested SELECT Statements                        with Table Aliases Tables from the main SELECT can be referred in the nes...
Using the EXISTS Operator Using the EXISTS operator in SELECT statements  Find all employees with managers from the firs...
SQL LanguageAggregating Data with Group Functions
Group Functions Group functions operate over sets    of rows to give one single result (per group)    EmployeeID Salary  ...
Group Functions in SQL COUNT(*) – count of the selected rows SUM(column) – sum of the values   in given column from the ...
AVG() and SUM() Functions You can use AVG() and SUM() only for numeric data types  SELECT    AVG(Salary) [Average Salary]...
MIN() and MAX() Functions You can use MIN() and MAX() for almost any data type (int, datetime, varchar, ...)   SELECT MIN...
The COUNT(…) Function   COUNT(*) returns the number of rows in the    result record set    SELECT COUNT(*) Cnt FROM Emplo...
Group Functions and NULLs Group functions ignore      NULL values in the target column   SELECT AVG(ManagerID) Avg,     S...
Group Functions in Nested Queries Find the earliest   hired employee for each department  SELECT e.FirstName, e.LastName,...
SQL LanguageGroup Functions and the GROUP BY Statement
Creating Groups of DataEmployeesDepartmentID Salary12           1030012           1680012           16800    7200012      ...
The GROUP BY Statement   We can divide rows in a table into smaller groups    by using the GROUP BY clause   The SELECT ...
The GROUP BY Statement (2) Example of grouping data:  SELECT DepartmentID, SUM(Salary) as SalariesCost  FROM Employees  G...
Grouping by Several ColumnsDepart-        JobTitle      SalarymentID        Network                3970011                ...
Grouping by Several                              Columns – Example Example of grouping data by several columns:   SELECT ...
Illegal Use of Group Functions This SELECT statement is       illegal:   SELECT DepartmentID, COUNT(LastName)   FROM Empl...
Restrictions for Grouping   When using groups we can select only columns    listed in the GROUP BY and grouping functions...
Using GROUP BY with                              HAVING Clause HAVING works likeWHERE but is used for the grouping functi...
Using Grouping Functions                               and Table Joins   Grouping function can be applied on columns    f...
SQL Language SQL Server Functions
Standard Functions in                        Microsoft SQL Server Single-row functions   String functions   Mathematica...
COALESCE() Function   COALESCE(<value>,<default_value>) –    converts NULL values to given default value     SELECT Name ...
String Functions Changing the casing     – LOWER, UPPER Manipulatingcharacters – SUBSTRING, LEN, LEFT, RIGHT, LTRIM, REP...
Other Functions Mathematical Functions – ROUND, FLOOR, POWER, ABS, SQRT, …  SELECT FLOOR(3.14)  3  SELECT ROUND(5.86, 0)...
Combining Functions We can combine functions to achieve more complex behavior   SELECT Name AS [Projects Name],     COALE...
SQL LanguageData Definition Language (DDL)
Data Definition Language DDL commands for defining / editing objects    CREATE    ALTER    DROP Data ControlLanguage ...
Creating Database Objects   CREATE command     CREATE TABLE <name> (<field_definitions>)     CREATE VIEW <name> AS <sel...
Creating Objects – More ExamplesCREATE TABLE Countries (  CountryID int IDENTITY,  Name nvarchar(100) NOT NULL,  CONSTRAIN...
Modifying Database Objects   ALTER command     ALTER TABLE <name> <command>     ALTER <object> <command>    -- Add a fo...
Deleting Database Objects DROP command   DROP TABLE <name>   DROP TRIGGER <name>   DROP INDEX <name>   DROP <object> ...
Managing Access Permissions GRANT command  GRANT <persmission> ON <object> TO <role>  Example:  GRANT SELECT ON Persons ...
Creating Tables in SQL Server          Best Practices
Creating Tables in SQL Server Creating new table:   Define the table name    Should have good name   Define the column...
Creating Tables in SQL                          Server – ExamplesCREATE TABLE Groups (  GroupID int IDENTITY,  Name nvarch...
TransactionsBegin / Commit / Rollback Transactions in SQL Server
What Is Concurrency Control? Pessimistic   locking (default in SQL Server)   Locks table data at each data is modificati...
Transactions Transactions           start by executing BEGIN TRANSACTION (or just BEGIN TRAN) Use COMMIT to confirm chan...
The Implicit Transactions Option What is   implicit transactions mode?   Automatically start a new transaction after    ...
Introduction to SQL, Part II    курсове и уроци по програмиране, уеб дизайн – безплатно     BG Coder - онлайн състезателна...
Free Trainings @ Telerik Academy "C# and Databases       " course @ Telerik    Academy       academy.telerik.com/…csharp...
Upcoming SlideShare
Loading in...5
×

8. Intro to SQL Part 2 - C# and Databases

1,955

Published on

Introduction to SQL, Part II (with Microsoft SQL Server)
Telerik Software Academy: http://academy.telerik.com/school-academy/meetings/details/2012/01/06/desktop-applications-csharp-databases
The website and all video materials are in Bulgarian.
Nested SELECT Statements
Aggregating Data
Group Functions and GROUP BY
Microsoft SQL Server Functions
SQL Server Data Types
Data Definition Language (DDL)
Creating Tables in MS SQL Server
Naming Conventions

Published in: Education, Technology, Business
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,955
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
330
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Transcript of "8. Intro to SQL Part 2 - C# and Databases"

  1. 1. Introduction to SQL, Part II (with Microsoft SQL Server)Svetlin NakovManager Technical Trainerhttp://www.nakov.com/Telerik Software Academyhttp://academy.telerik.com/
  2. 2. Table of Contents1. Nested SELECT Statements2. Aggregating Data  Group Functions and GROUP BY3. Microsoft SQL Server Functions4. SQL Server Data Types5. Data Definition Language (DDL)6. Creating Tables in MS SQL Server7. Naming Conventions 2
  3. 3. SQL LanguageNested SELECT Statements
  4. 4. Nested SELECT Statements SELECT statements can be nested in the where clause SELECT FirstName, LastName, Salary FROM Employees WHERE Salary = (SELECT MAX(Salary) FROM Employees) SELECT FirstName, LastName, DepartmentID, Salary FROM Employees WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE Name=Sales)  Note: always prefer joins to nested SELECT statements for better performance 4
  5. 5. Nested SELECT Statements with Table Aliases Tables from the main SELECT can be referred in the nested SELECT by aliases Example:  Find the maximal salary for each department and the name of the employee that gets it SELECT FirstName, LastName, DepartmentID, Salary FROM Employees e WHERE Salary = (SELECT MAX(Salary) FROM Employees WHERE DepartmentID = e.DepartmentID) ORDER BY DepartmentID 5
  6. 6. Using the EXISTS Operator Using the EXISTS operator in SELECT statements  Find all employees with managers from the first department SELECT FirstName, LastName, EmployeeID, ManagerID FROM Employees e WHERE EXISTS (SELECT EmployeeID FROM Employees m WHERE m.EmployeeID = e.ManagerID AND m.DepartmentID = 1) 6
  7. 7. SQL LanguageAggregating Data with Group Functions
  8. 8. Group Functions Group functions operate over sets of rows to give one single result (per group) EmployeeID Salary 1 12500,00 2 13500,00 MAX(Salary) 3 43300,00 125500,00 4 29800,00 5 25000,00 ... ... 8
  9. 9. Group Functions in SQL COUNT(*) – count of the selected rows SUM(column) – sum of the values in given column from the selected rows AVG(column) – average of the values in given column MAX(column) – the maximal value in given column MIN(column) – the minimal value in given column 9
  10. 10. AVG() and SUM() Functions You can use AVG() and SUM() only for numeric data types SELECT AVG(Salary) [Average Salary], MAX(Salary) [Max Salary], MIN(Salary) [Min Salary], SUM(Salary) [Salary Sum] FROM Employees WHERE JobTitle = Design Engineer Average Salary Max Salary Min Salary Salary Sum 32700.00 32700.00 32700.00 98100.00 10
  11. 11. MIN() and MAX() Functions You can use MIN() and MAX() for almost any data type (int, datetime, varchar, ...) SELECT MIN(HireDate) MinHD, MAX(HireDate) MaxHD FROM Employees MinHD MaxHD 1996-07-31 2003-06-03 Displayingthe first and last employees name in alphabetical order: SELECT MIN(LastName), MAX(LastName) FROM Employees 11
  12. 12. The COUNT(…) Function COUNT(*) returns the number of rows in the result record set SELECT COUNT(*) Cnt FROM Employees Cnt WHERE DepartmentID = 3 18 COUNT(expr) returns the number of rows with non-null values for the expr SELECT COUNT(ManagerID) MgrCount, MgrCount AllCount COUNT(*) AllCount 1 2 FROM Employees WHERE DepartmentID = 16 12
  13. 13. Group Functions and NULLs Group functions ignore NULL values in the target column SELECT AVG(ManagerID) Avg, SUM(ManagerID) / COUNT(*) AvgAll FROM Employees Avg AvgAll 108 106 If each NULL value in the ManagerID column were considered as 0 in the calculation, the result would be 106 13
  14. 14. Group Functions in Nested Queries Find the earliest hired employee for each department SELECT e.FirstName, e.LastName, e.HireDate, d.Name FROM Employees e JOIN Departments d ON e.DepartmentID = d.DepartmentID WHERE e.HireDate = (SELECT MIN(HireDate) FROM Employees WHERE DepartmentID = d.DepartmentID) FirstName LastName HireDate Name Guy Gilbert 1998-07-31 00:00:00 Production Kevin Brown 1999-02-26 00:00:00 Marketing Roberto Tamburello 1999-12-12 00:00:00 Engineering 14
  15. 15. SQL LanguageGroup Functions and the GROUP BY Statement
  16. 16. Creating Groups of DataEmployeesDepartmentID Salary12 1030012 1680012 16800 7200012 10300 Depart- SUM12 17800 mentID (Salary)2 28800 12 720002 25000 108600 2 1086002 29800 16 1856002 25000 ... ...16 125500 18560016 60100... ... 16
  17. 17. The GROUP BY Statement We can divide rows in a table into smaller groups by using the GROUP BY clause The SELECT + GROUP BY syntax: SELECT <columns>, <group_function(column)> FROM <table> [WHERE <condition>] [GROUP BY <group_by_expression> ] [HAVING <filtering_expression>] [ORDER BY <columns> The <group_by_expression> is a list of columns 17
  18. 18. The GROUP BY Statement (2) Example of grouping data: SELECT DepartmentID, SUM(Salary) as SalariesCost FROM Employees GROUP BY DepartmentID DepartmentID SalariesCost 12 72000 2 108600 16 185600 ... ... The GROUP BY column is not necessary needed to be in the SELECT list 18
  19. 19. Grouping by Several ColumnsDepart- JobTitle SalarymentID Network 3970011 39700 Manager Depart JobTitle Salary Network mentID11 32500 Administrator Network 65000 11 39700 Network Manager11 32500 Administrator Network 11 65000 Database Administrator11 38500 Administrator Database 77000 11 77000 Database Administrator11 38500 Administrator 10 Accountant 5280010 Accountant 26400 Finance 52800 10 4330010 Accountant 26400 Manager Finance ... ... ...10 43300 43300 Manager... ... ... 19
  20. 20. Grouping by Several Columns – Example Example of grouping data by several columns: SELECT DepartmentID, JobTitle, SUM(Salary) as Salaries, COUNT(*) as Count FROM Employees GROUP BY DepartmentID, JobTitle DepartmentID JobTitle Salaries Count 2 Senior Tool Designer 58600 2 2 Tool Designer 50000 2 7 Production Supervisor 525000 21 7 Production Technician 1926000 157 ... ... ... ... 20
  21. 21. Illegal Use of Group Functions This SELECT statement is illegal: SELECT DepartmentID, COUNT(LastName) FROM Employees  Can not combine columns with groups functions unless when using GROUP BY This SELECT statement is also illegal SELECT DepartmentID, AVG(Salary) FROM Employees WHERE AVG(Salary) > 30 GROUP BY DepartmentID  Can not use WHERE for group functions 21
  22. 22. Restrictions for Grouping When using groups we can select only columns listed in the GROUP BY and grouping functions over the other columns SELECT DepartmentID, JobTitle, SUM(Salary) AS Cost, MIN(HireDate) as StartDate FROM Employees GROUP BY DepartmentID, JobTitle  Can not select columns not listed in the GROUP BY clause  It is allowed to apply group functions over the columns in the GROUP BY clause, but has no sense 22
  23. 23. Using GROUP BY with HAVING Clause HAVING works likeWHERE but is used for the grouping functions SELECT DepartmentID, COUNT(EmployeeID) as Count, AVG(Salary) AverageSalary FROM Employees GROUP BY DepartmentID HAVING COUNT(EmployeeID) BETWEEN 3 AND 5 DepartmentID Count AverageSalary 2 4 27150 12 5 14400 … … … 23
  24. 24. Using Grouping Functions and Table Joins Grouping function can be applied on columns from joined tables SELECT COUNT(*) AS EmpCount, d.Name AS DeptName FROM Employees e JOIN Departments d ON e.DepartmentID = d.DepartmentID WHERE e.HireDate BETWEEN 1999-2-1 AND 2002-12-31 GROUP BY d.Name HAVING COUNT(*) > 5 ORDER BY EmpCount DESC EmpCount DeptName 95 Production 8 Finance 8 Information Services 24
  25. 25. SQL Language SQL Server Functions
  26. 26. Standard Functions in Microsoft SQL Server Single-row functions  String functions  Mathematical functions  Date functions  Conversion functions Multiple-row functions  Aggregate functions 26
  27. 27. COALESCE() Function COALESCE(<value>,<default_value>) – converts NULL values to given default value SELECT Name AS [Projects Name], COALESCE(EndDate, GETDATE()) AS [End Date] FROM Projects Projects Name End Date Classic Vest 2006-07-02 08:19:43.983 Cycling Cap 2003-06-01 00:00:00.000 Full-Finger Gloves 2003-06-01 00:00:00.000 Half-Finger Gloves 2003-06-01 00:00:00.000 HL Mountain Frame 2003-06-01 00:00:00.000 ... ... 27
  28. 28. String Functions Changing the casing – LOWER, UPPER Manipulatingcharacters – SUBSTRING, LEN, LEFT, RIGHT, LTRIM, REPLACE SELECT LastName, LEN(LastName) AS LastNameLen, UPPER(LastName) AS UpperLastName FROM Employees WHERE RIGHT(LastName, 3) = son LastName LastNameLen UpperLastName Erickson 8 ERICKSON Johnson 7 JOHNSON Munson 6 MUNSON ... ... ... 28
  29. 29. Other Functions Mathematical Functions – ROUND, FLOOR, POWER, ABS, SQRT, … SELECT FLOOR(3.14)  3 SELECT ROUND(5.86, 0)  6.00 Date Functions – GETDATE, DATEADD, DAY, MONTH, YEAR, … Conversion Functions – CONVERT, CAST SELECT CONVERT(DATETIME, 20051231, 112)  2005-12-31 00:00:00.000 -- 112 is the ISO formatting style YYYYMMDD 29
  30. 30. Combining Functions We can combine functions to achieve more complex behavior SELECT Name AS [Projects Name], COALESCE(CONVERT(nvarchar(50), EndDate), Not Finished) AS [Date Finished] FROM Projects Projects Name Date Finished HL Mountain Front Wheel Jun 1 2003 12:00AM LL Touring Handlebars Not Finished HL Touring Handlebars Not Finished LL Road Front Wheel Jun 1 2003 12:00AM ... ... 30
  31. 31. SQL LanguageData Definition Language (DDL)
  32. 32. Data Definition Language DDL commands for defining / editing objects  CREATE  ALTER  DROP Data ControlLanguage (DCL) for managing access permissions  GRANT  REVOKE  DENY 32
  33. 33. Creating Database Objects CREATE command  CREATE TABLE <name> (<field_definitions>)  CREATE VIEW <name> AS <select>  CREATE <object> <definition> CREATE TABLE Persons ( PersonID int IDENTITY, Name nvarchar(100) NOT NULL, CONSTRAINT PK_Persons PRIMARY KEY(PersonID) ) GO CREATE VIEW [First 10 Persons] AS SELECT TOP 10 Name FROM Persons 33
  34. 34. Creating Objects – More ExamplesCREATE TABLE Countries ( CountryID int IDENTITY, Name nvarchar(100) NOT NULL, CONSTRAINT PK_Countries PRIMARY KEY(CountryID))GOCREATE TABLE Cities ( CityID int IDENTITY, Name nvarchar(100) NOT NULL, CountryID int NOT NULL, CONSTRAINT PK_Cities PRIMARY KEY(CityID)) 34
  35. 35. Modifying Database Objects ALTER command  ALTER TABLE <name> <command>  ALTER <object> <command> -- Add a foreign key constraint Cities --> Country ALTER TABLE Cities ADD CONSTRAINT FK_Cities_Countries FOREIGN KEY (CountryID) REFERENCES Countries(CountryID) -- Add column Population to the table Country ALTER TABLE Countries ADD COLUMN Population int -- Remove column Population from the table Country ALTER TABLE Countries DROP COLUMN Population 35
  36. 36. Deleting Database Objects DROP command  DROP TABLE <name>  DROP TRIGGER <name>  DROP INDEX <name>  DROP <object> DROP TABLE Persons ALTER TABLE Cities DROP CONSTRAINT FK_Cities_Countries 36
  37. 37. Managing Access Permissions GRANT command GRANT <persmission> ON <object> TO <role>  Example: GRANT SELECT ON Persons TO public REVOKE command REVOKE <persmission> ON <object> FROM <role>  Example: REVOKE SELECT ON Employees FROM public 37
  38. 38. Creating Tables in SQL Server Best Practices
  39. 39. Creating Tables in SQL Server Creating new table:  Define the table name  Should have good name  Define the columns and their types  Use proper data type  Define the table primary key  Use IDENTITY for enabling auto increment of the primary key  Define foreign/keys and constraints 39
  40. 40. Creating Tables in SQL Server – ExamplesCREATE TABLE Groups ( GroupID int IDENTITY, Name nvarchar(100) NOT NULL, CONSTRAINT PK_Groups PRIMARY KEY(GroupID))CREATE TABLE Users ( UserID int IDENTITY, UserName nvarchar(100) NOT NULL, GroupID int NOT NULL, CONSTRAINT PK_Users PRIMARY KEY(UserID), CONSTRAINT FK_Users_Groups FOREIGN KEY(GroupID) REFERENCES Groups(GroupID)) 40
  41. 41. TransactionsBegin / Commit / Rollback Transactions in SQL Server
  42. 42. What Is Concurrency Control? Pessimistic locking (default in SQL Server)  Locks table data at each data is modification  Concurrent users are blocked until the lock is released Optimistic locking (default in Oracle)  No locks are performed when data is being read or changed  Concurrent users don’t see the changes until they are committed / rolled-back  Supported with SNAPSHOT isolation in SQL Server 42
  43. 43. Transactions Transactions start by executing BEGIN TRANSACTION (or just BEGIN TRAN) Use COMMIT to confirm changes and finish the transaction Use ROLLBACK to cancel changes and abort the transaction Example: BEGIN TRAN DELETE FROM EmployeesProjects; DELETE FROM Projects; ROLLBACK TRAN 43
  44. 44. The Implicit Transactions Option What is implicit transactions mode?  Automatically start a new transaction after each commit or rollback  Nested transactions are not allowed  Transaction must be explicitly completed with COMMIT or ROLLBACK TRANSACTION By default, IMPLICIT_TRANSACITONS setting is switched off SET IMPLICIT_TRANSACTIONS ON 44
  45. 45. Introduction to SQL, Part II курсове и уроци по програмиране, уеб дизайн – безплатно BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране – Телерик академия форум програмиране, форум уеб дизайн уроци по програмиране и уеб дизайн за ученици ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET http://academy.telerik.com програмиране за деца – безплатни курсове и уроци ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC безплатен SEO курс - оптимизация за търсачки алго академия – състезателно програмиране, състезаниякурсове и уроци по програмиране, книги – безплатно от Наков курс мобилни приложения с iPhone, Android, WP7, PhoneGap уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop Дончо Минков - сайт за програмиране free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране безплатен курс "Качествен програмен код" безплатен курс "Разработка на софтуер в cloud среда" C# курс, програмиране, безплатно
  46. 46. Free Trainings @ Telerik Academy "C# and Databases " course @ Telerik Academy  academy.telerik.com/…csharp-databases Telerik Software Academy  academy.telerik.com Telerik Academy @ Facebook  facebook.com/TelerikAcademy Telerik Software Academy Forums  forums.academy.telerik.com 46
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×