33

Click here to load reader

Databases, SQL and MS SQL Server

Embed Size (px)

Citation preview

Page 1: Databases, SQL and MS SQL Server

Creating E/R Diagrams with SQL Server Creating E/R Diagrams with SQL Server Management Studio, Writing SQL Management Studio, Writing SQL

QueriesQueries

Doncho MinkovDoncho Minkov

Telerik School AcademyTelerik School Academyschoolacademy.telerik.com

Technical TrainerTechnical Trainerhttp://www.minkov.it

Page 2: Databases, SQL and MS SQL Server

Table of ContentsTable of Contents

1.1. Data Modeling Data Modeling – – PrinciplesPrinciples

2.2. Data Types inData Types in SQL ServerSQL Server

3.3. Creating Databases inCreating Databases in SQL ServerSQL Server

4.4. Creating TablesCreating Tables

5.5. Defining aDefining a Primary Key and Primary Key and Identity ColumnsIdentity Columns

6.6. Creating Relationships between Creating Relationships between the Tablesthe Tables

One-to-many, Many-to-many, One-One-to-many, Many-to-many, One-to-oneto-one 2

Page 3: Databases, SQL and MS SQL Server

Relational DataRelational Data ModelingModeling

FundamentalFundamental ConceptsConcepts

Page 4: Databases, SQL and MS SQL Server

Steps inSteps in DatabaseDatabase DesignDesign

Steps in the database design process:Steps in the database design process: Identification of the entitiesIdentification of the entities Identification of the columns in theIdentification of the columns in the

tablestables Defining aDefining a primary key for eachprimary key for each entity entity

tabletable Identification and modeling of Identification and modeling of

relationshipsrelationships Multiplicity of relationshipsMultiplicity of relationships

Defining other constraintsDefining other constraints Filling test data in the tablesFilling test data in the tables

4

Page 5: Databases, SQL and MS SQL Server

Identification ofIdentification of EntitiesEntities

Entity tables represent objects Entity tables represent objects from the real worldfrom the real world Most often they are nouns in the Most often they are nouns in the

specificationspecification For exampleFor example::

EntitiesEntities: : StudentStudent, , CourseCourse, , TownTown5

We need to develop a system that stores We need to develop a system that stores information about information about studentsstudents, which are trained in , which are trained in various various coursescourses. The courses are held in . The courses are held in different different townstowns. When registering a new student . When registering a new student the following information is entered: name, the following information is entered: name, faculty number, photo and date.faculty number, photo and date.

Page 6: Databases, SQL and MS SQL Server

Identification of Identification of ColumnsColumns

Columns in the tables are Columns in the tables are characteristics of the entitiescharacteristics of the entities They have name and typeThey have name and type

For example students haveFor example students have:: NameName ((texttext))

FacultyFaculty numbernumber ((numbernumber))

PhotoPhoto ((binary blockbinary block))

DateDate ofof enlistmentenlistment ((datedate))

6

Page 7: Databases, SQL and MS SQL Server

Identification of the Identification of the ColumnsColumns

Columns are clarifications for the Columns are clarifications for the entities in the text of the specificationentities in the text of the specification, , for examplefor example::

Students have the following Students have the following characteristicscharacteristics:: NameName, , faculty numberfaculty number, , photophoto, , date of date of enlistment enlistment and a list of and a list of courses courses they they visitvisit

7

We need to develop a system that stores We need to develop a system that stores information about information about studentsstudents, which are trained in , which are trained in various various coursescourses. The courses are held in . The courses are held in different different townstowns. When registering a new student . When registering a new student the following information is entered: the following information is entered: namename, , facultyfaculty numbernumber, , photophoto and and datedate..

Page 8: Databases, SQL and MS SQL Server

How to Choose a How to Choose a Primary KeyPrimary Key??

Always define an additional column for Always define an additional column for the primary keythe primary key Don't use an existing columnDon't use an existing column ( (for examplefor example

SSNSSN)) Must be an integer numberMust be an integer number Must be declared as aMust be declared as a primary keyprimary key UseUse identityidentity to implement auto-incrementto implement auto-increment Put the primary key as a first columnPut the primary key as a first column

ExceptionsExceptions Entities that have well known ID, e.g. Entities that have well known ID, e.g.

countries (BG, DE, US) and currencies countries (BG, DE, US) and currencies (USD, EUR, BGN)(USD, EUR, BGN)

8

