You are on page 1of 141

te

.
e
s
our

m
o
c
.
k
l eri

c
Database
Modeling
mvc
and Introduction to
SQL

Creating E/R Diagrams with SQL Server
Management Studio, Writing SQL Queries
Doncho Minkov
Technical Trainer
http://www.minkov.it
Telerik Software Academy
academy.telerik.com

Table of Contents
Data Modeling – Principles
Data Types in SQL Server
Creating Databases in SQL Server
Creating Tables
Defining a Primary Key and
Identity Columns
Creating Relationships between
the Tables

1.
2.
3.
4.
5.

6.


7.

One-to-many, Many-to-many, Oneto-one

Naming conventions

2

Table of Contents (2)
8.
9.

Nested SELECT Statements
Aggregating Data
Group Functions and GROUP BY

10. Microsoft

SQL Server Functions
11. SQL Server Data Types
12. Data Definition Language (DDL)
13. Creating Tables in MS SQL Server
14. Naming Conventions

3

The Telerik Academy Database Schema 17.Table of Contents (3) 15. Introducing the SELECT SQL Statement Allowed Operators The WHERE Clause Sorting with ORDER BY Selecting Data From Multiple Tables 4 . SQL and T-SQL Languages 16.

Right and Full Outer Joins Cross Joins Inserting Data 20. Updating Data 21. Selecting Data From Multiple Tables Natural Joins Join with USING Clause Inner Joins with ON Clause Left. Deleting Data 19. 5 .Table of Contents (4) 18.

Relational Data Modeling Fundamental Concepts .

Steps in Database Design  Steps in the database design process:  Identification of the entities  Identification of the columns in the tables  Defining a primary key for each entity table  Identification and modeling of relationships  Multiplicity of relationships  Defining other constraints 7 .

The courses are held in different towns. photo and date.Identification of Entities  Entity tables represent objects from the real world  Most often they are nouns in the specification  For example: We need to develop a system that stores information about students. faculty number. which are trained in various courses.  Entities: Student. Course. When registering a new student the following information is entered: name. Town 8 .

Identification of Columns  Columns in the tables are characteristics of the entities  They have name and type  For example students have:     Name (text) Faculty number (number) Photo (binary block) Date of enlistment (date) 9 .

photo. The courses are held in different towns. When registering a new student the following information is entered: name. faculty number. date of 10 . which are trained in various courses.Identification of the Columns  Columns are clarifications for the entities in the text of the specification. faculty number. photo and date.  Students have the following characteristics:  Name. for example: We need to develop a system that stores information about students.

 How to Choose a Primary Key? Always define an additional column for the primary key  Don't use an existing column (for example SSN)  Must be an integer number  Must be declared as a primary key  Use identity to implement autoincrement  Put the primary key as a first column  Exceptions 11 .

Identification of Relationships  Relationships are dependencies between the entities: We need to develop a system that stores information about students. photo and date. When registering a new student the following information is entered: name. faculty number.  "Students are trained in courses" – many-to-many relationship  "Courses are held in towns" – manyto-one (or many-to-many) relationship 12 . which are trained in various courses. The courses are held in different towns.