Page 9: Databases, SQL and MS SQL Server

Identification of Identification of RelationshipsRelationships

Relationships are dependencies Relationships are dependencies between the entitiesbetween the entities::

""StudentsStudents are trained in are trained in coursescourses"" – – many-to-many relationshipmany-to-many relationship

""CoursesCourses are held in are held in townstowns" – " – many-to-many-to-one (or many-to-many) relationshipone (or many-to-many) relationship

9

We need to develop a system that stores We need to develop a system that stores information about information about studentsstudents, which , which are trained in are trained in various various coursescourses. The . The coursescourses are held in are held in different different townstowns. When registering a new student . When registering a new student the following information is entered: name, the following information is entered: name, faculty number, photo and date.faculty number, photo and date.

Page 10: Databases, SQL and MS SQL Server

Data Types inData Types in SQL SQL Server 200Server 20088

Page 11: Databases, SQL and MS SQL Server

Data Types inData Types in SQL SQL ServerServer

NumericNumeric bitbit (1-bit), (1-bit), integer integer (32-bit), (32-bit), bigintbigint (64-bit) (64-bit) floatfloat, , realreal, , numericnumeric(scale,(scale, precision)precision) moneymoney – – for money (precise) operationsfor money (precise) operations

StringsStrings char(size)char(size) – – fixed size stringfixed size string varchar(size)varchar(size) – – variable size stringvariable size string nvarchar(size)nvarchar(size) – Unicode – Unicode variable size variable size

stringstring texttext / / ntextntext – text data block (unlimited – text data block (unlimited

size)size)11

Page 12: Databases, SQL and MS SQL Server

Data Types inData Types in SQL SQL Server (2)Server (2)

Binary dataBinary data varbinary(size)varbinary(size) – – a sequence of bitsa sequence of bits imageimage – a binary block up to – a binary block up to 1 GB1 GB

Date and timeDate and time datetime datetime – – date and time starting date and time starting

fromfrom 1.1.171.1.175533 toto 31.12. 9999 31.12. 9999, a , a precision ofprecision of 1/300 1/300 secsec..

smalldatetimesmalldatetime – date and time (1- – date and time (1-minute precision)minute precision)

12

Page 13: Databases, SQL and MS SQL Server

Data Types inData Types in SQL SQL Server (3)Server (3)

Other typesOther types timestamptimestamp – automatically generated – automatically generated

number whenever a change is made number whenever a change is made to the data rowto the data row

uniqueidentifieruniqueidentifier – GUID identifier – GUID identifier xmlxml – data in XML format – data in XML format

13

Page 14: Databases, SQL and MS SQL Server

Data Types inData Types in SQL SQL Server (4)Server (4)

NullableNullable and and NOTNOT NULLNULL typestypes All types inAll types in SQL Server may or may SQL Server may or may

not allow not allow NULLNULL values values PrimaryPrimary keykey columnscolumns

Define the primary keyDefine the primary key IdentityIdentity columns columns

Automatically increased values when Automatically increased values when a new row is inserted a new row is inserted ((auto-auto-increment values)increment values)

Used in combination withUsed in combination with primaryprimary keykey14

Page 15: Databases, SQL and MS SQL Server

Database Modeling Database Modeling withwith SQL Server SQL Server

Management StudioManagement StudioCreating DatabaseCreating Database

Page 16: Databases, SQL and MS SQL Server

Connecting toConnecting to SQL SQL ServerServer

When startingWhen starting SSMS a window SSMS a window pops uppops up

Usually it is enough to just click Usually it is enough to just click the "Connect" button without the "Connect" button without changing anythingchanging anything

16

Page 17: Databases, SQL and MS SQL Server

Working withWorking with Object Object ExplorerExplorer

Object Explorer Object Explorer is the main toolis the main tool to to use when working with the databaseuse when working with the database and its objectsand its objects

Enables usEnables us:: To create a new databaseTo create a new database

To create objects in the databaseTo create objects in the database ((tablestables, , stored proceduresstored procedures, , relationships and othersrelationships and others))

To change the properties of objectsTo change the properties of objects

To enter records into the tablesTo enter records into the tables17

Page 18: Databases, SQL and MS SQL Server

Creating a New Creating a New DatabaseDatabase

InIn Object Explorer we go to the Object Explorer we go to the ""DatabasesDatabases"" and chooseand choose " "NewNew DatabaseDatabase……"" from the context menufrom the context menu