Data Types in SQL Server 2008 .

 Numeric Data Types in SQL Server  bit (1-bit). precision)  money – for money (precise) operations  Strings  char(size) – fixed size string  varchar(size) – variable size string  nvarchar(size) – Unicode variable 14 . real. integer (32-bit). bigint (64-bit)  float. numeric(scale.

1.  smalldatetime – date and time (1minute precision) 15 .1753 to 31. Binary data Data Types in SQL Server (2)  varbinary(size) – a sequence of bits  image – a binary block up to 1 GB  Date and time  datetime – date and time starting from 1.12. a precision of 1/300 sec. 9999.

Data Types in SQL Server (3)  Other types  timestamp – automatically generated number whenever a change is made to the data row  uniqueidentifier – GUID identifier  xml – data in XML format 16 .

Data Types in SQL Server (4)  Nullable and NOT NULL types  All types in SQL Server may or may not allow NULL values  Primary key columns  Define the primary key  Identity columns  Automatically increased values when a new row is inserted (autoincrement values)  Used in combination with primary key 17 .

Database Modeling with SQL Server Management Studio Creating Database .

Connecting to SQL Server When starting SSMS a window pops up  Usually it is enough to just click the "Connect" button without changing anything  19 .

stored procedures.Working with Object Explorer  Object Explorer is the main tool to use when working with the database and its objects  Enables us:  To create a new database  To create objects in the database (tables. relationships and others)  To change the properties of objects  To enter records into the tables 20 .

Creating a New Database  In Object Explorer we go to the "Databases" and choose "New Database…" from the context menu 21 .

Creating a New Database (2)  In the "New Database" window enter the name of the new database and click [OK] 22 .

Database Modeling with SQL Server Management Studio Creating E/R Diagrams .

Creating an E/R diagram  In the "Database Diagrams" menu choose the "New Database Diagram"  We can choose from the existing tables. which we want to add to the diagram 24 .

Database Modeling with SQL Server Management Studio Creating Tables .

Creating Tables If the database doesn't show immediately in Object Explorer perform "Refresh" [F5]  Creating new table:  26 .

Creating Tables (2)  Enter table name and define the table columns (name and type): Enter the name of the column here Choose the data type of the column here Choose whether NULLs are allowed 27 .

Creating Tables (3)  Defining a primary key Right click on the column start and select "Set Primary Key" 28 .

Creating Tables (4)

Defining an identity columns
 Identity means that the values in a
certain column are auto generated
(for int columns)
 These values cannot be assigned
manually
 Identity Seed – the starting number
from which the values in the column
begin to increase.
 Identity Increment – by how much
each consecutive value is increased
29

Creating Tables (5)

Setting an
identity
through the
"Column
Properties"
window

30

Creating Tables (6)

It is a good
practice to set the
name of the table
at the time it is
created
 Use the
"Properties"
window
 If it's not visible
use "View" 
"Properties
Window" or press

Tabl
ena
me

31

SSMS asks whether to save the table  You can do it manually by choosing “Save Table” from the “File” menu or by pressing Ctrl + S 32 .Creating Tables (7)  When closing the window for the table.

Database Modeling with SQL Server Management Studio Creating Relationships between Tables .

Creating Relationships  To create one-to-many relationship drag the foreign key column onto the other table  Drag from the child table to the parent table 34 .

Self-Relationships  Self-relationship can be created by dragging a foreign key onto the same table 35 .

Database Modeling with SQL Server Management Studio Naming Conventions .

key. PhotoAlbums. int.Naming Conventions  Tables  Each word is capitalized (Pascal Case)  In English. plural  Examples: Users.g. singular  Each word is capitalized (Pascal Case)  Avoid reserved words (e. Countries  Columns  In English. 37 .

Naming Conventions (2)  Primary key  Use "Id" or name_of_the_table + "Id"  Example: in the Users table the PK column should be called Id or UserId  Foreign key  Use the name of the referenced table + "Id"  Example: in the Users table the foreign key column that references the Groups table should be named 38 .

Naming Conventions (3)  Relationship names (constraints)  In English. Pascal Case  "FK_" + first_table + "_" + second_table  For example: FK_Users_Groups  Index names  "IX_" + table + column  For example: IX_Users_UserName 39 .

 Naming Conventions (4) Unique key constraints names  "UK_" + table + column  For instance: UK_Users_UserName  Views names  V_ + name  Example: V_BGCompanies  Stored procedures names  usp_ + name  Example: usp_InsertCustomer(@name) 40 .

Database Modeling with SQL Server Management Studio Live Demo .

Relational Databases and SQL The SQL Execution Model .

A Relational Databases and SQL relational database can be accessed and modified by executing SQL statements  SQL allows  Defining / modifying the database schema  Searching / modifying table data  A set of SQL commands are available for extracting subset of the table data  43 .

Communicating with the DB SQL statemen t is sent to the DB server SELECT Name FROM Departments Databas e Name Engineering Sales Marketing … d e n r u t e r s ti The resul set) d r o c e r sa a y l l a u s (u 44 .

SQL Execution  SQL commands are executed through a database connection  DB connection is a channel between the client and the SQL server  DB connections take resources and should be closed when no longer used  Multiple clients can be connected to the SQL server at the same time  SQL commands can be executed in parallel  45 .

SQL and T-SQL Introduction .

INSERT.What is SQL?  Structured Query Language (SQL)  Declarative language for query and manipulation of relational data  SQL consists of:  Data Manipulation Language (DML)  SELECT. ALTER  GRANT. UPDATE. DROP. REVOKE 47 . DELETE  Data Definition Language (DDL)  CREATE.

SQL – Few Examples SELECT FirstName. JobTitle FROM Employees SELECT * FROM Projects WHERE StartDate = '1/1/2006' INSERT INTO Projects(Name. LastName. '1/1/2006') UPDATE Projects SET EndDate = '8/31/2006' WHERE StartDate = '1/1/2006' DELETE FROM Projects WHERE StartDate = '1/1/2006' 48 . StartDate) VALUES('Introduction to SQL Course'.

functions. 49 .What is T-SQL?  T-SQL (Transact SQL) is an extension to the standard SQL language  T-SQL is the standard language used in MS SQL Server  Supports if statements. etc. exceptions  Constructions used in the highlevel procedural programming languages  T-SQL is used for writing stored procedures. loops. triggers.

T-SQL – Example CREATE PROCEDURE EmpDump AS DECLARE @EmpId INT. @EmpFName. @EmpFName NVARCHAR(100). @EmpLName NVARCHAR(100) DECLARE emps CURSOR FOR SELECT EmployeeID. LastName FROM Employees OPEN emps FETCH NEXT FROM emps INTO @EmpId. @EmpLName END CLOSE emps DEALLOCATE emps GO 50 . @EmpFName. FirstName. @EmpLName WHILE (@@FETCH_STATUS = 0) BEGIN PRINT CAST(@EmpId AS VARCHAR(10)) + ' ' + @EmpFName + ' ' + @EmpLName FETCH NEXT FROM emps INTO @EmpId.

SQL Language Introducing SELECT Statement .

Capabilities of SQL SELECT Projection Take some of the columns Table 1 Selection Take some of the rows Table 1 Join Combin e tables by some Table 1 column Table 2 52 .

The Telerik Academy
Database Schema in SQL
Server

53

Basic SELECT
Statement
SELECT *|{[DISTINCT] column|expression
[alias],...}
FROM table

 SELECT identifies what columns
 FROM identifies which table

54

SELECT Example

Selecting all columns from
departments
SELECT * FROM Departments
Departmen
tID

Name

ManagerI
D

1

Engineering

12

2

Tool design

4

3

Sales

273

Selecting specific columns
SELECT
DepartmentID,
Name
FROM Departments

Departmen Name
tID
1

Engineering

2

Tool design

3

Sales

55

00 43600. /  Examples: SELECT (2 + 3) * 4 --> returns 20 SELECT LastName.00 13800.00 56 .00 12800.00 Tamburello 43300.Arithmetic Operations  Arithmetic operators are available:  +. Salary. Salary + 300 FROM Employees LastName Salary (No column name) Gilbert 12500. -. *.00 Brown 13500.

or inapplicable  Not the same as zero or a blank space  Arithmetic expressions containing a NULL value are evaluated to NULL SELECT LastName. ManagerID FROM Employees LastNam ManagerI e D Sánchez NULL Duffy 300 Wang 1 NULL is displayed as empty space or as NULL 57 . unassigned. unknown.The NULL Value  A NULL is a value that is unavailable.

00000 Kevin Brown 13500.00 2700. LastName.00000 58 .00 2500.Column Aliases Aliases rename a column heading  Useful with calculations  Immediately follows the column name   There is an optional AS keyword  Double quotation marks if contains spaces SELECT FirstName.2 AS Bonus FROM Employees FirstNam e LastName Salary Bonus Guy Gilbert 12500. Salary*0. Salary.

] FROM Employees Full Name No. EmployeeID as [No. Guy Gilbert 1 Kevin Brown 2 Roberto Tamburello 3 59 .Concatenation Operator Concatenates columns or character strings to other columns  Is represented by plus sign “+”  Creates a resultant column that is a character expression  SELECT FirstName + ' ' + LastName AS [Full Name].

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 each+ row returned SELECTfor FirstName '''s last name is ' +  LastName AS [Our Employees] FROM Employees Our Employees Guy's last name is Gilbert Kevin's last name is Brown Roberto's last name is Tamburello 60 .Literal Character Strings A literal is a character.

including duplicate rows DepartmentID 7 SELECT DepartmentID FROM Employees  7 2 .. Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause SELECT DISTINCT DepartmentID FROM Employees DepartmentID 7 2 .Removing Duplicate Rows  The default display of queries is all rows. 61 ....

Set Operations: UNION... INTERSECT and MINUS  UNION combines the results from several SELECT statements  The columns count and types should match SELECT FirstName AS Name FROM Employees UNION SELECT LastName AS Name FROM Employees Name A.  INTERSECT / EXCEPT perform logical intersection / difference between 62 . Scott Abbas Abercrombi e .

... . LastName. DepartmentID FROM Employees WHERE LastName = 'Sullivan' SELECT LastName. Salary FROM Employees WHERE Salary <= 20000 63 . DepartmentID FROM Employees WHERE DepartmentID = 1  More examples: LastNam Department e ID Tamburel lo 1 Erickson 1 Goldberg 1 .. Limiting the Rows Selected Restrict the rows returned by using the WHERE clause: SELECT LastName. SELECT FirstName.

Salary FROM Employees WHERE Salary BETWEEN 20000 AND 22000  Using IN / NOT IN to specify a set of SELECT FirstName. LastName. Other Comparison Conditions Using BETWEEN operator to specify a range: SELECT LastName. 16)  Using LIKE operator to specify a SELECT FirstName FROM Employees WHERE FirstName LIKE 'S%' pattern: 64 . ManagerID FROM values: Employees WHERE ManagerID IN (109. 3.

Comparing with NULL  Checking for NULL value: SELECT LastName. MANAGER_ID FROM EMPLOYEES WHERE MANAGER_ID = NULL SELECT LAST_NAME. ManagerId FROM Employees WHERE ManagerId IS NULL SELECT LastName. ManagerId FROM Employees WHERE ManagerId IS NOT NULL  Attention: COLUMN=NULL is always false! SELECT LAST_NAME. WHERE NULL = NULL This is always MANAGER_ID FROMfalse! EMPLOYEES This is always false! 65 .

LastName FROM Employees WHERE (ManagerID = 3 OR ManagerID = 4) AND (Salary >= 20000 OR ManagerID IS NULL) 66 . Logical Operators and Brackets Using NOT. LastName FROM Employees WHERE Salary >= 20000 AND LastName LIKE 'C%' SELECT LastName FROM Employees WHERE ManagerID IS NOT NULL OR LastName LIKE '%so_' SELECT LastName FROM Employees WHERE NOT (ManagerID = 3 OR ManagerID = 4) SELECT FirstName. OR and AND operators and brackets: SELECT FirstName.

Sorting with ORDER BY  Sort rows with the ORDER BY clause  ASC: ascending order. HireDate FROM Employees ORDER BY HireDate DESC LastNam e HireDate Gilbert 1998-0731 Brown 1999-0226 LastNam Tamburell e o HireDate 1999-12- Valdez 2005-0701 Tsoflias 2005-0701 12 67 . default  DESC: descending order SELECT LastName. HireDate FROM Employees ORDER BY HireDate SELECT LastName.

SQL Language Selecting Data From Multiple Tables .

 Data from Multiple Tables Sometimes you need data from more than one table: LastNa me Departmen tID Departmen Name tID Duffy 1 1 Abbas 3 Engineeri ng Galvin 2 2 Tool design LastNam e 3 Sales DepartmentNa me Duffy Engineering Galvin Tool design Abbas Sales 69 .

Name AS DepartmentName FROM Employees. Departments  The result: LastNam DepartmentNa e me Duffy Document Control Wang Document Control Sullivan Document Control Duffy Engineering 70 .Cartesian Product  This will produce Cartesian product: SELECT LastName.

Cartesian Product (2)  A Cartesian product is formed when:  A join condition is omitted  A join condition is invalid  All rows in the first table are joined to all rows in the second table  To avoid a Cartesian product. always include a valid join condition 71 .

right and full outer joins  Cross joins 72 .Types of Joins  Inner joins  Left.

DepartmentID = d. d.DepartmentID. e. the ON clause is used  Such JOIN is called also INNER JOIN SELECT e.DepartmentID.Name AS DepartmentName FROM Employees e INNER JOIN Departments d ON e.DepartmentID Employe eID LastNa me Depa rtme ntID Depa rtme ntID DepartmentN ame 1 Gilbert 7 7 Production 2 Brown 4 4 Marketing 1 1 Engineering 3 Tamburel 73 .EmployeeID. d. e.LastName. Inner Join with ON Clause To specify arbitrary conditions or specify columns to join.

e. e.EmployeeID. Departments d WHERE e.DepartmentID.LastName.Name AS DepartmentName FROM Employees e.DepartmentID = d.DepartmentID Depar Employee LastNam tID e mentI D Depar tDepartme mentI nt-Name D 1 Gilbert 7 7 Production 2 Brown 4 4 Marketing 3 Tamburell 1 o 1 Engineerin g 74 . d.Equijoins  Inner joins with join conditions pushed down to the WHERE clause SELECT e. d.DepartmentID.

INNER vs. OUTER Joins  Inner join  A join of two tables returning only rows matching the join condition  Left (or right) outer join  Returns the results of the inner join as well as unmatched rows from the left (or right) table  Full outer join  Returns the results of an inner join as well as the results of a left and right join 75 .

76 .INNER JOIN SELECT e.LastName EmpLastName.EmployeeID EmpLastName MgrID MgrLastName Erickson 3 Tamburello Goldberg 3 Tamburello Duffy 109 Sánchez Johnson 185 Hill Higa 185 Hill Ford 185 Hill Maxwell 21 Krebs .. .LastName MgrLastName FROM Employees e INNER JOIN Employees m ON e.EmployeeID MgrID. . m. m....ManagerID = m...

.ManagerID = m.EmployeeID EmpLastName MgrID MgrLastName Sánchez NULL NULL Benshoof 6 Bradley Miller 14 Maxwell Okelberry 16 Brown Hill 25 Mu Frum 184 Richins Culbertson 30 Barreto de Mattos . . 77 .....EmployeeID MgrID.LastName EmpLastName. m. m.LastName MgrLastName FROM Employees e LEFT OUTER JOIN Employees m ON e.LEFT OUTER JOIN SELECT e.. .

....EmployeeID EmpLastName MgrID MgrLastName Lertpiriyasuwa t 38 Liu NULL 39 Hines NULL 40 McKay Berglund 41 Wu Koenigsbauer 123 Hay NULL 124 Zabokritski NULL 125 Decker .RIGHT OUTER JOIN SELECT e..LastName EmpLastName.EmployeeID MgrID.. 78 . . m.ManagerID = m.LastName MgrLastName FROM Employees e RIGHT OUTER JOIN Employees m ON e. m..

LastName MgrLastName FROM employee e FULL OUTER JOIN employee m ON e.EmployeeID MgrID.ManagerID = m.FULL OUTER JOIN SELECT e.EmployeeID EmpLastName MgrID MgrLastName Sanchez NULL NULL … … … Cracium 3 Tamburello Gilbert 16 Brown … … … NULL 17 Hartwig NULL 1 Gilbert … … … 79 . m.LastName EmpLastName. m.

AddressID JOIN Towns t ON a. Roberto Tamburel Redmon 8000 Crane Court 80 . e. t.TownID FirstNam LastNam Towns e e AddressText Guy Gilbert Monroe 7726 Driftwood Drive Kevin Brown Everett 2294 West 39th St.LastName. a.Name as Towns.TownID = t.FirstName.Three-Way Joins  A three-way join is a join of three tables SELECT e.AddressID = a.AddressText FROM Employees e JOIN Addresses a ON e.

ManagerId = m.Self-Join  Self-join means to join a table to itself SELECT Always used with aliases e.FirstName + ' ' +table e.LastName + ' is managed by ' + m.LastName as Message FROM Employees e JOIN Employees m ON (e.EmployeeId) Message Ovidiu Cracium is managed by Tamburello Michael Sullivan is managed by Tamburello Sharon Salavaria is managed by Tamburello Dylan Miller is managed by Tamburello … 81 .

Name [Dept Name] FROM Employees CROSS JOIN Departments Last Name Dept Name Duffy Document Control Wang Document Control Duffy Engineering Wang Engineering … … 82 .Cross Join  The CROSS JOIN clause produces the cross-product of two tables  Same as a Cartesian product  Not often used SELECT LastName [Last Name].

DepartmentID = d.Name AS DepartmentName FROM Employees e INNER JOIN Departments d ON e. e.Name = 'Sales' Depart Employee LastNam ID e mentI D Depart Departme mentI nt-Name D 268 Jiang 3 3 Sales 273 Welcker 3 3 Sales 83 .DepartmentID. d.EmployeeID. d.DepartmentID.Additional Conditions  You can apply additional conditions in the WHERE clause: SELECT e. e.DepartmentID WHERE d.LastName.

Name IN ('Sales'. e.HireDate > '1/1/1999' AND d.LastName. 'Finance')) FirstName LastName DeptName Deborah Poe Finance Wendy Kahn Finance … … … 84 . Complex Join Conditions Joins can use any Boolean expression in the ON clause: SELECT e.DepartmentId AND e.Name as DeptName FROM Employees e INNER JOIN Departments d ON (e.FirstName. d.DepartmentId = d.

SQL Language Inserting Data in Tables .

25) INSERT INTO Projects(Name.Inserting Data  INSERT command  INSERT INTO <table> VALUES (<values>)  INSERT INTO <table>(<columns>) VALUES (<values>)  INSERT INTO <table> SELECT <values> INSERT INTO EmployeesProjects VALUES (229. StartDate) VALUES ('New project'. GETDATE() FROM Departments 86 . GETDATE()) INSERT INTO Projects(Name. StartDate) SELECT Name + ' Restructuring'.

SQL Language Updating Data in Tables .

DepartmentID WHERE d.Updating Joined Tables  We can update tables based on condition from joined tables UPDATE Employees SET JobTitle = 'Senior ' + JobTitle FROM Employees e JOIN Departments d ON e.DepartmentID = d.Name = 'Sales' 88 .

JobTitle = 'Senior ' + JobTitle WHERE DepartmentID = 3 89 .Updating Data  UPDATE command  UPDATE <table> SET <column=expression> WHERE <condition>  Note: Don't forget the WHERE clause! UPDATE Employees SET LastName = 'Brown' WHERE EmployeeID = 1 UPDATE Employees SET Salary = Salary * 1.10.

SQL Language Deleting Data From Tables .

Deleting Data  Deleting rows from a table  DELETE FROM <table> WHERE <condition> DELETE FROM Employees WHERE EmployeeID = 1 DELETE FROM Employees WHERE LastName LIKE 'S%'  Note: Don’t forget the WHERE clause!  Delete all rows from a table at once TABLE TABLE Users <table>  TRUNCATE TRUNCATE 91 .

Deleting from Joined Tables  We can delete records from tables based on condition from joined tables DELETE FROM Employees FROM Employees e JOIN Departments d ON e.DepartmentID WHERE d.DepartmentID = d.Name = 'Sales' 92 .

WTF? 93 .

SQL Language Nested SELECT Statements SQL .

LastName. LastName. Nested SELECT Statements SELECT statements can be nested in the where clause SELECT FirstName. Salary FROM Employees WHERE Salary = (SELECT MAX(Salary) FROM Employees) SELECT FirstName. 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 95 .

DepartmentID.DepartmentID) ORDER BY DepartmentID 96 . employee that gets it Salary FROM Employees e WHERE Salary = (SELECT MAX(Salary) FROM Employees WHERE DepartmentID = e. LastName.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 SELECT FirstName.

ManagerID AND m. LastName. Using the EXISTS Operator Using the EXISTS operator in SELECT statements  Find all employees with managers from the first department SELECT FirstName.DepartmentID = 1) 97 .EmployeeID = e. EmployeeID. ManagerID FROM Employees e WHERE EXISTS (SELECT EmployeeID FROM Employees m WHERE m.

SQL Language Aggregating Data with Group Functions .

Group Functions  Group functions operate over sets of rows to give one single result (per group) Employee Salary ID 1 12500.0 0 2 13500.0 0 4 29800.0 MAX(Salar y) 125500.0 0 5 25000.0 0 3 43300.00 99 .

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  100 .

SUM(Salary) [Salary Sum] FROM Employees WHERE JobTitle = 'Design Engineer' Average Salary Max Salary Min Salary Salary Sum 32700. MAX(Salary) [Max Salary].00 32700.00 101 . AVG() and SUM() Functions You can use AVG() and SUM() only for numeric data types SELECT AVG(Salary) [Average Salary].00 98100. MIN(Salary) [Min Salary].00 32700.

datetime.. MAX(HireDate) MaxHD FROM Employees  MinHD MaxHD 1996-07-31 2003-06-03 Displaying the first and last employee's name in alphabetical order: SELECT MIN(LastName).. varchar. MIN() and MAX() Functions You can use MIN() and MAX() for almost any data type (int. MAX(LastName) FROM Employees 102 .) SELECT MIN(HireDate) MinHD. .

The COUNT(…) Function  COUNT(*) returns the number of rows in the result record set SELECT COUNT(*) Cnt FROM Employees  COUNT(expr) returns WHERE DepartmentID = 3 Cnt 18 the number of rows with non-null values for the expr SELECT COUNT(ManagerID) MgrCount. COUNT(*) AllCount FROM Employees WHERE DepartmentID = 16 MgrCou nt AllCou nt 1 2 103 .

the result would be 106 104 . 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. Group Functions and NULLs Group functions ignore NULL values in the target column SELECT AVG(ManagerID) Avg.

DepartmentID WHERE e.DepartmentID = d.LastName.Name FROM Employees e JOIN Departments d ON e. d. e.FirstName.DepartmentID) FirstNam LastNam e e HireDate Name Guy Gilbert 1998-07-31 00:00:00 Production Kevin Brown 1999-02-26 00:00:00 Marketing 105 .HireDate = (SELECT MIN(HireDate) FROM Employees WHERE DepartmentID = d.Group Functions in Nested Queries  Find the earliest hired employee for each department SELECT e.HireDate. e.

SQL Language Group Functions and the GROUP BY Statement .

.Employees Creating Groups of Data Departmen Salar tID y 12 12 1030 0 1680 0 12 1680 0 12 1030 0 12 1780 0 2 2880 0 2 2500 0 72000 108600 185600 Depart SUM (Salar mentI y) D 12 72000 2 10860 0 16 18560 0 ... 107 ...

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 108 .

SUM(Salary) as SalariesCost FROM Employees GROUP BY DepartmentID  DepartmentID SalariesCos t 12 72000 2 108600 The GROUP BY185600 column is not 16 .. The GROUP BY Statement (2) Example of grouping data: SELECT DepartmentID... . necessary needed to be in the SELECT list 109 ..

.... 110 .Grouping by Several Columns Depar tJobTitle mentI D Sala ry 11 Network Manager 11 Network 3250 Administra 0 tor 11 11 3970 0 Network 3250 Administra 0 tor Database 3850 Administra 0 tor 11 Database 3850 Administra 0 tor 10 Accountan t 2640 0 39700 65000 77000 52800 43300 Depa rtme ntID JobTitle Sala ry 11 Network Manager 3970 0 11 Network Administr ator 6500 0 11 Database Administr ator 7700 0 10 Accountan 5280 t 0 10 Finance Manager 4330 0 .. .. .

SUM(Salary) as Salaries. JobTitle Departmen JobTitle tID Salarie s Coun t 2 Senior Tool Designer 58600 2 2 Tool Designer 50000 2 7 Production Supervisor 525000 21 7 Production 1926000 157 111 . COUNT(*) as Count FROM Employees GROUP BY DepartmentID.Grouping by Several Columns – Example  Example of grouping data by several columns: SELECT DepartmentID. JobTitle.

AVG(Salary) FROM Employees WHERE AVG(Salary) > 30 GROUP BY DepartmentID  Can not use WHERE for group functions 112 .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.

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. 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. SUM(Salary) AS Cost. but has no sense 113 . MIN(HireDate) as StartDate FROM Employees GROUP BY DepartmentID. JobTitle.

Using GROUP BY with HAVING Clause  HAVING works like WHERE but is used for the grouping functions SELECT DepartmentID. AVG(Salary) AverageSalary FROM Employees GROUP BY DepartmentID HAVING COUNT(EmployeeID) BETWEEN 3 AND 5 DepartmentI D Count AverageSalary 2 4 27150 12 5 14400 … … … 114 . COUNT(EmployeeID) as Count.

Name HAVING COUNT(*) > 5 ORDER BY EmpCount DESC EmpCou DeptName nt 95 Production 8 Finance 8 Information 115 .HireDate BETWEEN '1999-2-1' AND '2002-1231' GROUP BY d.DepartmentID = d.Name AS DeptName FROM Employees e JOIN Departments d ON e. d.Using Grouping Functions and Joins  Grouping function can Table be applied on columns from joined tables SELECT COUNT(*) AS EmpCount.DepartmentID WHERE e.

SQL Language SQL Server Functions .

Standard Functions in Microsoft SQL Server  Single-row functions      String functions Mathematical functions Date functions Conversion functions SQL Multiple-row functions  Aggregate functions 117 .

000 Half-Finger Gloves 2003-06-01 00:00:00. 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.. 118 . .000 ...000 HL Mountain Frame 2003-06-01 00:00:00.<default_value>) – converts NULL values to given default value SELECT Name AS [Projects Name].000 Full-Finger Gloves 2003-06-01 00:00:00..COALESCE() Function  COALESCE(<value>.

. LEN(LastName) AS LastNameLen. .. UPPER  Manipulating characters – SUBSTRING. 3) = 'son' LastName LastNameLen UpperLastNam e Erickson 8 ERICKSON Johnson 7 JOHNSON Munson 6 MUNSON . . RIGHT. LTRIM.  UPPER(LastName) AS UpperLastName FROM Employees WHERE RIGHT(LastName... REPLACE SELECT LastName. 119 .String Functions Changing the casing – LOWER. LEFT.. LEN..

SQRT. 112)  2005-12-31 00:00:00.86.112 is the ISO formatting style YYYYMMDD 120 .Other Functions  Mathematical Functions – ROUND. …  Conversion Functions – CONVERT. FLOOR.00 Date Functions – GETDATE. ABS. …  SELECT FLOOR(3. '20051231'.000 -.14)  3 SELECT ROUND(5. CAST SELECT CONVERT(DATETIME. DAY. POWER. 0)  6. DATEADD. MONTH. YEAR.

.. 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 . .Combining Functions  We can combine functions to achieve more complex behavior SELECT Name AS [Projects Name]. COALESCE(CONVERT(nvarchar(50). 121 ..

SQL Language
Data Definition Language (DDL)

Data Definition
Language

DDL commands for defining /
editing objects
 CREATE
 ALTER
 DROP

Data Control Language (DCL) for
managing access permissions
 GRANT
 REVOKE
 DENY
123

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
124

Creating Objects – More Examples CREATE TABLE Countries ( CountryID int IDENTITY. Name nvarchar(100) NOT NULL. Name nvarchar(100) NOT NULL. CountryID int NOT NULL. CONSTRAINT PK_Countries PRIMARY KEY(CountryID) ) GO CREATE TABLE Cities ( CityID int IDENTITY. CONSTRAINT PK_Cities PRIMARY KEY(CityID) ) 125 .

Add a foreign key constraint Cities --> Country ALTER TABLE Cities ADD CONSTRAINT FK_Cities_Countries FOREIGN KEY (CountryID) REFERENCES Countries(CountryID) -.Modifying Database Objects  ALTER command  ALTER TABLE <name> <command>  ALTER <object> <command> -.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 126 .

Deleting Database Objects  DROP command     DROP DROP DROP DROP TABLE <name> TRIGGER <name> INDEX <name> <object> DROP TABLE Persons ALTER TABLE Cities DROP CONSTRAINT FK_Cities_Countries 127 .

 Managing Access Permissions GRANT command GRANT <persmission> ON <object> TO <role>  Example:  GRANT SELECT ON Persons TO public REVOKE command <persmission>  REVOKE Example: ON <object> FROM <role> REVOKE SELECT ON Employees FROM public 128 .

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 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 130 .

Name nvarchar(100) NOT NULL. CONSTRAINT PK_Users PRIMARY KEY(UserID). UserName nvarchar(100) NOT NULL. CONSTRAINT PK_Groups PRIMARY KEY(GroupID) ) CREATE TABLE Users ( UserID int IDENTITY.Creating Tables in SQL Server – Examples CREATE TABLE Groups ( GroupID int IDENTITY. CONSTRAINT FK_Users_Groups FOREIGN KEY(GroupID) REFERENCES Groups(GroupID) ) 131 . GroupID int NOT NULL.

Transactions Begin / Commit / Rollback Transactions in SQL Server .

 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 / 133 .

DELETE FROM Projects.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. ROLLBACK TRAN 134 .

 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 SET IMPLICIT_TRANSACTIONS ON setting is switched off 135 .

Homework 1. Define a primary key column with a primary key constraint. Users should have username. full name and last login time. Write a SQL statement to create a table Users. password. Define unique constraint to avoid repeating usernames. Define a check 136 . Choose appropriate data types for the table fields. Define the primary key column as identity to facilitate inserting records.

Test if the view works correctly. 3.Homework (2) 2. Write a SQL statement to create a table Groups. Write a SQL statement to add a column GroupID to the table Users. Write a SQL statement to add a foreign key constraint between 137 . Write a SQL statement to create a view that displays the users from the Users table that have been in the system today. Groups should have unique name (use unique constraint). Fill some data in this new column and as well in the Groups table. Define primary key and identity column. 4.

8. Write SQL statements to insert several records in the Users and Groups tables.Homework (3) 5.2011. 6. Write SQL statements to update some of the records in the Users and Groups tables. 9. Write SQL statements to delete some of the records from the Users and Groups tables. Write a SQL statement that changes the password to NULL for all users that have not been in the system since 07. Write a SQL statement that deletes all 138 . 7.10.

Create the following database diagram in SQL Server: Fill some sample data in the tables with SQL Server Management Studio.Homework (4) 10. .

безплат на книга C#. C#. Android.сай т за програмиране Николай Кост ов .NET курс .teler . Photoshop free C# book. форум уеб ди зайн ASP. ASP. програми ране. HTML.NET MVC алго академи я – съст езат елно програмиране. . JavaScript.Database Modeling and Introduction to SQL ? ? ? ? ? ? ? ? ? ? ? ? ? ? BG Coder . C#. W P7.уеб програмиране. книга C# безплат ен курс "Качест вен програмен код" безплат ен курс "Разработ ка на софт уер в cloud среда" ? ? Questions? ? http://academy.опт и ми зация за т ърсачки курсове и уроци по програми ране. бази данни.NET MVC курс – HTML. безплат но ? ? курсове и уроци по програми ране.блог за програми ране C# курс.NET. SQL. книги – безпл ат но от Наков уроци по уеб дизайн. PhoneGap Дончо Минков . ASP.online judge форум програми ране.NET. уеб дизайн – безплат но курсове и уроци по програми ране – Телери к академия уроци по програми ране и уеб ди зай н за учени ци програмиране за деца – безплат ни курсове и уроци безпл ат ен SEO курс . книга Java.NET ASP. съст езания курс мобилни приложения с iPhone.онл айн съст езат елна сист ема . CSS. .

com .NET MVC Course   Telerik Software Academy   academy.telerik.telerik.com facebook.Free Trainings @ Telerik Academy  Web Applications with ASP.com Telerik Academy @ Facebook   mvccourse.telerik.com/TelerikAcademy Telerik Software Academy Forums  forums.academy.