18

Page 19: Databases, SQL and MS SQL Server

Creating a New Creating a New Database (2)Database (2)

In theIn the ""NewNew DatabaseDatabase" window enter the " window enter the name of the new database and click [name of the new database and click [OKOK]]

19

Page 20: Databases, SQL and MS SQL Server

Database Modeling Database Modeling withwith SQL Server SQL Server

Management StudioManagement StudioCreating E/R DiagramsCreating E/R Diagrams

Page 21: Databases, SQL and MS SQL Server

Creating an E/R Creating an E/R diagramdiagram

In theIn the " "DatabaseDatabase DiagramsDiagrams"" menu menu choose thechoose the " "NewNew DatabaseDatabase DiagramDiagram""

We can choose from the existing We can choose from the existing tablestables, , which we want to add to the which we want to add to the diagramdiagram

21

Page 22: Databases, SQL and MS SQL Server

Database Modeling Database Modeling withwith SQL Server SQL Server

Management StudioManagement StudioCreating TablesCreating Tables

Page 23: Databases, SQL and MS SQL Server

Creating TablesCreating Tables If the database doesn't show If the database doesn't show

immediately inimmediately in Object Explorer Object Explorer performperform "Refresh" [F"Refresh" [F55]]

Creating new table:Creating new table:

23

Page 24: Databases, SQL and MS SQL Server

Creating Tables (2)Creating Tables (2) Enter table name and define the Enter table name and define the

table columns (name and type):table columns (name and type):

24

Enter the Enter the name of name of

the the column column

herehere

Choose the Choose the data type of data type of the column the column

herehere

Choose Choose whether whether

NULLs are NULLs are allowedallowed

Page 25: Databases, SQL and MS SQL Server

Creating Tables (3)Creating Tables (3) Defining a primary keyDefining a primary key

25

Right click on the Right click on the column start and column start and

select "Set select "Set Primary Key"Primary Key"

Page 26: Databases, SQL and MS SQL Server

Creating Tables (4)Creating Tables (4) Defining anDefining an identity columnsidentity columns

IdentityIdentity means that the values in a means that the values in a certain columncertain column are auto generatedare auto generated (for (for intint columnscolumns))

These values cannot be assigned These values cannot be assigned manuallymanually

Identity Seed Identity Seed – the starting number – the starting number from which the values in the column from which the values in the column begin to increasebegin to increase..

IdentityIdentity Increment Increment – by how much – by how much each consecutive value is increasedeach consecutive value is increased

26

Page 27: Databases, SQL and MS SQL Server

Creating Tables (5)Creating Tables (5) Setting anSetting an

identityidentity through thethrough the ""ColumnColumn PropertiesProperties" " windowwindow

27

Page 28: Databases, SQL and MS SQL Server

Creating Tables (6)Creating Tables (6) It is a good practice It is a good practice

toto set the name of set the name of the table at the time the table at the time it is createdit is created Use theUse the ""PropertiesProperties" "

windowwindow If it's not visible useIf it's not visible use

""ViewView" " ""Properties Properties WindowWindow" or press " or press [[F4F4]]

28

TablTablenaenameme

Page 29: Databases, SQL and MS SQL Server

Creating Tables (7)Creating Tables (7)

When closing the window for the When closing the window for the tabletable, , SSMS asks whether to save SSMS asks whether to save the tablethe table You can do it manually by choosingYou can do it manually by choosing

““Save TableSave Table” from the” from the ““FileFile” menu ” menu or by pressingor by pressing Ctrl Ctrl ++ S S

29

Page 30: Databases, SQL and MS SQL Server

Database Modeling Database Modeling withwith SQL Server SQL Server

Management StudioManagement StudioCreating Relationships between TablesCreating Relationships between Tables

Page 31: Databases, SQL and MS SQL Server

Creating RelationshipsCreating Relationships To create one-to-manyTo create one-to-many relationship relationship

drag the foreign key column onto drag the foreign key column onto the other tablethe other table Drag from the child table to theDrag from the child table to the

parent tableparent table

31

Page 32: Databases, SQL and MS SQL Server

Self-RelationshipsSelf-Relationships Self-relationship can be created by Self-relationship can be created by

dragging a foreign key onto the dragging a foreign key onto the same tablesame table

32

Page 33: Databases, SQL and MS SQL Server

Database Modeling and Database Modeling and Introduction to SQL Introduction to SQL

Questions?Questions?