SlideShare a Scribd company logo
i
ADDIS ABABA UNIVERSITY
COLLEGE OF NATURAL & COMPUTITIONAL SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Laboratory Manual for the Fundamentals of Database Systems
(COSC 3051)
Using Microsoft SQL Server 2012 DBMS
Prepared By: Surafiel Habib
March 2017
ii
Table of Contents
Acronyms ...........................................................................................................................................vi
Objectives of the Manual ................................................................................................................. vii
Required Software........................................................................................................................... viii
Introduction to Microsoft SQL Server ................................................................................................1
What is SQL Server?.......................................................................................................................1
Usage of SQL Server.......................................................................................................................1
SQL Server Components.................................................................................................................3
Instance of SQL Server ...................................................................................................................3
Advantages of Instances ............................................................................................................. 3
Installation Guide of Microsoft SQL Servers .................................................................................4
Installation Steps......................................................................................................................... 5
Error messages with their possible solutions when you try to install SQL Server 2012.......... 15
The SQL Server Setup Log Files ......................................................................................................20
Summary Text ...............................................................................................................................20
Summary_engine-base_YYYYMMDD_HHMMss.txt ................................................................21
Summary_engine-base_YYYYMMDD_HHMMss_ComponentUpdate.txt................................21
Summary_engine-base_<VersionNumber>MMDD_HHMMss_GlobalRules.txt .......................21
Detail.txt........................................................................................................................................21
BootstrapLogDetail.txt. .............................................................................................................21
Detail_ComponentUpdate.txt........................................................................................................22
Detail_GlobalRules.txt..................................................................................................................22
MSI log files..................................................................................................................................22
ConfigurationFile.ini.....................................................................................................................22
BootstrapLog.SystemConfigurationCheck_Report.htm ...........................................................22
MS SQL Server - Architecture..........................................................................................................23
General Architecture .....................................................................................................................23
Memory Architecture ....................................................................................................................24
Data File Architecture...................................................................................................................25
File Groups................................................................................................................................ 25
Files........................................................................................................................................... 26
iii
Extents....................................................................................................................................... 26
Pages ......................................................................................................................................... 26
Log File Architecture ....................................................................................................................27
Checkpoints in SQL Server...............................................................................................................28
SQL Server Management Studio (SSMS).........................................................................................29
MS SQL Server: Login Database......................................................................................................30
The SQL Language ...........................................................................................................................34
Data Manipulation Language (DML) Vs Data Definition Language (DDL)...............................35
LAB1: MS SQLServer:Database creation using Graphical User Interface of SQL Server
Management Studio...............................................................................................................37
System Databases..........................................................................................................................37
1.1 How to Create Database in Microsoft SQL Server 2012 using SSMS...................................38
1.2 Creating a Table ......................................................................................................................39
1.3 Editing Table Rows.................................................................................................................41
LAB 2: Starting writing SQL Statements using SQL Server Management Studio Command line
Query Editor..........................................................................................................................42
Data Types of SQL Server ............................................................................................................42
2.1 Create Database Statement......................................................................................................45
2.2 Create Table Statement ...........................................................................................................49
SQL Alter Table Syntax............................................................................................................ 51
Changing the Data type of a column in a Relational Database................................................. 51
LAB 3: Implementing Constraints....................................................................................................52
3.1 Primary Key Constraints .........................................................................................................52
3.1.1 Adding a primary key while creating a Table.................................................................. 52
3.1.2 Adding a primary key after a Table is created................................................................. 52
Dropping a primary key constraint ........................................................................................... 53
3.2 Foreign Key Constraints..........................................................................................................53
3.2.1 SQL FOREIGN KEY Constraint on ALTER TABLE ........................................................54
Lab 4: Default Constraints ................................................................................................................55
4.1 SQL DEFAULT Constraint on CREATE TABLE.................................................................55
4.2 SQL DEFAULT Constraint on ALTER TABLE ...................................................................55
4.3 DROP a DEFAULT Constraint ..............................................................................................56
iv
Lab 5: SQL CHECK Constraint........................................................................................................57
5.1 SQL CHECK Constraint on CREATE TABLE .....................................................................57
5.2 DROPING a CHECK Constraint ............................................................................................58
LAB 6: SQL Create Index Statement................................................................................................59
6.1 Create an Index........................................................................................................................59
LAB 7: SQL Drop statements of COLUMN, INDEX, TABLE and DATABASE..........................61
7.1 Dropping an existing column..................................................................................................61
7.2 The DROP INDEX Statement.................................................................................................61
7.3 The DROP TABLE Statement ................................................................................................62
7.4 The TRUNCATE TABLE Statement .....................................................................................62
LAB 8: Data Manipulation Language (DML) .................................................................................63
8.1 Inserting Records (INSERT SQL Command).........................................................................63
8.2 Updating Records (UPDATE SQL Command)......................................................................64
8.3 Deleting Records (DELETE Command) ................................................................................64
LAB 9: Selecting Data from the Database Tables ............................................................................65
Attaching AdventureWorks Sample Database in to the SQL Server 2012R2 .............................66
Syntax of selecting data from SQL server 2012 Databases: ........................................................71
Order By clause.............................................................................................................................73
LAB 10: IN, NOTIN, LIKE and ISNULL Keywords.......................................................................74
10.1 The use of IN keyword..........................................................................................................74
10.2 The use of NOT IN keyword ................................................................................................74
10.3 The use of LIKE keyword.....................................................................................................75
10.4 IS NULL Keyword................................................................................................................75
LAB 11: Aggregate functions ...........................................................................................................77
11.1 Count function.......................................................................................................................77
LAB 11.2 MAX and MIN functions............................................................................................77
11.3 Average function ...................................................................................................................77
LAB 12: Group by clause..................................................................................................................78
12.1 Having clause ........................................................................................................................78
12.2 Combining conditions and Boolean Operators.....................................................................80
12.3 The use of DISTINCT Keyword...........................................................................................80
v
LAB 13: Tables Join .........................................................................................................................81
13.1 Joining Two Tables...............................................................................................................81
13.2 INNER JOIN .........................................................................................................................81
13.3 OUTER JOIN........................................................................................................................81
13.4 Sub Query..............................................................................................................................82
LAB 14: View...................................................................................................................................83
14.1 Creating Views......................................................................................................................83
14. 2 Updating a View ..................................................................................................................85
14.3 Inserting Rows in a View......................................................................................................85
14. 4 Deleting Rows in a View .....................................................................................................86
14. 5 Dropping Views: ..................................................................................................................86
References:........................................................................................................................................87
vi
Acronyms
BIDS Business Intelligence Development Studio
CRM Customer Relationship Management
DBMS Database Management System
DDL Data Definition Language
DML Data Manipulation Language
ETL Extract, Transform, Load
GAM Global Allocation Map
IAX Index Allocation Map
IBM International Business Machines
IP Internet Protocol
MS Microsoft
MSI Microsoft Software Installer
MSP Microsoft Solution Provider
ODBMS Object Database Management System
OS Operating System
PFS Page Free Space
PID Process Identification Number
R2 Release Two
RDBMS Relational Database Management System
RDP Remote Desktop Protocol
RTM Release-to-Manufacturing
SP Service Pack
SQL Standard Query Language
SSAS SQL Server Analysis Services
SSCM SQL Server Configuration Manager
SSIS SQL Server Integration Services
SSMS SQL Server Management Studio
SSRS SQL Server Reporting Services
TCP/IP Transmission Control Protocol/Internet Protocol
VIA Virtual Interface Adapter
vii
Objectives of the Manual
This laboratory Manual is prepared to deliver examples and exercises for the fundamentals of
Database systems (COSC 3051) course within the Microsoft SQL server 2012 Relational Database
Management System tool. The main objective is to learn the basic development of a relational
database application and to illustrate the concepts of SQL using simple examples. This laboratory
manual has been divided up into fourteen (14) sessions. Each one contains of examples, tasks and
exercises about a particular concept in SQL and how it is implemented in MS SQL Server 2012.
After completion of this fourteen (14) weeks laboratory guide the students will be able to:
 Implement a Data Definition Language (DDL) to create a Relational Databases, Tables and
Indexes.
 Implement a Data Manipulation Language (DML) to Insert, Update, Select and Delete data’s
of the Database tables.
 Create queries using basic and advanced SELECT statements.
 Perform Join operations on Relational Database Tables.
 Implement Aggregate functions in SQL.
 Write sub queries.
 Create Views of the Database.
viii
Required Software
The Microsoft SQL Server 2012 DBMS must be installed in the laboratory room Personal
Computers.
1
Introduction to Microsoft SQL Server
Microsoft SQL Server is a Relational Database Management System (RDBMS) developed by
Microsoft Software Company. It is built for the basic function of storing and retrieving data as
required by other applications and can be run either on the same computer or on another across a
network.
SQL Server is commonly used as the backend system for websites and corporate CRMs and can
support thousands of concurrent users.
SQL Server comes with a number of tools to help the users on Database Administration and
programming tasks.
What is SQL Server?
 It is application software, developed by Microsoft Company, which is implemented from
the specification of Relational Database Management System (RDBMS).
 It is also an Object Relational Database Management System (ORDBMS).
 It is platform dependent.
 It is both Graphical User Interface (GUI) and command based software.
 It supports SQL (SE-QUE-EL) language which is an IBM product, non-procedural,
common Database and case insensitive language.
Usage of SQL Server
 To create Databases.
 To maintain Databases.
 To analyze the data through SQL Server Analysis Services (SSAS).
 To generate reports through SQL Server Reporting Services (SSRS).
 To carry out ETL operations through SQL Server Integration Services (SSIS).
2
Table 1: Versions of Microsoft SQL Server
Version Name RTM (no SP) SP1 SP2 SP3 SP4
SQL Server 2017
codename vNext
14.0.1000.169
*Latest Version
(New)
SQL Server 2016 13.0.1601.5 13.0.4001.0
or
13.1.4001.0
SQL Server 2014 12.0.2000.8 12.0.4100.1
or
12.1.4100.1
12.0.5000.0
or
12.2.5000.0
SQL Server 2012
codename Denali
11.0.2100.60 11.0.3000.0
or 11.1.3000.0
11.0.5058.0
or
11.2.5058.0
11.0.6020.0
or
11.3.6020.0
11.0.7001.0
or
11.4.7001.0
SQL Server
2008 R2
codename
Kilimanjaro
10.50.1600.1 10.50.2500.0
or
10.51.2500.0
10.50.4000.0
or
10.52.4000.0
10.50.6000.34
or
10.53.6000.34
SQL Server 2008
codename Katmai
10.0.1600.22 10.0.2531.0
or
10.1.2531.0
10.0.4000.0
or
10.2.4000.0
10.0.5500.0
or
10.3.5500.0
10.0.6000.29
or
10.4.6000.29
SQL Server 2005
codename Yukon
9.0.1399.06 9.0.2047 9.0.3042 9.0.4035 9.0.5000
SQL Server 2000
codename Shiloh
8.0.194 8.0.384 8.0.532 8.0.760 8.0.2039
SQL Server 7.0
codename Sphinx
7.0.623 7.0.699 7.0.842 7.0.961 7.0.1063
3
SQL Server Components
SQL Server works in client-server architecture; hence it supports two types of components,
Workstation and Server.
 Workstation components are installed in every device/SQL Server operator’s machine.
These are just interfaces to interact with Server components. Example: SSMS, SSCM,
Profiler, BIDS, etc.
 Server components are installed in centralized server. These are services. Example: SQL
Server, SQL Server Agent, SSIS, SSAS, SSRS, SQL browser, SQL Server full text search
etc.
Instance of SQL Server
 An instance is an installation of SQL Server.
 An instance is an exact copy of the same software.
 If we install 'n' times, then 'n' instances will be created.
 There are two types of instances in SQL Server
1. Default
2. Named
 In SQL Server Express, a named instance is always used by default, It’s possible to specify
an instance name in the process of SQL Server Express installation, or the default named
instance of SQL Express is can be used. If the default instance is used it has to be
referenced as Computer_NameSQLExpress.
 Only one default instance will be supported in one Server.
 Multiple named instances will be supported in one Server.
 Default instance will take the server name as Instance name.
 Default instance service name is MS SQL SERVER.
 16 instances will be supported in 2000 version.
 50 instances will supported in 2005 and later versions.
Advantages of Instances
 To install different versions in one machine.
 To reduce cost.
 To maintain production, development, and test environments separately.
4
 To reduce temporary database problems.
 To separate security privileges.
 To maintain standby server.
Installation Guide of Microsoft SQL Servers
SQL Server supports two types of installation:
 Standalone
 Cluster based
Checks
 Check RDP access for the server.
 Check OS bit, IP, domain of server.
 Check if your account is an Administrator account or group to run setup.exe file.
 Software location.
Requirements
 Which version, edition, SP and hotfix if any.
 Service accounts for database engine, agent, SSAS, SSIS, and SSRS, if any.
 Named instance name if any.
 Location for binaries, system, user databases.
 Authentication mode.
 Collation setting.
 List of features.
Pre-requisites for 2005
 Setup support files.
 .net framework 2.0.
 SQL Server native client.
Pre-requisites for 2008 & 2008R2
 Setup support files.
 .net framework 3.5 SP1.
5
 SQL Server native client.
 Windows installer 4.5/later version.
Pre-requisites for 2012 & 2014
 Setup support files.
 .net framework 4.0.
 SQL Server native client.
 Windows installer 4.5/later version.
 Windows PowerShell 2.0.
Installation Steps
Step 1: Download the Evaluation Edition from the following link, http://www.microsoft.com/
download/en/details.aspx?id=29066 once the software is downloaded, and the following files will
be available based on your download (32 or 64 bit) option.
ENUx86SQLFULL_x86_ENU_Core.box
ENUx86SQLFULL_x86_ENU_Install.exe
ENUx86SQLFULL_x86_ENU_Lang.box
OR:
ENUx86SQLFULL_x64_ENU_Core.box
ENUx86SQLFULL_x64_ENU_Install.exe
ENUx86SQLFULL_x64_ENU_Lang.box
Note − X86 (32 bit) and X64 (64 bit)
Step 2: Double-click the “SQLFULL_x86_ENU_Install.exe”
OR:
“SQLFULL_x64_ENU_Install.exe” depending on your requirement; it will extract the required
files for installation in the“SQLFULL_x86_ENU” or “SQLFULL_x64_ENU” folder respectively.
Step 3: Click the “SQLFULL_x86_ENU” or “SQLFULL_x64_ENU_Install.exe” folder and
double-click “SETUP” application.
 For full of understanding, here we have used SQLFULL_x64_ENU_Install.exe software and
follow each instruction of the installation process.
6
Step 4: Once we click on 'setup' application, the following screen will open.
Step 5: Click Installation which is on the left side of the above screen.
7
Step 6: Click the first option of the right side seen on the above screen. The following screen will
open.
Step 7: Click OK and the following screen pops up.
8
Step 8: Click Next on the above screen to get the following screen.
Step 9: Make sure to check the product key selection and click Next.
Step 10: Select the checkbox to accept the license option and click Next.
9
Step 11: Select SQL Server feature installation option and click Next.
Step 12: Select Database engine services checkbox and click Next.
10

Step 13: Enter the named instance (here I used TestInstance) and click Next.
11
Step 14: Click Next on the above screen and the following screen appears.
Step 15: Select service account names and start-up types for the above listed services and click
Collation.
Step 16: Make sure the correct collation selection is checked and click Next.
12
Step 17: Make sure authentication mode selection and administrators are checked and click Data
Directories.
Step 18: Make sure to select the above directory locations and click Next. The following screen
appears
13
Step 19: Click Next on the above screen.
Step 20: Click Next on the above screen to the get the following screen.
14
Step 21: Make sure to check the above selection correctly and click Install as you see on the above
figure.
 Installation complete as you can see on the above screen.
15
Error messages with their possible solutions when you try to install SQL Server 2012
When you try to install Microsoft SQL Server 2012, you receive one or more of the following error
messages or experience one or more of the following symptoms. Additionally, you cannot continue
with the Setup.
 Setup error messages or symptoms with their possible solutions are the following:-
Error message 1:
“The system can’t be open the device or file specified.”
To resolve this problem, use one of the following methods:
 Save the Windows Installer package to a folder that is not encrypted.
 Install the Windows Installer package to a folder that is not encrypted.
 Turn off encryption on the %TEMP% folder.
Error Message 2:
“SQL Server installation failed.”
Solution:
1. Log on to the computer as a user who has administrative credentials.
2. Click Start, click Run, type Control admintools, and then click OK.
3. Double-click Local Security Policy.
4. In the Local Security Settings dialog box, click Local Policies, double-click User Rights
Assignment, and then double-click Backup Files and Directories.
5. In the Backup Files and Directories Properties dialog box, click Add User or Group.
6. In the Select User or Groups dialog box, type the user account that is being used for setup, and
then click OK two times.
7. Repeat the procedure for the other two policies that are mentioned in the "Cause" section.
8. On the File menu, click Exit to close the Local Security Settings dialog box.
16
Error Message 3:
“Setup.rll is either not designed to run on Windows or it contains an error or The ENU localization
is not supported by this SQL Server Media.”
To solve the above problem: copy the setup.rll files from the installation media
path: 1033_ENU_LPx64Setupsqlsupport_msiPFilesSqlServr100Setupfe72iemrRes1033
to Program FilesMicrosoft SQL Server100Setup BootstrapSQLServer2008R2Resources1033.
Error Message 4:
“The installer has encountered an unexpected error installing this package. This may indicate a
problem with this package. The error code is 2337.”
To solve this problem you have to download the file again and run the setup as an Administrator.
It’s unlikely that SQL server 2008 R2 will affect the installation of 2012. Make sure previous failed
installation components are removed
Error Message 5:
“Setup.exe - bad image.”
To solve this error try burning the ISO into a DVD and install from there or download and
extracting the ISO again.
Error Message 6:
“Error occurred during the login process due to bad media.”
Download the image file again, extract and reinstall the setup.
Error message 7:
“The cabinets file ‘sql.cab’ required for this installation is corrupt and cannot be used.”
To solve the problem copy the contents of the SQL DVD to a local disk on the server and use that
as the SQL source file location when prompted or download a new copy of the DVD ISO because
there’s always the possibility the previous copy was corrupted
Error Message 8:
“Errors occur when reading from a file.”
Symptom 1: You cannot select x64 bit installation.
Symptom 2: Some components are missing on the Select Component page of Setup.
17
Error message 9:
“Network error occurred while attempting to read from the file.”
When a network related or instance specific error occurred while establishing a connection to SQL
Server. The server was not found or was not accessible. Verify that the instance name is correct and
that SQL Server is configured to allow remote connections.
Error message 10:
“Source for file 'p76pctiy.dll' is uncompressed (sql_engine_core_shared) Event Viewer error
message failed to initialize SQLSQM timer.”
Cause:
This problem may occur for one of the following reasons:
 The installation media is damaged.
 The installation source is corrupted.
Solution:
 Download the SQL Server image again from the original location, and then rerun the Setup
program.
 If you installed SQL Server over a computer network, install it again from a local drive, and
then rerun the Setup program.
 Rename the Setup.rll file. To do this, follow these steps:
5 Open Windows Explorer. To do this, click Start, click All Programs, click Accessories, and
then click Windows Explorer.
5 Locate and then click the following folder:
C:Program FilesMicrosoft SQL Server100Setup BootstrapSQLServer2012resources1033
Right-click Setup.rll, and then click Rename.
18
5 Type setup.rll.old and press Enter.
5 Rerun the Setup program.
5 If you are using a localized version of SQL Server, you can change the operating system
settings to support localized versions. For more information about how to change the operating
system settings, go to the following Microsoft website:
 IMPORTANT Installations of different language versions of SQL Server instances on the
same computer are not supported.
Error Message 11:
“SQL Server setup media does not support the language.”
Solution:
Go to your Control Panel, Regional Settings and change the "Format" language on the first
section; close window, re-enter and change format back to your locale then launch the setup of
SQL Server.
19
Error Message 12:
“Could not find the Database Engine startup handle (Summary.txt file).”
Solution:
1. Uninstall
 Uninstall the existing SQL Server and all the components from the add remove
program.
 Backup the Registry.
 Delete the following keys using regedit command:
o --HKEY_LOCAL_MACHINESOFTWAREMicrosoftMicrosoft SQL
Server
o --HKEY_LOCAL_MACHINESOFTWAREMicrosoftMSSQLServer
 Go to
HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionUninst
all and delete all the sub-keys referencing SQL Server.
 Go to HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServices and delete all
the keys referencing SQL Server.
 Rename all the SQL Server folders in the computer.
 Reboot the machine.
2. Fresh Installation
 Start a fresh installation. Locate Setup.exe file in SQL Server installable.
 Right click on Setup file and select Run As Administrator to launch the setup.
 If you reach to Server Configuration page select startup account for Database
Engine services as NT AuthoritySYSTEM which is also called as Local System
account.
20
The SQL Server Setup Log Files
Each execution of Setup creates log files are created with a new timestamped log folder at
%programfiles% Microsoft SQL ServernnnSetup BootstrapLog. The time-stamped log
folder name format is YYYYMMDD_hhmmss. When Setup is run in an unattended mode, the logs
are created at % temp%sqlsetup.log. All files in the logs folder are archived into the Log.cab file
in their respective log folder.
A typical Setup request goes through three execution phases:
 Global rules text
 Component update
 User-requested action
In each phase, Setup generates detail and summary logs with additional logs created as appropriate.
Setup is called at least three times per user-requested Setup action.
Datastore files contain a snapshot of the state of all configuration objects being tracked by the
Setup process, and are useful for troubleshooting configuration errors. XML file dumps are created
for datastore objects for each execution phase. They are saved in their own log subfolder under the
time-stamped log folder, as follows:
 Datastore_GlobalRules
 Datastore_ComponentUpdated
 Datastore
The following sections describe SQL Server Setup log files:
Summary Text
This file shows the SQL Server components that were detected during Setup, the operating system
environment, command-line parameter values if they are specified, and the overall status of each
MSI/MSP that was executed.
The log is organized into the following sections:
 An overall summary of the execution
 Properties and the configuration of the computer where SQL Server Setup was run
 SQL Server product features previously installed on the computer
 Description of the installation version and installation package properties
21
 Runtime input settings that are provided during install
 Location of the configuration file
 Details of the execution results
 Global rules
 Rules specific to the installation scenario
 Failed rules
 Location of the rules report file
It is located at %programfiles% Microsoft SQL ServernnnSetup BootstrapLog. To find errors in
the summary text file, search the file by using the "error" or "failed" keywords.
Summary_engine-base_YYYYMMDD_HHMMss.txt
The summary_engine base file is similar to the summary file and is generated during the main
workflow. It is located at %programfiles% Microsoft SQL ServernnnSetup BootstrapLog.
Summary_engine-base_YYYYMMDD_HHMMss_ComponentUpdate.txt
The component update summary log file is similar to the summary file and is generated during the
component update workflow. It is located at %programfiles%MicrosoftSQL ServernnnSetup
BootstrapLog.
Summary_engine-base_<VersionNumber>MMDD_HHMMss_GlobalRules.txt
The global rules summary log file is similar to the summary file generated during the global rules
workflow. It is located at %programfiles% Microsoft SQL ServernnnSetup BootstrapLog.
Detail.txt
Detail.txt is generated for the main workflow such as install or upgrade, and provides the details of
the execution. The logs in the file are generated based on the time when each action for the
installation was invoked, and show the order in which the actions were executed, and their
dependencies. It is located at %programfiles% Microsoft SQL ServernnnSetup.
BootstrapLogDetail.txt.
If an error occurs during the Setup process, the exception or error are logged at the end of this file.
To find the errors in this file, first examine the end of the file followed by a search of the file for
the "error" or "exception" keywords.
22
Detail_ComponentUpdate.txt
The Detail_ComponentUpdate.txt file is generated for the component update workflow and is
similar to Detail.txt. It is located at %programfiles% Microsoft SQL ServernnnSetup
BootstrapLog.
Detail_GlobalRules.txt
Detail_GlobalRules.txt is generated for the global rules execution and is similar to Detail.txt. It is
located at %programfiles% Microsoft SQL ServernnnSetup BootstrapLog.
MSI log files
The MSI log files provide details of the installation package process. They are generated by the
MSIEXEC during the installation of the specified package.
Types of MSI log files:
<Feature><Architecture><Interaction>.log
<Feature><Architecture><Language>_<Interaction>.log
<Feature><Architecture><Interaction>_<workflow>.log
The MSI log files are located at %programfiles%MicrosoftSQLServernnnSetup
BootstrapLog.log.
At the end of the file is a summary of the execution which includes the success or failure status and
properties. To find the error in the MSI file, search for "value 3" and usually the errors can be
found close to the string.
ConfigurationFile.ini
The configuration file contains the input settings that are provided during installation. It can be
used to restart the installation without having to enter the settings manually. However, passwords
for the accounts, PID, and some parameters are not saved in the configuration file. The settings can
be either added to the file or provided by using the command line or the Setup user interface. It is
located at %programfiles% Microsoft SQL ServernnnSetup.
BootstrapLog.SystemConfigurationCheck_Report.htm
The system configuration check report contains a short description for each executed rule, and the
execution status. It is located at %programfiles% Microsoft SQL ServernnnSetup
BootstrapLog.
23
MS SQL Server - Architecture
We can classify the architecture of SQL Server into the following parts for easily understanding:
 General architecture
 Memory architecture
 Data file architecture
 Log file architecture
General Architecture
Client: Where the request initiated.
Query: SQL query which is high level language.
Logical Units: Keywords, expressions and operators, etc.
N/W Packets: Network related code.
Protocols: In SQL Server we have four protocols.
 Shared memory (for local connections and troubleshooting purpose).
 Named pipes (for connections which are in LAN connectivity).
 TCP/IP (for connections which are in WAN connectivity).
 VIA: Virtual Interface Adapter (requires special hardware to set up by vendor and also
deprecated from SQL 2012 version).
Server: Where SQL Services got installed and databases reside.
Relational Engine: This is where real execution will be done. It contains Query parser, Query
optimizer and Query executor.
Query Parser (Command Parser) and Compiler (Translator): This will check syntax of the
query and it will convert the query to machine language.
Query Optimizer: It will prepare the execution plan as output by taking query, statistics and
Algebrizer tree as input.
Execution Plan: It is like a roadmap, which contains the order of all the steps to be performed as
part of the query execution.
24
Query Executor: This is where the query will be executed step by step with the help of execution
plan and also the storage engine will be contacted.
Storage Engine: It is responsible for storage and retrieval of data on the storage system (disk,
SAN, etc.,), data manipulation, locking and managing transactions.
SQL OS: This lies between the host machine (Windows OS) and SQL Server. All the activities
performed on database engine are taken care of by SQL OS. SQL OS provides various operating
system services, such as memory management deals with buffer pool, log buffer and deadlock
detection using the blocking and locking structure.
Checkpoint Process: Checkpoint is an internal process that writes all dirty pages (modified pages)
from Buffer Cache to Physical disk. Apart from this, it also writes the log records from log buffer
to physical file. Writing of Dirty pages from buffer cache to data file is also known as Hardening of
dirty pages.
It is a dedicated process and runs automatically by SQL Server at specific intervals. SQL Server
runs checkpoint process for each database individually. Checkpoint helps to reduce the recovery
time for SQL Server in the event of unexpected shutdown or system crashFailure.
Memory Architecture
Following are some of the salient features of memory architecture.
 One of the primary design goals of all database software is to minimize disk I/O because disk
reads and writes are among the most resource-intensive operations.
 Memory in windows can be called with Virtual Address Space, shared by Kernel mode (OS
mode) and User mode (Application like SQL Server).
 SQL Server "User address space" is broken into two regions: MemToLeave and Buffer Pool.
 Size of MemToLeave (MTL) and Buffer Pool (BPool) is determined by SQL Server during
startup.
 Buffer management is a key component in achieving I/O highly efficiency. The buffer
management component consists of two mechanisms: the buffer manager to access and update
database pages, and the buffer pool to reduce database file I/O. The buffer pool is further
divided into multiple sections. The most important ones being the buffer cache (also referred to
as data cache) and procedure cache. Buffer cache holds the data pages in memory so that
frequently accessed data can be retrieved from cache. The alternative would be reading data
pages from the disk. Reading data pages from cache optimizes performance by minimizing the
25
number of required I/O operations which are inherently slower than retrieving data from the
memory.
 Procedure cache keeps the stored procedure and query execution plans to minimize the
number of times that query plans have to be generated. You can find out information about the
size and activity within the procedure cache using DBCC PROCCACHE statement.
Other portions of buffer pool include:
 System level data structures − Holds SQL Server instance level data about databases and
locks.
 Log cache − Reserved for reading and writing transaction log pages.
 Connection context − Each connection to the instance has a small area of memory to record
the current state of the connection. This information includes stored procedure and user-defined
function parameters, cursor positions and more.
 Stack space − Windows allocates stack space for each thread started by SQL Server.
Data File Architecture
Data File architecture has the following components:
File Groups
Database files can be grouped together in file groups for allocation and administration purposes.
No file can be a member of more than one file group. Log files are never part of a file group. Log
space is managed separately from data space.
There are two types of file groups in SQL Server, Primary and User-defined. Primary file group
contains the primary data file and any other files not specifically assigned to another file group. All
pages for the system tables are allocated in the primary file group. User-defined file groups are any
file groups specified using the file group keyword in create database or alter database statement.
One file group in each database operates as the default file group. When SQL Server allocates a
page to a table or index for which no file group was specified when they were created, the pages
are allocated from default file group. To switch the default file group from one file group to
another file group, it should have db_owner fixed db role.
By default, primary file group is the default file group. User should have db_owner fixed database
role in order to take backup of files and file groups individually.
26
Files
Databases have three types of files - Primary data file, Secondary data file, and Log file. Primary
data file is the starting point of the database and points to the other files in the database.
Every database has one primary data file. We can give any extension for the primary data file but
the recommended extension is .mdf. Secondary data file is a file other than the primary data file in
that database. Some databases may have multiple secondary data files. Some databases may not
have a single secondary data file. Recommended extension for secondary data file is .ndf.
Log files hold all of the log information used to recover the database. Database must have at least
one log file. We can have multiple log files for one database. The recommended extension for log
file is .ldf.
The location of all the files in a database are recorded in both master database and the primary file
for the database. Most of the time, the database engine uses the file location from the master
database.
Files have two names − Logical and Physical. Logical name is used to refer to the file in all T-SQL
statements. Physical name is the OS_file_name; it must follow the rules of OS. Data and Log files
can be placed on either FAT or NTFS file systems, but cannot be placed on compressed file
systems. There can be up to 32,767 files in one database.
Extents
Extents are basic unit in which space is allocated to tables and indexes. An extent is 8 contiguous
pages or 64KB. SQL Server has two types of extents - Uniform and Mixed. Uniform extents are
made up of only single object. Mixed extents are shared by up to eight objects.
Pages
It is the fundamental unit of data storage in MS SQL Server. The size of the page is 8KB. The start
of each page is 96 byte header used to store system information such as type of page, amount of
free space on the page and object id of the object owning the page. There are nine (9) types of data
pages in SQL Server:
 Data: Data rows with all data except text, ntext and image data.
 Index: Index entries.
 TestImage: Text, image and ntext data.
 GAM: Information about allocated extents.
 SGAM: Information about allocated extents at system level.
 PFS: Information about free space available on pages.
 IAM: Information about extents used by a table or index.
27
 Bulk Changed Map (BCM) − Information about extents modified by bulk operations since the
last backup log statement.
 Differential Changed Map (DCM) − Information about extents that have changed since the last
backup database statement.
Log File Architecture
The SQL Server transaction log operates logically as if the transaction log is a string of log records.
Each log record is identified by Log Sequence Number (LSN). Each log record contains the ID of
the transaction that it belongs to.
Log records for data modifications record either the logical operation performed or they record the
before and after images of the modified data. The before image is a copy of the data before the
operation is performed; the after image is a copy of the data after the operation has been performed.
The steps to recover an operation depend on the type of log record −
 Logical operation logged.
o To roll the logical operation forward, the operation is performed again.
o To roll the logical operation back, the reverse logical operation is performed.
 Before and after image logged.
o To roll the operation forward, the after image is applied.
o To roll the operation back, the before image is applied.
Different types of operations are recorded in the transaction log. These operations include −
 The start and end of each transaction.
 Every data modification (insert, update, or delete). This includes changes by system stored
procedures or data definition language (DDL) statements to any table, including system tables.
 Every extent and page allocation or de allocation.
 Creating or dropping a table or index.
Rollback operations are also logged. Each transaction reserves space on the transaction log to make
sure that enough log space exists to support a rollback that is caused by either an explicit rollback
statement or if an error is encountered. This reserved space is freed when the transaction is
completed.
28
The section of the log file from the first log record that must be present for a successful database-
wide rollback to the last-written log record is called the active part of the log, or the active log. This
is the section of the log required to a full recovery of the database. No part of the active log can
ever be truncated. LSN of this first log record is known as the minimum recovery LSN (Min LSN).
The SQL Server Database Engine divides each physical log file internally into a number of virtual
log files. Virtual log files have no fixed size, and there is no fixed number of virtual log files for a
physical log file.
The Database Engine chooses the size of the virtual log files dynamically while it is creating or
extending log files. The Database Engine tries to maintain a small number of virtual files. The size
or number of virtual log files cannot be configured or set by administrators. The only time virtual
log files affect system performance is if the physical log files are defined by small size and
growth_increment values.
The size value is the initial size for the log file and the growth_increment value is the amount of
space added to the file every time new space is required. If the log files grow to a large size
because of many small increments, they will have many virtual log files. This can slow down
database startup and also log backup and restore operations.
We recommend that you assign log files a size value close to the final size required, and also have
a relatively large growth_increment value. SQL Server uses a write-ahead log (WAL), which
guarantees that no data modifications are written to disk before the associated log record is written
to disk. This maintains the ACID properties for a transaction.
Checkpoints in SQL Server
In SQL Server 2012 there are four types of checkpoints:
 Automatic: This is the most common checkpoint which runs as a process in the background to
make sure SQL Server Database can be recovered in the time limit defined by the Recovery
Interval − Server Configuration Option.
 Indirect: This is new in SQL Server 2012. This also runs in the background but to meet a user-
specified target recovery time for the specific database where the option has been configured.
Once the Target_Recovery_Time for a given database has been selected, this will override the
Recovery Interval specified for the server and avoid automatic checkpoint on such Database.
 Manual: This one runs just like any other T-SQL statement, once you issue checkpoint command
it will run to its completion. Manual checkpoint runs for your current database only. You can also
specify the Checkpoint_Duration which is optional - this duration specifies the time in which you
want your checkpoint to complete.
29
 Internal: As a user you can’t control internal checkpoint. Issued on specific operations such as:
 Shutdown initiates a checkpoint operation on all databases except when shutdown is
not clean (shutdown with nowait).
 If the recovery model gets changed from FullBulk-logged to Simple.
 While taking backup of the database.
 If your DB is in simple recovery model, checkpoint process executes automatically
either when the log becomes 70% full, or based on Server option-Recovery Interval.
 Alter database command to add or remove a datalog file also initiates a checkpoint.
 Checkpoint also takes place when the recovery model of the DB is bulk-logged and a
minimally logged operation is performed.
 DB Snapshot creation.
 Lazy Writer Process: Lazy writer will push dirty pages to disk for an entirely different reason,
because it needs to free up memory in the buffer pool. This happens when SQL server comes
under memory pressure. As far as I am aware, this is controlled by an internal process and there is
no setting for it. SQL server constantly monitors memory usage to assess resource contention (or
availability); its job is to make sure that there is a certain amount of free space available at all
times. As part of this process, when it notices any such resource contention, it triggers Lazy Writer
to free up some pages in memory by writing out dirty pages to disk. It employs Least Recently
Used (LRU) algorithm to decide which pages are to be flushed to the disk. If Lazy Writer is
always active, it could indicate memory bottleneck.
SQL Server Management Studio (SSMS)
SQL Server Management Studio (SSMS) is the main administration console for SQL Server.
SSMS enables you to create database objects (such as databases, tables, views etc), view the data
within your database; you can configure user accounts, transfer data between databases, and more.
SQL Server Management Studio is a workstation componentclient tool that will be installed if we
select workstation component in installation steps. This allows you to connect to and manage your
SQL Server from a graphical interface instead of having to use the command line.
In order to connect to a remote instance of an SQL Server, you will need this or similar software. It
is used by Administrators, Developers, Testers, etc.
30
The following methods are used to open SQL Server Management Studio.
First Method:
Start → All Programs → MS SQL Server 2012 → SQL Server Management Studio.
Second Method:
Go to Run and type SQLWB (For 2005 Version) SSMS (For 2008 and Later Versions). Then press
Enter.
SQL Server Management Studio will be open up as shown in the following snapshot in either of
the above method.
MS SQL Server: Login Database
A login is a simple credential for accessing SQL Server. For example, you provide your username
and password when logging on to Windows or even your e-mail account. This username and
password builds up the credentials. Therefore, credentials are simply a username and a password.
SQL Server allows four types of logins −
 A login based on Windows credentials.
 A login specific to SQL Server.
 A login mapped to a certificate.
 A login mapped to asymmetric key.
In this manual document, we are interested in logins based on Windows Credentials and logins
specific to SQL Server.
31
Logins based on Windows credentials allow you to log in to SQL Server using a Windows
username and password. If you need to create your own credentials (username and password,) you
can create a login specific to SQL Server.
To create, alter, or remove a SQL Server login, you can take one of two approaches:
 Using SQL Server Management Studio.
 Using T-SQL statements.
Method 1: Using SQL Server Management Studio
Step 1: After connecting to SQL Server Instance, expand logins folder as shown in the following
snapshot.
32
Step 2: Right-click on Logins, then click Newlogin, and the following screen will open.
Then the following screen will open:
33
Step 3: Fill the Login name, Password and Confirm password columns as shown in the above
screen and then click OK.
Login will be created as shown in the following image.
Method 2: Using T-SQL Script
Create login yourloginname with password='yourpassword'
To create login name with TestLogin and password ‘P@ssword’ run below the following query.
Create login TestLogin with password='P@ssword'
Here's what SQL Server Management Studio looks like when you first open it up:
The left pane contains the Object Explorer. The Object Explorer provides navigation to databases,
server objects (such as triggers), log files, and more.
The right pane allows you to write queries against the database and view the results. In this
screenshot I have opened a blank query by clicking the "New Query" button. You can also bring up
other windows, such as the Properties window.
34
The SQL Language
The name SQL stands for Structured Query Language. It is pronounced “S-Q-L” and can also be
pronounced “SE-QUE-EL”.
 SQL is a standard language for accessing and manipulating databases.
 SQL is a computer language designed to get information from data that is stored in a
relational database.
 SQL is different from most other computer languages. With SQL, you describe the type
of information you want. The computer then determines the best procedure to use to
obtain it and runs that procedure. This is called a declarative computer language because
the focus is on the result:
 You specify what the result should look like. The computer is allowed to use any method
of processing as long as it obtains the correct result.
 Most other computer languages are procedural. These are languages like C, COBOL,
Java, Assembler, FORTRAN, Visual Basic, and others. In these languages, you describe
the procedure that will be applied to the data; you do not describe the result. The result is
whatever emerges from applying the procedure to the data.
 SQL is a nonprocedural language, in contrast to the procedural or third generation
languages (3GLs) such as COBOL and C that had been created up to that time.
 SQL describes what data to retrieve, delete, or insert, rather than how to perform the
operation.
 Two standards organizations, the American National Standards Institute (ANSI) and the
International Standards Organization (ISO), currently promote SQL standards to industry.
Notes about SQL
 SQL is the designated language for getting information from a relational database.
 SQL says what information to get, rather than how to get it.
 Basic SQL is easy to learn.
 SQL empowers people by giving them control over information.
 SQL allows people to handle information in new ways.
 SQL makes information powerful by bringing it to people when they need it.
35
What Can SQL do?
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views
Data Manipulation Language (DML) Vs Data Definition Language (DDL)
SQL can be divided into two parts:
 Data Manipulation Language (DML)
 Data Definition Language (DDL)
Data Manipulation language (DML): is used to retrieve and manipulate data in a relational
database.
The query and update commands form the Data Manipulation Language (DML) parts of SQL are:
SELECT: Extracts data from a database
UPDATE: Updates data in a database
DELETE: Deletes data from a database
INSERT INTO: Inserts new data into a database
Data Definition Language (DDL): A part of SQL permits database tables to be created or deleted.
It also defines indexes (keys), specifies links between tables, and imposes constraints between
tables. The most important DDL statements in SQL are:
 CREATE DATABASE: Creates a new Database.
 ALTER DATABASE: Modifies a Database.
 DROP DATABASE: Deletes a Database.
36
 CREATE TABLE : Creates a new Table
 ALTER TABLE : Modifies a Table
 DROP TABLE : Deletes a Table
 CREATE INDEX: Creates an index (search key).
 DROP INDEX : Deletes an index
37
LAB1: MS SQLServer:Database creation using Graphical User Interface of
SQL Server Management Studio
Objective:
 To Show how to create a database and Tables using graphical user interface (GUI) in MS SQL
Server 2012.
 In MS SQL Server, two types of databases are available:
 System databases
 User Databases
System Databases
System databases are created automatically when we install MS SQL Server. The followings are
system databases of Microsoft SQL Server:
 Master
 Model
 MSDB
 Tempdb
 Resource (Introduced in 2005 version)
 Distribution (It’s for Replication feature only)
Table 2: System Databases
Database Type Description
Master System Database Stores system level information such as user accounts,
configuration settings, and info on all other databases.
Model System Database This database is used as a template for all other databases that
are created.
MSDB System Database Used by the SQL Server Agent for configuring alerts and
scheduled jobs etc
TEMPDB System Database Holds all temporary tables, temporary stored procedures, and
any other temporary storage requirements generated by SQL
Server.
38
1.1 How to Create Database in Microsoft SQL Server 2012 using SSMS
1. Open Microsoft SQL Management Studio
2. Connect to the database engine using database administrator credentials
3. Expand the server node
4. Right click Databases and select New Database
5 Name your database and click "OK":
39
1.2 Creating a Table
1. Ensuring you have the right database expanded, right click on the "Tables" icon and Click "New
Table...“
 While you have the above screen open, do the following:
1. Using the values in the screenshot; complete the details in the "Column Name", "Data Type"
column "Length" and "Allow Nulls" fields.
2. Make the IndividualId column an "identity column", by setting "Is Identity" to "Yes" (this
option is under the "Identity Specification" section in the bottom pane).
Note that to set values in the bottom pane, you need to select the column name in the top pane
first). This column is going to be an auto-number column - it will contain an incrementing number
for each record that is created.
40
3. Save the table by clicking File > Save Table_1:
41
1.3 Editing Table Rows
• We can use the "Edit Top 200 Rows" option to add data to our created table.
• To use this option, right click on the table you wish to open, and select "Edit Top 200 Rows".
42
LAB 2: Starting writing SQL Statements using SQL Server Management
Studio Command line Query Editor
Objective:
 To show the basics of Standard Query Language Syntaxes using SQL Server Management
Studio.
Data Types of SQL Server
SQL Server supplies a set of system data tyes that define all the types of data that can be used with
SQL Server. The Data types in SQL Server are organized into the following categories:
1. Exact numeric
2. Approximate numeric
3. Date and time
4. Character strings
5. Binary strings
Table 3: Exact Numeric, Approximate Numeric and Date and Time Data types
Data Type Storage Value Range Purpose
bigint 8 bytes -2E63 to 2E63-1
Stores very large numbers
that can be positive or
negative.
int 4 bytes -2E31 to 2E31 - 1
Stores whole numbers that
can be positive and negatives.
smallint 2 bytes -32,768 to 32,767
Stores whole numbers that
can be positive and negatives.
tinyint 1 bytes 0 to 255
Stores a small range of
positive whole numbers.
43
decimal(p,s)
5-17 bytes
depending on the
precision
-10E38 + 1 to -10E38 - 1 Stores decimal up to a
maximum of 38 places.
numeric (p,s)
5-17 bytes
depending on the
precision
-10E38 + 1 to -10E38 - 1 Functionally equivalent to
decimal, and can be used
interchangeably with
decimal.
float(p) 4 0r 8 bytes
-2.23E308 to 2.3E308 Stores large floating point
numbers that exceed the
capacity of decimal data type.
real 4 bytes
-3.4E38 to 3.4E38 Still valid, but replaced by
float to meet the SQL-92
standard.
money 8 bytes
-
922,337,203,685,477,5808
to
922,337,203,685,477,5807
Stores large currency values.
smallmoney 4 bytes
-214,748.3648 to
214,748.3647
Stores small currency
values
datetime 8 bytes
January 1, 1753, through
December 31, 9999 within
an accuracy of 3.33
milliseconds.
Stores large date and time
values.
smalldatetime 4 bytes
January 1, 1900, through
June 6, 2079 within an
accuracy of 1 minute.
Stores a small range of date
and time values.
44
Table 4: Character and string Data types
Data type Storage Number of characters Purpose
char(n) 1 up to 8,000 bytes Maximum of 8,000 characters ANSI data type that has
fixed width.
varchar(n) 1 up to 8,000 bytes Maximum of 8,000 characters ANSI data type that has
fixed variable width.
varchar(max) Up to 2 GB Maximum of 1,073,741,824
characters
ANSI data type that has
fixed variable width.
text Up to 2 GB Maximum of 1,073,741,824
characters
ANSI data type that has
fixed variable width.
nchar(n) 2 up to 8,000 bytes Maximum of 4000 characters Unicode data type that
has fixed width.
nvarchar(n) 2 up to 8,000 bytes Maximum of 4000 characters Unicode data type that
has fixed variable width.
nvarchar(max) Up to 2 GB Maximum of 1,073,741,824
characters
Unicode data type that
has fixed variable width.
ntext Up to 2 GB Maximum of 536,870,912
characters
Unicode data type that
has fixed variable width.
Table 5: Binary Data types
Data type Storage Purpose
binary(n) 1 up to 8,000 bytes Stores fixed size binary data
varbinary(n) 1 up to 8,000 bytes
Stores variable size binary data
type.
varbinary(max) Up to 2 GB
Stores variable size binary data
type.
image Up to 2 GB
Stores variable size binary data
type.
45
2.1 Create Database Statement
To start writing an SQL statement in your SQL Server Management Studio you have three options:
1. Go to the File menu and select New -> Query with current connection.
2. Click New Query from the quick access tool bar.
46
3. Press Ctrl + N keys from your keyboard.
After you choose and apply either of the above three options you can start to write a query on the
white area of the SQL Server Management Studio window as shown as below.
Syntax:
CREATE DATABASE database_name;
Example: Create a database called University
CREATE DATABASE University;
47
You have three options to execute your written Query:
1. Select the statement and go to Query menu and from the given drop down options select
Execute.
2. Select your SQL statement and click Execute from the quick access toolbar.
3. Write click on the free space of your SQL editor and select execute from the given options.
48
After you executed the above SQL statement you have to see the message under your editor that
says “Command(s) completed successfully.” Which means your University database is created
successfully.
Now you can find your new created Database which is named as University in Object Explorer
window under Databases folder as shown as below.
49
2.2 Create Table Statement
Before you going to write an SQL statement to create under in your University Databse first you
have to check the current working available is University database or not and you also ave to
change the current available working database is University. To check and set your working
database as University follows the following steps:
 Go to the quick access tool bar and check the available databases list or you can easily access it
by pressing Ctrl+U from your keyboard.
 As you see in the above figure the current database is master so to use the University database
as a current working database drop down the available database list and select University.
50
Syntax:
CREATE TABLE table_name;
(field1 datatype , field2 datatype, field3 datatype);
Example: Using SQL Server Create the following tables under the University Database
1. Department (dno,dname)
2. Student (idNo, fname, lname, age, sex, dnumber)
Solution:
CREATE TABLE Department
( DeptId int not null,
DeptName varchar(15) not null );
CREATE TABLE Student
( idNo varchar(10) not null, FName varchar(15),LName varchar(15), Age int ,
Sex char(1), DeptId int );
 After you write and execute the above SQL statement your Department and Student tables are
successfully created under University Database.
51
SQL Alter Table Syntax
To add a column in a table, use the following Syntax:
ALTER TABLE table_name
ADD column_name datatype
Example:
ALTER TABLE Student
ADD GPA float;
Changing the Data type of a column in a Relational Database
To change the data type of a column in a table, use the following Syntax:
SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
Example:
ALTER TABLE Student
ALTER COLUMN Sex varchar(6)
52
LAB 3: Implementing Constraints
Objectives:
 To show how to create constraints in MS SQL server 2012
 To show how the relational model supports well defined theory of constraints on attributes or
tables.
3.1 Primary Key Constraints
3.1.1 Adding a primary key while creating a Table
Example:
CREATE DATABASE HumanResource;
CREATE TABLE Department.
(
DeptId int IDENTITY(1,1) PRIMARY KEY, DeptName varchar(50) NOT NULL
)
3.1.2 Adding a primary key after a Table is created
This section shows how to add a primary key to a table, even after the table is created.
Syntax:
ALTER TABLE table_name
ADD CONSTRAINT name_of_the_constraint
PRIMARY KEY (list_of_columns_in_the_primary_key);
Remark: In SQL Server, the column to be used as a Primary key should defined as NOT NULL.
Example: Changing the primary key of a table Department under the University Database.
Use University
Alter table Department add constraint pk primary key (DeptId);
53
Dropping a primary key constraint
Example 1:
Alter table department drop constraint pk DeptId;
Example 2: Not using the name of the constraint to drop it.
alter table department drop primary key;
3.2 Foreign Key Constraints
Example:
Use HumanResource
Create table Employee
(
EmpId int primary key, Name nvarchar(15), City varchar(25),
DeptId int references Department(DeptId) on update cascade on delete cascade
)
OR
Use Human Resource
Create table Managers (
ManId int primary key, Name nvarchar(15),
DeptId int null foreign key (DeptID) references Department(DeptID) on update cascade on delete
cascade
)
OR
Create table Employee
(
EMPId int not null, Name nvarchar(15), DeptId int null , City varchar(25), primary key(EmpID),
54
CONSTRAIN fk foreign key(DeptId) references Department(DeptId) )
3.2.1 SQL FOREIGN KEY Constraint on ALTER TABLE
Use University
ALTER TABLE Student
ADD FOREIGN KEY (DeptId) REFERENCES Department(DeptId)
OR
Use University
ALTER TABLE Student
ADD CONSTRAINT fk
FOREIGN KEY (DeptId) REFERENCES Department(DeptId)
DROP ING a FOREIGN KEY Constraint
Use University
ALTER TABLE Student
DROP CONSTRAINT fk
55
Lab 4: Default Constraints
Objective:
 To Practice how to use Default constraints in MS SQL server.
SQL DEFAULT Constraint:
 The DEFAULT constraint is used to insert a default value into a column.
 The default value will be added to all new records, if no other value is specified.
4.1 SQL DEFAULT Constraint on CREATE TABLE
Now you are expected to know how to create a database and tables so create a database you want
which is determined by a table “Persons” and practice Default constraints using the following SQL
statements.
 A DEFAULT constraint on the "City" column when the "Persons" table is created:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(35) NOT NULL,MiddleName varchar (35) FirstName varchar(35),
Address varchar(75),
City varchar(25) DEFAULT ‘Addis Ababa'
)
4.2 SQL DEFAULT Constraint on ALTER TABLE
To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:
SQL Server / MS Access: Syntax:
ALTER TABLE Table_Name ADD CONSTRAINT DF_SomeDFCName DEFAULT
'Some_Name' FOR Column_Name;
56
Examples:
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'Adama’
OR
Use Human Resource
ALTER TABLE Employee ADD CONSTRAINT DF_CityName DEFAULT 'Addis
Ababa' FOR City;
4.3 DROP a DEFAULT Constraint
• To drop a DEFAULT constraint, use the following SQL:
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT
OR
ALTER TABLE Persons
DROP CONSTRAINT defaultContsraintName;
57
Lab 5: SQL CHECK Constraint
Objective:
 Practice CHECK constraint in SQL Server 2012 Relational Database.
The CHECK constraint is used to limit the value range that can be placed in a column. If you
define a CHECK constraint on a single column it allows only certain values for this column. If you
define a CHECK constraint on a table it can limit the values in certain columns based on values in
other columns in the row.
5.1 SQL CHECK Constraint on CREATE TABLE
The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is
created. The CHECK constraint specifies that the column "PId" must only include integers greater
than 0.
The following SQL statement can be used in Oracle and MS Access in addition to SQL Server:
CREATE TABLE Persons
(
P_Id int NOT NULL CHECK (P_Id>0), LastName varchar(255) NOT NULL, FirstName
varchar(255),
Address varchar (255), City varchar (255)
)
 To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL Syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons
( P_Id int NOT NULL,
LastName varchar(255) NOT NULL, FirstName varchar(255),
Address varchar(255), City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Addis Ababa')
)
58
To create a CHECK constraint on the "PId" column when the table is already created, use the
following SQL statement:
 MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD CHECK (P_Id>0)
 To know about how to allow naming of a CHECK constraint, and for defining a CHECK
constraint on multiple columns, look the following example:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Addis Ababa')
5.2 DROPING a CHECK Constraint
To drop a CHECK constraint, use the following SQL:
 SQL Server / Oracle / MS Access:
ALTER TABLE Persons
DROP CONSTRAINT chk_Person
59
LAB 6: SQL Create Index Statement
Objective:
 To practice an INDEX statement in SQL Server 2012 Relational Database.
The CREATE INDEX statement is used to create indexes in tables.
Indexes allow the database application to find data fast; without reading the whole table.
Indexes:
 An index can be created in a table to find data more quickly and efficiently.
 The users cannot see the indexes; they are just used to speed up searches/queries.
 Duplicate values are allowed except in unique index:
Note: You should only create indexes on columns (and tables) that will be frequently searched
against.
6.1 Create an Index
Syntax:
CREATE INDEX index_name
ON table_name (column_name)
SQL CREATE UNIQUE INDEX
 When a unique index is created on a table, Duplicate values are not allowed.
Syntax:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
Note: The syntax for creating index is varies among different databases. Therefore: Check the
syntax for creating indexes in your database.
60
Example:
The SQL statement below creates an index named "PIndex" on the "LastName" column in the
"Persons" table:
CREATE INDEX PIndex
ON Persons (LastName)
If you want to create an index on a combination of columns, you can list the column names within
the parentheses, separated by commas:
CREATE INDEX PIndex
ON Persons (LastName, FirstName)
61
LAB 7: SQL Drop statements of COLUMN, INDEX, TABLE and DATABASE
Objective:
 To practice drop statements in SQL Server 2012.
A drop statement is used to remove a Column, Table and an entire database when each of them is
needed to be deleted respectively.
7.1 Dropping an existing column
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name
Examples:
alter table department drop column sex
ALTER TABLE Persons
DROP COLUMN Sex
7.2 The DROP INDEX Statement
Indexes, tables, and databases can be easily deleted/removed with the DROP statement
The DROP INDEX statement is used to delete an index in a table.
 DROP INDEX Syntax for MS Access:
DROP INDEX index_name ON table_name
 DROP INDEX Syntax for MS SQL Server:
DROP INDEX table_name.index_name
62
7.3 The DROP TABLE Statement
• The DROP TABLE statement is used to delete a table.
Syntax:
DROP TABLE table_name
7.4 The TRUNCATE TABLE Statement
What if we only want to delete the data inside the table, and not the table itself? Then, use the
TRUNCATE TABLE statement:
Syntax:
TRUNCATE TABLE table_name
Example:
TRUNCATE TABLE Persons
63
LAB 8: Data Manipulation Language (DML)
Objectives:
 Inserting Records (INSERT SQL Command)
 Updating Records (UPDATE SQL Command)
 Deleting Records (DELETE Command)
 The SELECT statement
8.1 Inserting Records (INSERT SQL Command)
Syntax:
USE database_name
INSERT INTO tablename [(first_column,...,last_column)] VALUES (first_value,...,last_value)
Example:
• Option 1:
USE University
INSERT INTO Student (StudID, FirstName, LastName, Sex) VALUES ('AB101', 'Abebe',
'Kebede', 'Male')
• Option 2:
USE University
INSERT INTO Student
VALUES ('AB101', 'Abebe', 'Kebede', 'Male')
 Option 3:
USE University
INSERT INTO Student (Sex, FirstName, LastName, StudID) VALUES ('Male', 'Abebe', 'Kebede',
'AB101')
64
8.2 Updating Records (UPDATE SQL Command)
Syntax:
USE database_name
UPDATE tablename
SET columnname = “newvalue" ["nextcolumn" = “newvalue2"...]
WHERE columnname OPERATOR value [AND|OR columname OPERATOR value]
Example:
USE University UPDATE Student
SET FirstName = 'Almaz', Sex = 'Female' WHERE FirstName = 'Abebe' AND Sex = 'Male'
8.3 Deleting Records (DELETE Command) SYNTAX:
USE database_name
DELETE [FROM] table_name
[WHERE search_condition]
Example:
USE University
DELETE FROM Student
WHERE FirstName = 'Almaz' AND Sex = 'Female'
 In the Above example you can use “Delete Student” instead of “Delete From Student”
keyword.
65
LAB 9: Selecting Data from the Database Tables
Objectives:
 To show how to retrieve the selected data’s from a Database.
Before starting looking the process of selecting data from databases, first you have to download the
sample AdventureWorksLT2012 Database (Zip file) from:
https://msftdbprodsamples.codeplex.com/releases/view/93587 then extract and add it in to your
SQL server 2012 Database lists.
66
Attaching AdventureWorks Sample Database in to the SQL Server 2012R2
1. Go to the directory :
C:Program FilesMicrosoft SQLServerMSSQL11.MSSQLSERVERMSSQLDATA and
copy the AdventureWorks2012_Data.mdf file.
2. Go to the Microsoft SQL Server Management Studio -> right click on Databases and select
attach option from the given lists.
67
3. In the popup attach databases window click the Add button.
68
4. Select AdventureWorks2012_Data.mdf and click OK.
69
5. Under “AdventureWorks LT2012” database details select the log file type then click Remove
button and finally Click OK.
70
6. Now you can find your AdventureWorksLT2012 database under the databases folder in your
Microsoft SQL Server Management Studio.
71
Syntax of selecting data from SQL server 2012 Databases:
USE database_name
SELECT [ALL | DISTINCT] column1 [, column2] FROM table1 [, table2]
[WHERE conditions] [GROUP BY column-list] [HAVING conditions]
[ORDER BY column-list [ASC | DESC] ]
Example 1:
use AdventureWorksLT2012
SELECT * FROM SalesLT.Customer use AdventureWorksLT2012
SELECT FROM SalesLT.Customer use AdventureWorksLT2012
SELECT FirstName,LastName,EmailAddress FROM SalesLT.Customer
use AdventureWorksLT2012
SELECT FirstName + ' ' + LastName AS FULLNAME,EmailAddress
FROM SalesLT.Customer
 Comparison Operators used in the WHERE clause are the following:
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> or! = Not equal to
Examples 2:
Use AdventureWorksLT2012
SELECT FirstName,LastName,EmailAddress
FROM SalesLT.Customer
WHERE LastName='Vargas'
72
Example 3:
Use AdventureWorksLT2012
SELECT FirstName,LastName,EmailAddress
FROM SalesLT.Customer
WHERE CustomerID=600
Example 4:
Use AdventureWorksLT2012
SELECT FirstName,LastName,EmailAddress
FROM SalesLT.Customer
WHERE CustomerID > 600
Example 5:
use AdventureWorksLT2012
SELECT FirstName,LastName,EmailAddress
FROM SalesLT.Customer
WHERE CustomerID > 600 AND CustomerID < =800
Example 6:
use AdventureWorksLT2012
SELECT CustomerID,FirstName,LastName,EmailAddress
FROM SalesLT.Customer
WHERE CustomerID BETWEEN 600 AND 800
73
Order By clause
Syntax:
SELECT column1, column2
FROM list-of-tables
ORDER BY column-list [ASC | DESC];
Example 1:
Use AdventureWorksLT2012
SELECT CustomerID, FirstName, MiddleName, LastName, EmailAddress, CompanyName
FROM SalesLT.Customer
where MiddleName IS NOT NULL ORDER BY FirstName
Example 2:
Use AdventureWorksLT2012
SELECT ProductID,Name,Color,ListPrice
FROM SalesLT.Product
ORDER BY ListPrice
Example 3:
Use AdventureWorksLT2012
SELECT ProductID,Name,Color,ListPrice
FROM SalesLT.Product
ORDER BY ListPrice DESC
Example 4:
Use AdventureWorksLT2012
SELECT ProductID,Name,Color,ListPrice
FROM SalesLT.Product
WHERE Color is NOT NULL ORDER BY Color,ListPrice DESC
74
LAB 10: IN, NOTIN, LIKE and ISNULL Keywords
Objective:
 Practice the IN, NOTIN, LIKE and ISNULL keywords of SQL in MS SQL Server 2012.
10.1 The use of IN keyword
Example 1:
Use AdventureWorksLT2012
SELECT CustomerID,FirstName,LastName,EmailAddress
FROM SalesLT.Customer
WHERE CustomerID IN ( 600, 700,500,533,800)
Example 2:
Use AdventureWorksLT2012
SELECT CustomerID,FirstName,LastName,EmailAddress
FROM SalesLT.Customer
WHERE LastName IN ('Tian','Clark','Harding')
10.2 The use of NOT IN keyword
Example:
Use AdventureWorksLT2012
SELECT CustomerID,FirstName,LastName,EmailAddress
FROM SalesLT.Customer
WHERE CustomerID NOT IN (600, 700,500,533,800)
75
10.3 The use of LIKE keyword
Example:
Use AdventureWorksLT2012
SELECT CustomerID,FirstName,LastName,EmailAddress , CompanyName
FROM SalesLT.Customer
WHERE CompanyName LIKE 'Metro%'
SELECT CustomerID,FirstName,LastName,EmailAddress ,CompanyName
FROM SalesLT.Customer
WHERE CompanyName LIKE „%Metro%'
SELECT CustomerID,FirstName,LastName,EmailAddress , CompanyName
FROM SalesLT.Customer
WHERE CompanyName LIKE „%_etro%'
10.4 IS NULL Keyword
Example:
Use AdventureWorksLT2012
SELECT CustomerID, FirstName, MiddleName, LastName, EmailAddress, CompanyName
FROM SalesLT.Customer where MiddleName IS NULL
Exercises:
1. List all the item numbers along with their order date that are Purchased by a customer whose
customerid is 10101, From the items_ordered table
Solution:
SELECT itemno, ordered_date
FROM items_ordered WHERE customerid= 10101
76
2. List the records of all employees whose name beginning with the letter ‘A’ from empinfo Table.
Solution:
SELECT * FROM empInfo
WHERE FirstName like „A%‟;
77
LAB 11: Aggregate functions
Objective:
 Practice aggregate functions in SQL Server 2012.
 Aggregate functions are used to summarize the results of a particular column. These are:
MIN(), MAX(), SUM(), AVG() and COUNT()
11.1 Count function
Example:
Select count(*) as TotalProducts from SalesLT.Product
OR
Select count(ProductID) from SalesLT.Product select count(*)
From SalesLT.Product where Color='Red'
LAB 11.2 MAX and MIN functions
Select MAX(ListPrice) from SalesLT.Product select MIN(ListPrice) from SalesLT.Product
Select MAX(ListPrice) As MaxPrice,MIN(ListPrice) AS MinPrice ,AVG(ListPrice) As
AveragePrice from SalesLT.Product
11.3 Average function
Example:
Select AVG(ListPrice) from SalesLT.Product
11.4 The SUM function
Select SUM (TotalDue)
From SalesLT.SalesOrderHeader
78
LAB 12: Group by clause
Objective:
 To show how to collaborate with SELECT statement to arrange identical data into groups.
The GROUP BY clause will gather all of the rows together that contain data in the specified
column(s) and will allow aggregate functions to be performed on the one or more columns.
GROUP BY clause
Syntax:
SELECT column1[, column2, etc] FROM list-of-tables
GROUP BY "column-list";
Example:
Select Color,count(*) from SalesLT.Product group by Color
12.1 Having clause
Similar to where condition except that HAVING is used with group of records instead of single
records.
Example 1:
Show all the average salaries of departments that are greater than 1200
SELECT dept, AVG (salary) FROM employee
GROUP BY dept
HAVING AVG (salary) > 1200;
79
Example 2:
Select Color,count(*) from SalesLT.Product group by Color having Color is not null
Exercises:
1. Display the sum of the salaries of all employees from empInfo Table
Solution:
SELECT SUM (salary) as TotalSalary
FROM empInfo
2. Using empInfo Table, display the max, min, and average salary.
Solution:
SELECT MAX(salary) as Max , MIN(salary) as Min , AVG(salary) as Average
FROM empInfo
3. Display the number of available records in empInfo Table.
Solution:
SELECT COUNT(*) as count
FROM empInfo
4. Using empInfo table, display the number of employees under each department.
Solution:
SELECT dept, COUNT(*) as count
FROM empInfo
GROUP BY dept
5. Using empInfo Table, display the Max and Min salaries of employees for each department.
Solution:
SELECT dept, MAX (salary) as Max, MIN (salary) as Min
FROM empInfo GROUP BY dept
80
6. List the records of all employees sorted by First Name then by Last Name in descending order.
Solution:
SELECT * FROM empInfo
ORDER BY FirstName, LastName DESC
12.2 Combining conditions and Boolean Operators
The following two keywords are used to combine conditions.
1. AND
3. OR
Syntax:
SELECT column1 [, column2] FROM list-of-tables
WHERE condition1 AND condition2;
Example:
SELECT EmpID, firstname, lastname, city, salary
FROM EmpInfo
WHERE salary >= 500.00 AND city = 'A/A'
12.3 The use of DISTINCT Keyword
Example:
SELECT DISTINCT CountryRegion
FROM SalesLT.Address
SELECT count(DISTINCT StateProvince) FROM SalesLT.Address
81
LAB 13: Tables Join
Objective:
 To show how to implement the combination of columns from one or more tables in a Relational
Database.
Syntax:
SELECT list-of-columns
FROM table1, table2
WHERE search-condition(s)
13.1 Joining Two Tables
Example:
Select a.Name, Color, a.ProductCategoryID, b.Name from SalesLT.Product a,
SalesLT.ProductCategory b where a.ProductCategoryID=b.ProductCategoryID
13.2 INNER JOIN
Example:
Select a.Name,Color,a.ProductCategoryID ,b.Name
From SalesLT.Product a INNER JOIN SalesLT.ProductCategory b
ON a.ProductCategoryID=b.ProductCategoryID
13.3 OUTER JOIN
Example:
select a.Name,Color,a.ProductCategoryID,b.ProductCategoryID,b.Name from SalesLT.Product a
RIGHT OUTER JOIN SalesLT.ProductCategory b ON
a.ProductCategoryID=b.ProductCategoryID
82
13.4 Sub Query
Example:
SELECT FirstName,LastName,CompanyName
FROM SalesLT.Customer WHERE CustomerID
= (select TOP 1 CustomerID
FROM SalesLT.SalesOrderHeader
ORDER BY TotalDue DESC
)
Exercise
Find those Customers who did not place any order?
Solution:
SELECT FirstName,LastName,CompanyName
FROM SalesLT.Customer WHERE CustomerID NOT IN (SELECT DISTINCT CustomerID
FROM SalesLT.SalesOrderHeader
)
Exercise:
Display all customers who have ordered item1
Solution:
SELECT c.customerid,FirstName, LastName
FROM customers c, oredered_items o
Where c.customerid = o.custpmerid
83
LAB 14: View
Objective:
 To show how to implement Views of a Database.
A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.
It can contain all rows of a table or select rows from a table. A view can be created from one or
many tables which depend on the written SQL query to create a view.
Views, which are kind of virtual tables, allow users to do the following:
• Restrict access to the data such that a user can see and (sometimes) modify exactly what they
need and no more.
• · Summarize data from various tables which can be used to generate reports.
14.1 Creating Views
• Database views are created using the CREATE VIEW statement. Views can be created from a
single table, multiple tables, or another view.
• To create a view, a user must have the appropriate system privilege according to the specific
implementation.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2..... FROM table_name
WHERE [condition];
• You can include multiple tables in your SELECT statement in very similar way as you use them
in normal SQL SELECT query.
• Consider the CUSTOMERS table having the following records:
| ID | NAME | AGE | ADDRESS | SALARY
• Now, following is the example to create a view from CUSTOMERS table. This view would be
used to have customer name and age from CUSTOMERS table:
84
CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age
FROM CUSTOMERS;
• Now, you can query CUSTOMERS_VIEW in similar way as you query an actual table.
SQL > SELECT * FROM CUSTOMERS_VIEW WITH CHECK OPTION:
• The WITH CHECK OPTION is a CREATE VIEW statement option.
• The purpose of the WITH CHECK OPTION is to ensure that all UPDATEs and INSERTs
satisfy the condition(s) in the view definition.
• If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
CHECK OPTION:
Example:
CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age
FROM CUSTOMERS WHERE age IS NOT NULL WITH CHECK OPTION;
 In the above case The WITH CHECK OPTION should deny the entry of any NULL values in
the view's AGE column, because the view is defined by data that does not have a NULL value
in the AGE column.
85
14. 2 Updating a View
 A view can be updated under certain conditions:
 The SELECT clause may not contain the keyword DISTINCT.
 The SELECT clause may not contain summary functions.
 The SELECT clause may not contain set operators.
 The SELECT clause may not contain an ORDER BY clause.
 The FROM clause may not contain multiple tables.
 The WHERE clause may not contain subqueries.
 The query may not contain GROUP BY or HAVING.
 Calculated columns may not be updated.
 All NOT NULL columns from the base table must be included in the view in order for the
INSERT query to function.
 So if a view satisfies all the above mentioned rules then you can update a view.
The Following is an example to update the age of Ramesh:
UPDATE CUSTOMERS_VIEW SET AGE = 35
WHERE name='Ramesh';
14.3 Inserting Rows in a View
 Rows of data can be inserted into a view. The same rules that apply to the UPDATE command
also apply to the INSERT command.
 Here, we can’t insert rows in CUSTOMERS_VIEW because we have not included all the NOT
NULL columns in this view, otherwise you can insert rows in a view in similar way as you
insert them in a table.
86
14. 4 Deleting Rows in a View
Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT
commands apply to the DELETE command.
The Following is an example to delete a record having AGE= 22.
DELETE FROM CUSTOMERS_VIEW
WHERE age = 22;
14. 5 Dropping Views:
Obviously, where you have a view, you need a way to drop the view if it is no longer needed. The
syntax is very simple as given below:
DROP VIEW view_name;
The Following is an example to drop CUSTOMERS_VIEW from CUSTOMERS table:
DROP VIEW CUSTOMERS_VIEW;
87
References:
1. Tutorials: MSDN – Microsoft.
(https://msdn.microsoft.com/enus/library/ms167593(v=sql.105).aspx)
2. Tutorials for SQL Server Microsoft Docs.
(https://msdn.microsoft.com/library/ms167593.aspx)
3. MS SQL Server Tutorial.
(https://www.tutorialspoint.com/ms_sql_server/)
4. SQL Server Tutorial.
(https://www.techonthenet.com/sql_server/index.php)
5. Elmasri and Navathe: Fundamentals of Database Systems, 7th
Ed.

More Related Content

What's hot

Ms excel for Accountants
Ms excel for AccountantsMs excel for Accountants
Ms excel for Accountants
zia256
 
Enterprise portal development cookbook
Enterprise portal development cookbookEnterprise portal development cookbook
Enterprise portal development cookbookAhmed Farag
 
Google Search Quality Rating Program General Guidelines 2011
Google Search Quality Rating Program General Guidelines 2011Google Search Quality Rating Program General Guidelines 2011
Google Search Quality Rating Program General Guidelines 2011
Interrocks, Koppelkracht, ELF Voetbal, Voetbalprimeur.nl en Blue Linking
 
Microsoft project server 2010 project managers guide for project web app
Microsoft project server 2010 project managers guide for project web appMicrosoft project server 2010 project managers guide for project web app
Microsoft project server 2010 project managers guide for project web appApimuk Siripitupum
 
Codendi 4.0 User Guide
Codendi 4.0 User GuideCodendi 4.0 User Guide
Codendi 4.0 User Guide
Codendi
 
Hibernate reference
Hibernate referenceHibernate reference
Hibernate reference
Arvind Moorthy
 
Hibernate Reference
Hibernate ReferenceHibernate Reference
Hibernate ReferenceSyed Shahul
 
Microsoft project server 2010 administrators guide
Microsoft project server 2010 administrators guideMicrosoft project server 2010 administrators guide
Microsoft project server 2010 administrators guideApimuk Siripitupum
 
Web Adoption and Implementation
Web Adoption and ImplementationWeb Adoption and Implementation
Web Adoption and Implementation
Assaf Alrousan
 
Health Literacy Online: A Guide to Writing and Designing Easy-to-Use Health W...
Health Literacy Online: A Guide to Writing and Designing Easy-to-Use Health W...Health Literacy Online: A Guide to Writing and Designing Easy-to-Use Health W...
Health Literacy Online: A Guide to Writing and Designing Easy-to-Use Health W...
Path of the Blue Eye Project
 
sun-java-style
sun-java-stylesun-java-style
sun-java-styleAbrarMoiz
 
Excel Training Manual
Excel Training ManualExcel Training Manual
Excel Training ManualSusan Mei
 
Bullet Physic Engine SDK
Bullet Physic Engine SDKBullet Physic Engine SDK
Bullet Physic Engine SDK
ナム-Nam Nguyễn
 
Complete ad troubleshooting
Complete ad troubleshootingComplete ad troubleshooting
Complete ad troubleshooting
apshirame
 
Google guidelines
Google guidelinesGoogle guidelines
Google guidelines
SEOM
 

What's hot (19)

Ms excel for Accountants
Ms excel for AccountantsMs excel for Accountants
Ms excel for Accountants
 
Enterprise portal development cookbook
Enterprise portal development cookbookEnterprise portal development cookbook
Enterprise portal development cookbook
 
Google Search Quality Rating Program General Guidelines 2011
Google Search Quality Rating Program General Guidelines 2011Google Search Quality Rating Program General Guidelines 2011
Google Search Quality Rating Program General Guidelines 2011
 
Morph xit
Morph xitMorph xit
Morph xit
 
Microsoft project server 2010 project managers guide for project web app
Microsoft project server 2010 project managers guide for project web appMicrosoft project server 2010 project managers guide for project web app
Microsoft project server 2010 project managers guide for project web app
 
Codendi 4.0 User Guide
Codendi 4.0 User GuideCodendi 4.0 User Guide
Codendi 4.0 User Guide
 
Hibernate reference
Hibernate referenceHibernate reference
Hibernate reference
 
Hibernate Reference
Hibernate ReferenceHibernate Reference
Hibernate Reference
 
Hibernate Reference
Hibernate ReferenceHibernate Reference
Hibernate Reference
 
Microsoft project server 2010 administrators guide
Microsoft project server 2010 administrators guideMicrosoft project server 2010 administrators guide
Microsoft project server 2010 administrators guide
 
Web Adoption and Implementation
Web Adoption and ImplementationWeb Adoption and Implementation
Web Adoption and Implementation
 
Health Literacy Online: A Guide to Writing and Designing Easy-to-Use Health W...
Health Literacy Online: A Guide to Writing and Designing Easy-to-Use Health W...Health Literacy Online: A Guide to Writing and Designing Easy-to-Use Health W...
Health Literacy Online: A Guide to Writing and Designing Easy-to-Use Health W...
 
sun-java-style
sun-java-stylesun-java-style
sun-java-style
 
Excel Training Manual
Excel Training ManualExcel Training Manual
Excel Training Manual
 
Patient management
Patient managementPatient management
Patient management
 
Bullet Physic Engine SDK
Bullet Physic Engine SDKBullet Physic Engine SDK
Bullet Physic Engine SDK
 
Complete ad troubleshooting
Complete ad troubleshootingComplete ad troubleshooting
Complete ad troubleshooting
 
Google guidelines
Google guidelinesGoogle guidelines
Google guidelines
 
Data base quries
Data base quries Data base quries
Data base quries
 

Similar to Fundamentals of Database Systems Laboratory Manual

Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
Andre Prakoso
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
Syed Zaid Irshad
 
Sql server community_fa_qs_manual
Sql server community_fa_qs_manualSql server community_fa_qs_manual
Sql server community_fa_qs_manualSteve Xu
 
XCC Documentation
XCC   DocumentationXCC   Documentation
XCC Documentation
TIMETOACT GROUP
 
Spring data-keyvalue-reference
Spring data-keyvalue-referenceSpring data-keyvalue-reference
Spring data-keyvalue-reference
dragos142000
 
Big Data: Getting started with Big SQL self-study guide
Big Data:  Getting started with Big SQL self-study guideBig Data:  Getting started with Big SQL self-study guide
Big Data: Getting started with Big SQL self-study guide
Cynthia Saracco
 
Best Practices SQL 2005 SSIS
Best Practices SQL 2005 SSISBest Practices SQL 2005 SSIS
Best Practices SQL 2005 SSIS
ptolozah
 
SQL Server Analysis Services
SQL Server Analysis ServicesSQL Server Analysis Services
SQL Server Analysis Services
Ahmed Al Salih
 
SAP MM Tutorial ds_42_tutorial_en.pdf
SAP MM Tutorial    ds_42_tutorial_en.pdfSAP MM Tutorial    ds_42_tutorial_en.pdf
SAP MM Tutorial ds_42_tutorial_en.pdf
sjha120721
 
Jdbc
JdbcJdbc
Sybase SQL AnyWhere12
Sybase SQL AnyWhere12Sybase SQL AnyWhere12
Sybase SQL AnyWhere12Sunny U Okoro
 
SAP CPI-DS.pdf
SAP CPI-DS.pdfSAP CPI-DS.pdf
SAP CPI-DS.pdf
JagadishBabuParri
 
Slima thesis carnegie mellon ver march 2001
Slima thesis carnegie mellon ver march 2001Slima thesis carnegie mellon ver march 2001
Slima thesis carnegie mellon ver march 2001
Servio Fernando Lima Reina
 
RDB Synchronization, Transcoding and LDAP Directory Services ...
RDB Synchronization, Transcoding and LDAP Directory Services ...RDB Synchronization, Transcoding and LDAP Directory Services ...
RDB Synchronization, Transcoding and LDAP Directory Services ...Videoguy
 
hci10_help_sap_en.pdf
hci10_help_sap_en.pdfhci10_help_sap_en.pdf
hci10_help_sap_en.pdf
JagadishBabuParri
 
Moss2007
Moss2007Moss2007
Moss2007
LiquidHub
 
Optimizing oracle-on-sun-cmt-platform
Optimizing oracle-on-sun-cmt-platformOptimizing oracle-on-sun-cmt-platform
Optimizing oracle-on-sun-cmt-platform
Sal Marcus
 

Similar to Fundamentals of Database Systems Laboratory Manual (20)

Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
 
Sql server community_fa_qs_manual
Sql server community_fa_qs_manualSql server community_fa_qs_manual
Sql server community_fa_qs_manual
 
XCC Documentation
XCC   DocumentationXCC   Documentation
XCC Documentation
 
Spring data-keyvalue-reference
Spring data-keyvalue-referenceSpring data-keyvalue-reference
Spring data-keyvalue-reference
 
Big Data: Getting started with Big SQL self-study guide
Big Data:  Getting started with Big SQL self-study guideBig Data:  Getting started with Big SQL self-study guide
Big Data: Getting started with Big SQL self-study guide
 
Best Practices SQL 2005 SSIS
Best Practices SQL 2005 SSISBest Practices SQL 2005 SSIS
Best Practices SQL 2005 SSIS
 
SQL Server Analysis Services
SQL Server Analysis ServicesSQL Server Analysis Services
SQL Server Analysis Services
 
SAP MM Tutorial ds_42_tutorial_en.pdf
SAP MM Tutorial    ds_42_tutorial_en.pdfSAP MM Tutorial    ds_42_tutorial_en.pdf
SAP MM Tutorial ds_42_tutorial_en.pdf
 
Jdbc
JdbcJdbc
Jdbc
 
Sybase SQL AnyWhere12
Sybase SQL AnyWhere12Sybase SQL AnyWhere12
Sybase SQL AnyWhere12
 
SAP CPI-DS.pdf
SAP CPI-DS.pdfSAP CPI-DS.pdf
SAP CPI-DS.pdf
 
Slima thesis carnegie mellon ver march 2001
Slima thesis carnegie mellon ver march 2001Slima thesis carnegie mellon ver march 2001
Slima thesis carnegie mellon ver march 2001
 
RDB Synchronization, Transcoding and LDAP Directory Services ...
RDB Synchronization, Transcoding and LDAP Directory Services ...RDB Synchronization, Transcoding and LDAP Directory Services ...
RDB Synchronization, Transcoding and LDAP Directory Services ...
 
hci10_help_sap_en.pdf
hci10_help_sap_en.pdfhci10_help_sap_en.pdf
hci10_help_sap_en.pdf
 
R Data
R DataR Data
R Data
 
Moss2007
Moss2007Moss2007
Moss2007
 
Hung_thesis
Hung_thesisHung_thesis
Hung_thesis
 
Optimizing oracle-on-sun-cmt-platform
Optimizing oracle-on-sun-cmt-platformOptimizing oracle-on-sun-cmt-platform
Optimizing oracle-on-sun-cmt-platform
 
FULLTEXT01
FULLTEXT01FULLTEXT01
FULLTEXT01
 

Recently uploaded

The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 

Recently uploaded (20)

The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 

Fundamentals of Database Systems Laboratory Manual

  • 1. i ADDIS ABABA UNIVERSITY COLLEGE OF NATURAL & COMPUTITIONAL SCIENCE DEPARTMENT OF COMPUTER SCIENCE Laboratory Manual for the Fundamentals of Database Systems (COSC 3051) Using Microsoft SQL Server 2012 DBMS Prepared By: Surafiel Habib March 2017
  • 2. ii Table of Contents Acronyms ...........................................................................................................................................vi Objectives of the Manual ................................................................................................................. vii Required Software........................................................................................................................... viii Introduction to Microsoft SQL Server ................................................................................................1 What is SQL Server?.......................................................................................................................1 Usage of SQL Server.......................................................................................................................1 SQL Server Components.................................................................................................................3 Instance of SQL Server ...................................................................................................................3 Advantages of Instances ............................................................................................................. 3 Installation Guide of Microsoft SQL Servers .................................................................................4 Installation Steps......................................................................................................................... 5 Error messages with their possible solutions when you try to install SQL Server 2012.......... 15 The SQL Server Setup Log Files ......................................................................................................20 Summary Text ...............................................................................................................................20 Summary_engine-base_YYYYMMDD_HHMMss.txt ................................................................21 Summary_engine-base_YYYYMMDD_HHMMss_ComponentUpdate.txt................................21 Summary_engine-base_<VersionNumber>MMDD_HHMMss_GlobalRules.txt .......................21 Detail.txt........................................................................................................................................21 BootstrapLogDetail.txt. .............................................................................................................21 Detail_ComponentUpdate.txt........................................................................................................22 Detail_GlobalRules.txt..................................................................................................................22 MSI log files..................................................................................................................................22 ConfigurationFile.ini.....................................................................................................................22 BootstrapLog.SystemConfigurationCheck_Report.htm ...........................................................22 MS SQL Server - Architecture..........................................................................................................23 General Architecture .....................................................................................................................23 Memory Architecture ....................................................................................................................24 Data File Architecture...................................................................................................................25 File Groups................................................................................................................................ 25 Files........................................................................................................................................... 26
  • 3. iii Extents....................................................................................................................................... 26 Pages ......................................................................................................................................... 26 Log File Architecture ....................................................................................................................27 Checkpoints in SQL Server...............................................................................................................28 SQL Server Management Studio (SSMS).........................................................................................29 MS SQL Server: Login Database......................................................................................................30 The SQL Language ...........................................................................................................................34 Data Manipulation Language (DML) Vs Data Definition Language (DDL)...............................35 LAB1: MS SQLServer:Database creation using Graphical User Interface of SQL Server Management Studio...............................................................................................................37 System Databases..........................................................................................................................37 1.1 How to Create Database in Microsoft SQL Server 2012 using SSMS...................................38 1.2 Creating a Table ......................................................................................................................39 1.3 Editing Table Rows.................................................................................................................41 LAB 2: Starting writing SQL Statements using SQL Server Management Studio Command line Query Editor..........................................................................................................................42 Data Types of SQL Server ............................................................................................................42 2.1 Create Database Statement......................................................................................................45 2.2 Create Table Statement ...........................................................................................................49 SQL Alter Table Syntax............................................................................................................ 51 Changing the Data type of a column in a Relational Database................................................. 51 LAB 3: Implementing Constraints....................................................................................................52 3.1 Primary Key Constraints .........................................................................................................52 3.1.1 Adding a primary key while creating a Table.................................................................. 52 3.1.2 Adding a primary key after a Table is created................................................................. 52 Dropping a primary key constraint ........................................................................................... 53 3.2 Foreign Key Constraints..........................................................................................................53 3.2.1 SQL FOREIGN KEY Constraint on ALTER TABLE ........................................................54 Lab 4: Default Constraints ................................................................................................................55 4.1 SQL DEFAULT Constraint on CREATE TABLE.................................................................55 4.2 SQL DEFAULT Constraint on ALTER TABLE ...................................................................55 4.3 DROP a DEFAULT Constraint ..............................................................................................56
  • 4. iv Lab 5: SQL CHECK Constraint........................................................................................................57 5.1 SQL CHECK Constraint on CREATE TABLE .....................................................................57 5.2 DROPING a CHECK Constraint ............................................................................................58 LAB 6: SQL Create Index Statement................................................................................................59 6.1 Create an Index........................................................................................................................59 LAB 7: SQL Drop statements of COLUMN, INDEX, TABLE and DATABASE..........................61 7.1 Dropping an existing column..................................................................................................61 7.2 The DROP INDEX Statement.................................................................................................61 7.3 The DROP TABLE Statement ................................................................................................62 7.4 The TRUNCATE TABLE Statement .....................................................................................62 LAB 8: Data Manipulation Language (DML) .................................................................................63 8.1 Inserting Records (INSERT SQL Command).........................................................................63 8.2 Updating Records (UPDATE SQL Command)......................................................................64 8.3 Deleting Records (DELETE Command) ................................................................................64 LAB 9: Selecting Data from the Database Tables ............................................................................65 Attaching AdventureWorks Sample Database in to the SQL Server 2012R2 .............................66 Syntax of selecting data from SQL server 2012 Databases: ........................................................71 Order By clause.............................................................................................................................73 LAB 10: IN, NOTIN, LIKE and ISNULL Keywords.......................................................................74 10.1 The use of IN keyword..........................................................................................................74 10.2 The use of NOT IN keyword ................................................................................................74 10.3 The use of LIKE keyword.....................................................................................................75 10.4 IS NULL Keyword................................................................................................................75 LAB 11: Aggregate functions ...........................................................................................................77 11.1 Count function.......................................................................................................................77 LAB 11.2 MAX and MIN functions............................................................................................77 11.3 Average function ...................................................................................................................77 LAB 12: Group by clause..................................................................................................................78 12.1 Having clause ........................................................................................................................78 12.2 Combining conditions and Boolean Operators.....................................................................80 12.3 The use of DISTINCT Keyword...........................................................................................80
  • 5. v LAB 13: Tables Join .........................................................................................................................81 13.1 Joining Two Tables...............................................................................................................81 13.2 INNER JOIN .........................................................................................................................81 13.3 OUTER JOIN........................................................................................................................81 13.4 Sub Query..............................................................................................................................82 LAB 14: View...................................................................................................................................83 14.1 Creating Views......................................................................................................................83 14. 2 Updating a View ..................................................................................................................85 14.3 Inserting Rows in a View......................................................................................................85 14. 4 Deleting Rows in a View .....................................................................................................86 14. 5 Dropping Views: ..................................................................................................................86 References:........................................................................................................................................87
  • 6. vi Acronyms BIDS Business Intelligence Development Studio CRM Customer Relationship Management DBMS Database Management System DDL Data Definition Language DML Data Manipulation Language ETL Extract, Transform, Load GAM Global Allocation Map IAX Index Allocation Map IBM International Business Machines IP Internet Protocol MS Microsoft MSI Microsoft Software Installer MSP Microsoft Solution Provider ODBMS Object Database Management System OS Operating System PFS Page Free Space PID Process Identification Number R2 Release Two RDBMS Relational Database Management System RDP Remote Desktop Protocol RTM Release-to-Manufacturing SP Service Pack SQL Standard Query Language SSAS SQL Server Analysis Services SSCM SQL Server Configuration Manager SSIS SQL Server Integration Services SSMS SQL Server Management Studio SSRS SQL Server Reporting Services TCP/IP Transmission Control Protocol/Internet Protocol VIA Virtual Interface Adapter
  • 7. vii Objectives of the Manual This laboratory Manual is prepared to deliver examples and exercises for the fundamentals of Database systems (COSC 3051) course within the Microsoft SQL server 2012 Relational Database Management System tool. The main objective is to learn the basic development of a relational database application and to illustrate the concepts of SQL using simple examples. This laboratory manual has been divided up into fourteen (14) sessions. Each one contains of examples, tasks and exercises about a particular concept in SQL and how it is implemented in MS SQL Server 2012. After completion of this fourteen (14) weeks laboratory guide the students will be able to:  Implement a Data Definition Language (DDL) to create a Relational Databases, Tables and Indexes.  Implement a Data Manipulation Language (DML) to Insert, Update, Select and Delete data’s of the Database tables.  Create queries using basic and advanced SELECT statements.  Perform Join operations on Relational Database Tables.  Implement Aggregate functions in SQL.  Write sub queries.  Create Views of the Database.
  • 8. viii Required Software The Microsoft SQL Server 2012 DBMS must be installed in the laboratory room Personal Computers.
  • 9. 1 Introduction to Microsoft SQL Server Microsoft SQL Server is a Relational Database Management System (RDBMS) developed by Microsoft Software Company. It is built for the basic function of storing and retrieving data as required by other applications and can be run either on the same computer or on another across a network. SQL Server is commonly used as the backend system for websites and corporate CRMs and can support thousands of concurrent users. SQL Server comes with a number of tools to help the users on Database Administration and programming tasks. What is SQL Server?  It is application software, developed by Microsoft Company, which is implemented from the specification of Relational Database Management System (RDBMS).  It is also an Object Relational Database Management System (ORDBMS).  It is platform dependent.  It is both Graphical User Interface (GUI) and command based software.  It supports SQL (SE-QUE-EL) language which is an IBM product, non-procedural, common Database and case insensitive language. Usage of SQL Server  To create Databases.  To maintain Databases.  To analyze the data through SQL Server Analysis Services (SSAS).  To generate reports through SQL Server Reporting Services (SSRS).  To carry out ETL operations through SQL Server Integration Services (SSIS).
  • 10. 2 Table 1: Versions of Microsoft SQL Server Version Name RTM (no SP) SP1 SP2 SP3 SP4 SQL Server 2017 codename vNext 14.0.1000.169 *Latest Version (New) SQL Server 2016 13.0.1601.5 13.0.4001.0 or 13.1.4001.0 SQL Server 2014 12.0.2000.8 12.0.4100.1 or 12.1.4100.1 12.0.5000.0 or 12.2.5000.0 SQL Server 2012 codename Denali 11.0.2100.60 11.0.3000.0 or 11.1.3000.0 11.0.5058.0 or 11.2.5058.0 11.0.6020.0 or 11.3.6020.0 11.0.7001.0 or 11.4.7001.0 SQL Server 2008 R2 codename Kilimanjaro 10.50.1600.1 10.50.2500.0 or 10.51.2500.0 10.50.4000.0 or 10.52.4000.0 10.50.6000.34 or 10.53.6000.34 SQL Server 2008 codename Katmai 10.0.1600.22 10.0.2531.0 or 10.1.2531.0 10.0.4000.0 or 10.2.4000.0 10.0.5500.0 or 10.3.5500.0 10.0.6000.29 or 10.4.6000.29 SQL Server 2005 codename Yukon 9.0.1399.06 9.0.2047 9.0.3042 9.0.4035 9.0.5000 SQL Server 2000 codename Shiloh 8.0.194 8.0.384 8.0.532 8.0.760 8.0.2039 SQL Server 7.0 codename Sphinx 7.0.623 7.0.699 7.0.842 7.0.961 7.0.1063
  • 11. 3 SQL Server Components SQL Server works in client-server architecture; hence it supports two types of components, Workstation and Server.  Workstation components are installed in every device/SQL Server operator’s machine. These are just interfaces to interact with Server components. Example: SSMS, SSCM, Profiler, BIDS, etc.  Server components are installed in centralized server. These are services. Example: SQL Server, SQL Server Agent, SSIS, SSAS, SSRS, SQL browser, SQL Server full text search etc. Instance of SQL Server  An instance is an installation of SQL Server.  An instance is an exact copy of the same software.  If we install 'n' times, then 'n' instances will be created.  There are two types of instances in SQL Server 1. Default 2. Named  In SQL Server Express, a named instance is always used by default, It’s possible to specify an instance name in the process of SQL Server Express installation, or the default named instance of SQL Express is can be used. If the default instance is used it has to be referenced as Computer_NameSQLExpress.  Only one default instance will be supported in one Server.  Multiple named instances will be supported in one Server.  Default instance will take the server name as Instance name.  Default instance service name is MS SQL SERVER.  16 instances will be supported in 2000 version.  50 instances will supported in 2005 and later versions. Advantages of Instances  To install different versions in one machine.  To reduce cost.  To maintain production, development, and test environments separately.
  • 12. 4  To reduce temporary database problems.  To separate security privileges.  To maintain standby server. Installation Guide of Microsoft SQL Servers SQL Server supports two types of installation:  Standalone  Cluster based Checks  Check RDP access for the server.  Check OS bit, IP, domain of server.  Check if your account is an Administrator account or group to run setup.exe file.  Software location. Requirements  Which version, edition, SP and hotfix if any.  Service accounts for database engine, agent, SSAS, SSIS, and SSRS, if any.  Named instance name if any.  Location for binaries, system, user databases.  Authentication mode.  Collation setting.  List of features. Pre-requisites for 2005  Setup support files.  .net framework 2.0.  SQL Server native client. Pre-requisites for 2008 & 2008R2  Setup support files.  .net framework 3.5 SP1.
  • 13. 5  SQL Server native client.  Windows installer 4.5/later version. Pre-requisites for 2012 & 2014  Setup support files.  .net framework 4.0.  SQL Server native client.  Windows installer 4.5/later version.  Windows PowerShell 2.0. Installation Steps Step 1: Download the Evaluation Edition from the following link, http://www.microsoft.com/ download/en/details.aspx?id=29066 once the software is downloaded, and the following files will be available based on your download (32 or 64 bit) option. ENUx86SQLFULL_x86_ENU_Core.box ENUx86SQLFULL_x86_ENU_Install.exe ENUx86SQLFULL_x86_ENU_Lang.box OR: ENUx86SQLFULL_x64_ENU_Core.box ENUx86SQLFULL_x64_ENU_Install.exe ENUx86SQLFULL_x64_ENU_Lang.box Note − X86 (32 bit) and X64 (64 bit) Step 2: Double-click the “SQLFULL_x86_ENU_Install.exe” OR: “SQLFULL_x64_ENU_Install.exe” depending on your requirement; it will extract the required files for installation in the“SQLFULL_x86_ENU” or “SQLFULL_x64_ENU” folder respectively. Step 3: Click the “SQLFULL_x86_ENU” or “SQLFULL_x64_ENU_Install.exe” folder and double-click “SETUP” application.  For full of understanding, here we have used SQLFULL_x64_ENU_Install.exe software and follow each instruction of the installation process.
  • 14. 6 Step 4: Once we click on 'setup' application, the following screen will open. Step 5: Click Installation which is on the left side of the above screen.
  • 15. 7 Step 6: Click the first option of the right side seen on the above screen. The following screen will open. Step 7: Click OK and the following screen pops up.
  • 16. 8 Step 8: Click Next on the above screen to get the following screen. Step 9: Make sure to check the product key selection and click Next. Step 10: Select the checkbox to accept the license option and click Next.
  • 17. 9 Step 11: Select SQL Server feature installation option and click Next. Step 12: Select Database engine services checkbox and click Next.
  • 18. 10 Step 13: Enter the named instance (here I used TestInstance) and click Next.
  • 19. 11 Step 14: Click Next on the above screen and the following screen appears. Step 15: Select service account names and start-up types for the above listed services and click Collation. Step 16: Make sure the correct collation selection is checked and click Next.
  • 20. 12 Step 17: Make sure authentication mode selection and administrators are checked and click Data Directories. Step 18: Make sure to select the above directory locations and click Next. The following screen appears
  • 21. 13 Step 19: Click Next on the above screen. Step 20: Click Next on the above screen to the get the following screen.
  • 22. 14 Step 21: Make sure to check the above selection correctly and click Install as you see on the above figure.  Installation complete as you can see on the above screen.
  • 23. 15 Error messages with their possible solutions when you try to install SQL Server 2012 When you try to install Microsoft SQL Server 2012, you receive one or more of the following error messages or experience one or more of the following symptoms. Additionally, you cannot continue with the Setup.  Setup error messages or symptoms with their possible solutions are the following:- Error message 1: “The system can’t be open the device or file specified.” To resolve this problem, use one of the following methods:  Save the Windows Installer package to a folder that is not encrypted.  Install the Windows Installer package to a folder that is not encrypted.  Turn off encryption on the %TEMP% folder. Error Message 2: “SQL Server installation failed.” Solution: 1. Log on to the computer as a user who has administrative credentials. 2. Click Start, click Run, type Control admintools, and then click OK. 3. Double-click Local Security Policy. 4. In the Local Security Settings dialog box, click Local Policies, double-click User Rights Assignment, and then double-click Backup Files and Directories. 5. In the Backup Files and Directories Properties dialog box, click Add User or Group. 6. In the Select User or Groups dialog box, type the user account that is being used for setup, and then click OK two times. 7. Repeat the procedure for the other two policies that are mentioned in the "Cause" section. 8. On the File menu, click Exit to close the Local Security Settings dialog box.
  • 24. 16 Error Message 3: “Setup.rll is either not designed to run on Windows or it contains an error or The ENU localization is not supported by this SQL Server Media.” To solve the above problem: copy the setup.rll files from the installation media path: 1033_ENU_LPx64Setupsqlsupport_msiPFilesSqlServr100Setupfe72iemrRes1033 to Program FilesMicrosoft SQL Server100Setup BootstrapSQLServer2008R2Resources1033. Error Message 4: “The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2337.” To solve this problem you have to download the file again and run the setup as an Administrator. It’s unlikely that SQL server 2008 R2 will affect the installation of 2012. Make sure previous failed installation components are removed Error Message 5: “Setup.exe - bad image.” To solve this error try burning the ISO into a DVD and install from there or download and extracting the ISO again. Error Message 6: “Error occurred during the login process due to bad media.” Download the image file again, extract and reinstall the setup. Error message 7: “The cabinets file ‘sql.cab’ required for this installation is corrupt and cannot be used.” To solve the problem copy the contents of the SQL DVD to a local disk on the server and use that as the SQL source file location when prompted or download a new copy of the DVD ISO because there’s always the possibility the previous copy was corrupted Error Message 8: “Errors occur when reading from a file.” Symptom 1: You cannot select x64 bit installation. Symptom 2: Some components are missing on the Select Component page of Setup.
  • 25. 17 Error message 9: “Network error occurred while attempting to read from the file.” When a network related or instance specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. Error message 10: “Source for file 'p76pctiy.dll' is uncompressed (sql_engine_core_shared) Event Viewer error message failed to initialize SQLSQM timer.” Cause: This problem may occur for one of the following reasons:  The installation media is damaged.  The installation source is corrupted. Solution:  Download the SQL Server image again from the original location, and then rerun the Setup program.  If you installed SQL Server over a computer network, install it again from a local drive, and then rerun the Setup program.  Rename the Setup.rll file. To do this, follow these steps: 5 Open Windows Explorer. To do this, click Start, click All Programs, click Accessories, and then click Windows Explorer. 5 Locate and then click the following folder: C:Program FilesMicrosoft SQL Server100Setup BootstrapSQLServer2012resources1033 Right-click Setup.rll, and then click Rename.
  • 26. 18 5 Type setup.rll.old and press Enter. 5 Rerun the Setup program. 5 If you are using a localized version of SQL Server, you can change the operating system settings to support localized versions. For more information about how to change the operating system settings, go to the following Microsoft website:  IMPORTANT Installations of different language versions of SQL Server instances on the same computer are not supported. Error Message 11: “SQL Server setup media does not support the language.” Solution: Go to your Control Panel, Regional Settings and change the "Format" language on the first section; close window, re-enter and change format back to your locale then launch the setup of SQL Server.
  • 27. 19 Error Message 12: “Could not find the Database Engine startup handle (Summary.txt file).” Solution: 1. Uninstall  Uninstall the existing SQL Server and all the components from the add remove program.  Backup the Registry.  Delete the following keys using regedit command: o --HKEY_LOCAL_MACHINESOFTWAREMicrosoftMicrosoft SQL Server o --HKEY_LOCAL_MACHINESOFTWAREMicrosoftMSSQLServer  Go to HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionUninst all and delete all the sub-keys referencing SQL Server.  Go to HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServices and delete all the keys referencing SQL Server.  Rename all the SQL Server folders in the computer.  Reboot the machine. 2. Fresh Installation  Start a fresh installation. Locate Setup.exe file in SQL Server installable.  Right click on Setup file and select Run As Administrator to launch the setup.  If you reach to Server Configuration page select startup account for Database Engine services as NT AuthoritySYSTEM which is also called as Local System account.
  • 28. 20 The SQL Server Setup Log Files Each execution of Setup creates log files are created with a new timestamped log folder at %programfiles% Microsoft SQL ServernnnSetup BootstrapLog. The time-stamped log folder name format is YYYYMMDD_hhmmss. When Setup is run in an unattended mode, the logs are created at % temp%sqlsetup.log. All files in the logs folder are archived into the Log.cab file in their respective log folder. A typical Setup request goes through three execution phases:  Global rules text  Component update  User-requested action In each phase, Setup generates detail and summary logs with additional logs created as appropriate. Setup is called at least three times per user-requested Setup action. Datastore files contain a snapshot of the state of all configuration objects being tracked by the Setup process, and are useful for troubleshooting configuration errors. XML file dumps are created for datastore objects for each execution phase. They are saved in their own log subfolder under the time-stamped log folder, as follows:  Datastore_GlobalRules  Datastore_ComponentUpdated  Datastore The following sections describe SQL Server Setup log files: Summary Text This file shows the SQL Server components that were detected during Setup, the operating system environment, command-line parameter values if they are specified, and the overall status of each MSI/MSP that was executed. The log is organized into the following sections:  An overall summary of the execution  Properties and the configuration of the computer where SQL Server Setup was run  SQL Server product features previously installed on the computer  Description of the installation version and installation package properties
  • 29. 21  Runtime input settings that are provided during install  Location of the configuration file  Details of the execution results  Global rules  Rules specific to the installation scenario  Failed rules  Location of the rules report file It is located at %programfiles% Microsoft SQL ServernnnSetup BootstrapLog. To find errors in the summary text file, search the file by using the "error" or "failed" keywords. Summary_engine-base_YYYYMMDD_HHMMss.txt The summary_engine base file is similar to the summary file and is generated during the main workflow. It is located at %programfiles% Microsoft SQL ServernnnSetup BootstrapLog. Summary_engine-base_YYYYMMDD_HHMMss_ComponentUpdate.txt The component update summary log file is similar to the summary file and is generated during the component update workflow. It is located at %programfiles%MicrosoftSQL ServernnnSetup BootstrapLog. Summary_engine-base_<VersionNumber>MMDD_HHMMss_GlobalRules.txt The global rules summary log file is similar to the summary file generated during the global rules workflow. It is located at %programfiles% Microsoft SQL ServernnnSetup BootstrapLog. Detail.txt Detail.txt is generated for the main workflow such as install or upgrade, and provides the details of the execution. The logs in the file are generated based on the time when each action for the installation was invoked, and show the order in which the actions were executed, and their dependencies. It is located at %programfiles% Microsoft SQL ServernnnSetup. BootstrapLogDetail.txt. If an error occurs during the Setup process, the exception or error are logged at the end of this file. To find the errors in this file, first examine the end of the file followed by a search of the file for the "error" or "exception" keywords.
  • 30. 22 Detail_ComponentUpdate.txt The Detail_ComponentUpdate.txt file is generated for the component update workflow and is similar to Detail.txt. It is located at %programfiles% Microsoft SQL ServernnnSetup BootstrapLog. Detail_GlobalRules.txt Detail_GlobalRules.txt is generated for the global rules execution and is similar to Detail.txt. It is located at %programfiles% Microsoft SQL ServernnnSetup BootstrapLog. MSI log files The MSI log files provide details of the installation package process. They are generated by the MSIEXEC during the installation of the specified package. Types of MSI log files: <Feature><Architecture><Interaction>.log <Feature><Architecture><Language>_<Interaction>.log <Feature><Architecture><Interaction>_<workflow>.log The MSI log files are located at %programfiles%MicrosoftSQLServernnnSetup BootstrapLog.log. At the end of the file is a summary of the execution which includes the success or failure status and properties. To find the error in the MSI file, search for "value 3" and usually the errors can be found close to the string. ConfigurationFile.ini The configuration file contains the input settings that are provided during installation. It can be used to restart the installation without having to enter the settings manually. However, passwords for the accounts, PID, and some parameters are not saved in the configuration file. The settings can be either added to the file or provided by using the command line or the Setup user interface. It is located at %programfiles% Microsoft SQL ServernnnSetup. BootstrapLog.SystemConfigurationCheck_Report.htm The system configuration check report contains a short description for each executed rule, and the execution status. It is located at %programfiles% Microsoft SQL ServernnnSetup BootstrapLog.
  • 31. 23 MS SQL Server - Architecture We can classify the architecture of SQL Server into the following parts for easily understanding:  General architecture  Memory architecture  Data file architecture  Log file architecture General Architecture Client: Where the request initiated. Query: SQL query which is high level language. Logical Units: Keywords, expressions and operators, etc. N/W Packets: Network related code. Protocols: In SQL Server we have four protocols.  Shared memory (for local connections and troubleshooting purpose).  Named pipes (for connections which are in LAN connectivity).  TCP/IP (for connections which are in WAN connectivity).  VIA: Virtual Interface Adapter (requires special hardware to set up by vendor and also deprecated from SQL 2012 version). Server: Where SQL Services got installed and databases reside. Relational Engine: This is where real execution will be done. It contains Query parser, Query optimizer and Query executor. Query Parser (Command Parser) and Compiler (Translator): This will check syntax of the query and it will convert the query to machine language. Query Optimizer: It will prepare the execution plan as output by taking query, statistics and Algebrizer tree as input. Execution Plan: It is like a roadmap, which contains the order of all the steps to be performed as part of the query execution.
  • 32. 24 Query Executor: This is where the query will be executed step by step with the help of execution plan and also the storage engine will be contacted. Storage Engine: It is responsible for storage and retrieval of data on the storage system (disk, SAN, etc.,), data manipulation, locking and managing transactions. SQL OS: This lies between the host machine (Windows OS) and SQL Server. All the activities performed on database engine are taken care of by SQL OS. SQL OS provides various operating system services, such as memory management deals with buffer pool, log buffer and deadlock detection using the blocking and locking structure. Checkpoint Process: Checkpoint is an internal process that writes all dirty pages (modified pages) from Buffer Cache to Physical disk. Apart from this, it also writes the log records from log buffer to physical file. Writing of Dirty pages from buffer cache to data file is also known as Hardening of dirty pages. It is a dedicated process and runs automatically by SQL Server at specific intervals. SQL Server runs checkpoint process for each database individually. Checkpoint helps to reduce the recovery time for SQL Server in the event of unexpected shutdown or system crashFailure. Memory Architecture Following are some of the salient features of memory architecture.  One of the primary design goals of all database software is to minimize disk I/O because disk reads and writes are among the most resource-intensive operations.  Memory in windows can be called with Virtual Address Space, shared by Kernel mode (OS mode) and User mode (Application like SQL Server).  SQL Server "User address space" is broken into two regions: MemToLeave and Buffer Pool.  Size of MemToLeave (MTL) and Buffer Pool (BPool) is determined by SQL Server during startup.  Buffer management is a key component in achieving I/O highly efficiency. The buffer management component consists of two mechanisms: the buffer manager to access and update database pages, and the buffer pool to reduce database file I/O. The buffer pool is further divided into multiple sections. The most important ones being the buffer cache (also referred to as data cache) and procedure cache. Buffer cache holds the data pages in memory so that frequently accessed data can be retrieved from cache. The alternative would be reading data pages from the disk. Reading data pages from cache optimizes performance by minimizing the
  • 33. 25 number of required I/O operations which are inherently slower than retrieving data from the memory.  Procedure cache keeps the stored procedure and query execution plans to minimize the number of times that query plans have to be generated. You can find out information about the size and activity within the procedure cache using DBCC PROCCACHE statement. Other portions of buffer pool include:  System level data structures − Holds SQL Server instance level data about databases and locks.  Log cache − Reserved for reading and writing transaction log pages.  Connection context − Each connection to the instance has a small area of memory to record the current state of the connection. This information includes stored procedure and user-defined function parameters, cursor positions and more.  Stack space − Windows allocates stack space for each thread started by SQL Server. Data File Architecture Data File architecture has the following components: File Groups Database files can be grouped together in file groups for allocation and administration purposes. No file can be a member of more than one file group. Log files are never part of a file group. Log space is managed separately from data space. There are two types of file groups in SQL Server, Primary and User-defined. Primary file group contains the primary data file and any other files not specifically assigned to another file group. All pages for the system tables are allocated in the primary file group. User-defined file groups are any file groups specified using the file group keyword in create database or alter database statement. One file group in each database operates as the default file group. When SQL Server allocates a page to a table or index for which no file group was specified when they were created, the pages are allocated from default file group. To switch the default file group from one file group to another file group, it should have db_owner fixed db role. By default, primary file group is the default file group. User should have db_owner fixed database role in order to take backup of files and file groups individually.
  • 34. 26 Files Databases have three types of files - Primary data file, Secondary data file, and Log file. Primary data file is the starting point of the database and points to the other files in the database. Every database has one primary data file. We can give any extension for the primary data file but the recommended extension is .mdf. Secondary data file is a file other than the primary data file in that database. Some databases may have multiple secondary data files. Some databases may not have a single secondary data file. Recommended extension for secondary data file is .ndf. Log files hold all of the log information used to recover the database. Database must have at least one log file. We can have multiple log files for one database. The recommended extension for log file is .ldf. The location of all the files in a database are recorded in both master database and the primary file for the database. Most of the time, the database engine uses the file location from the master database. Files have two names − Logical and Physical. Logical name is used to refer to the file in all T-SQL statements. Physical name is the OS_file_name; it must follow the rules of OS. Data and Log files can be placed on either FAT or NTFS file systems, but cannot be placed on compressed file systems. There can be up to 32,767 files in one database. Extents Extents are basic unit in which space is allocated to tables and indexes. An extent is 8 contiguous pages or 64KB. SQL Server has two types of extents - Uniform and Mixed. Uniform extents are made up of only single object. Mixed extents are shared by up to eight objects. Pages It is the fundamental unit of data storage in MS SQL Server. The size of the page is 8KB. The start of each page is 96 byte header used to store system information such as type of page, amount of free space on the page and object id of the object owning the page. There are nine (9) types of data pages in SQL Server:  Data: Data rows with all data except text, ntext and image data.  Index: Index entries.  TestImage: Text, image and ntext data.  GAM: Information about allocated extents.  SGAM: Information about allocated extents at system level.  PFS: Information about free space available on pages.  IAM: Information about extents used by a table or index.
  • 35. 27  Bulk Changed Map (BCM) − Information about extents modified by bulk operations since the last backup log statement.  Differential Changed Map (DCM) − Information about extents that have changed since the last backup database statement. Log File Architecture The SQL Server transaction log operates logically as if the transaction log is a string of log records. Each log record is identified by Log Sequence Number (LSN). Each log record contains the ID of the transaction that it belongs to. Log records for data modifications record either the logical operation performed or they record the before and after images of the modified data. The before image is a copy of the data before the operation is performed; the after image is a copy of the data after the operation has been performed. The steps to recover an operation depend on the type of log record −  Logical operation logged. o To roll the logical operation forward, the operation is performed again. o To roll the logical operation back, the reverse logical operation is performed.  Before and after image logged. o To roll the operation forward, the after image is applied. o To roll the operation back, the before image is applied. Different types of operations are recorded in the transaction log. These operations include −  The start and end of each transaction.  Every data modification (insert, update, or delete). This includes changes by system stored procedures or data definition language (DDL) statements to any table, including system tables.  Every extent and page allocation or de allocation.  Creating or dropping a table or index. Rollback operations are also logged. Each transaction reserves space on the transaction log to make sure that enough log space exists to support a rollback that is caused by either an explicit rollback statement or if an error is encountered. This reserved space is freed when the transaction is completed.
  • 36. 28 The section of the log file from the first log record that must be present for a successful database- wide rollback to the last-written log record is called the active part of the log, or the active log. This is the section of the log required to a full recovery of the database. No part of the active log can ever be truncated. LSN of this first log record is known as the minimum recovery LSN (Min LSN). The SQL Server Database Engine divides each physical log file internally into a number of virtual log files. Virtual log files have no fixed size, and there is no fixed number of virtual log files for a physical log file. The Database Engine chooses the size of the virtual log files dynamically while it is creating or extending log files. The Database Engine tries to maintain a small number of virtual files. The size or number of virtual log files cannot be configured or set by administrators. The only time virtual log files affect system performance is if the physical log files are defined by small size and growth_increment values. The size value is the initial size for the log file and the growth_increment value is the amount of space added to the file every time new space is required. If the log files grow to a large size because of many small increments, they will have many virtual log files. This can slow down database startup and also log backup and restore operations. We recommend that you assign log files a size value close to the final size required, and also have a relatively large growth_increment value. SQL Server uses a write-ahead log (WAL), which guarantees that no data modifications are written to disk before the associated log record is written to disk. This maintains the ACID properties for a transaction. Checkpoints in SQL Server In SQL Server 2012 there are four types of checkpoints:  Automatic: This is the most common checkpoint which runs as a process in the background to make sure SQL Server Database can be recovered in the time limit defined by the Recovery Interval − Server Configuration Option.  Indirect: This is new in SQL Server 2012. This also runs in the background but to meet a user- specified target recovery time for the specific database where the option has been configured. Once the Target_Recovery_Time for a given database has been selected, this will override the Recovery Interval specified for the server and avoid automatic checkpoint on such Database.  Manual: This one runs just like any other T-SQL statement, once you issue checkpoint command it will run to its completion. Manual checkpoint runs for your current database only. You can also specify the Checkpoint_Duration which is optional - this duration specifies the time in which you want your checkpoint to complete.
  • 37. 29  Internal: As a user you can’t control internal checkpoint. Issued on specific operations such as:  Shutdown initiates a checkpoint operation on all databases except when shutdown is not clean (shutdown with nowait).  If the recovery model gets changed from FullBulk-logged to Simple.  While taking backup of the database.  If your DB is in simple recovery model, checkpoint process executes automatically either when the log becomes 70% full, or based on Server option-Recovery Interval.  Alter database command to add or remove a datalog file also initiates a checkpoint.  Checkpoint also takes place when the recovery model of the DB is bulk-logged and a minimally logged operation is performed.  DB Snapshot creation.  Lazy Writer Process: Lazy writer will push dirty pages to disk for an entirely different reason, because it needs to free up memory in the buffer pool. This happens when SQL server comes under memory pressure. As far as I am aware, this is controlled by an internal process and there is no setting for it. SQL server constantly monitors memory usage to assess resource contention (or availability); its job is to make sure that there is a certain amount of free space available at all times. As part of this process, when it notices any such resource contention, it triggers Lazy Writer to free up some pages in memory by writing out dirty pages to disk. It employs Least Recently Used (LRU) algorithm to decide which pages are to be flushed to the disk. If Lazy Writer is always active, it could indicate memory bottleneck. SQL Server Management Studio (SSMS) SQL Server Management Studio (SSMS) is the main administration console for SQL Server. SSMS enables you to create database objects (such as databases, tables, views etc), view the data within your database; you can configure user accounts, transfer data between databases, and more. SQL Server Management Studio is a workstation componentclient tool that will be installed if we select workstation component in installation steps. This allows you to connect to and manage your SQL Server from a graphical interface instead of having to use the command line. In order to connect to a remote instance of an SQL Server, you will need this or similar software. It is used by Administrators, Developers, Testers, etc.
  • 38. 30 The following methods are used to open SQL Server Management Studio. First Method: Start → All Programs → MS SQL Server 2012 → SQL Server Management Studio. Second Method: Go to Run and type SQLWB (For 2005 Version) SSMS (For 2008 and Later Versions). Then press Enter. SQL Server Management Studio will be open up as shown in the following snapshot in either of the above method. MS SQL Server: Login Database A login is a simple credential for accessing SQL Server. For example, you provide your username and password when logging on to Windows or even your e-mail account. This username and password builds up the credentials. Therefore, credentials are simply a username and a password. SQL Server allows four types of logins −  A login based on Windows credentials.  A login specific to SQL Server.  A login mapped to a certificate.  A login mapped to asymmetric key. In this manual document, we are interested in logins based on Windows Credentials and logins specific to SQL Server.
  • 39. 31 Logins based on Windows credentials allow you to log in to SQL Server using a Windows username and password. If you need to create your own credentials (username and password,) you can create a login specific to SQL Server. To create, alter, or remove a SQL Server login, you can take one of two approaches:  Using SQL Server Management Studio.  Using T-SQL statements. Method 1: Using SQL Server Management Studio Step 1: After connecting to SQL Server Instance, expand logins folder as shown in the following snapshot.
  • 40. 32 Step 2: Right-click on Logins, then click Newlogin, and the following screen will open. Then the following screen will open:
  • 41. 33 Step 3: Fill the Login name, Password and Confirm password columns as shown in the above screen and then click OK. Login will be created as shown in the following image. Method 2: Using T-SQL Script Create login yourloginname with password='yourpassword' To create login name with TestLogin and password ‘P@ssword’ run below the following query. Create login TestLogin with password='P@ssword' Here's what SQL Server Management Studio looks like when you first open it up: The left pane contains the Object Explorer. The Object Explorer provides navigation to databases, server objects (such as triggers), log files, and more. The right pane allows you to write queries against the database and view the results. In this screenshot I have opened a blank query by clicking the "New Query" button. You can also bring up other windows, such as the Properties window.
  • 42. 34 The SQL Language The name SQL stands for Structured Query Language. It is pronounced “S-Q-L” and can also be pronounced “SE-QUE-EL”.  SQL is a standard language for accessing and manipulating databases.  SQL is a computer language designed to get information from data that is stored in a relational database.  SQL is different from most other computer languages. With SQL, you describe the type of information you want. The computer then determines the best procedure to use to obtain it and runs that procedure. This is called a declarative computer language because the focus is on the result:  You specify what the result should look like. The computer is allowed to use any method of processing as long as it obtains the correct result.  Most other computer languages are procedural. These are languages like C, COBOL, Java, Assembler, FORTRAN, Visual Basic, and others. In these languages, you describe the procedure that will be applied to the data; you do not describe the result. The result is whatever emerges from applying the procedure to the data.  SQL is a nonprocedural language, in contrast to the procedural or third generation languages (3GLs) such as COBOL and C that had been created up to that time.  SQL describes what data to retrieve, delete, or insert, rather than how to perform the operation.  Two standards organizations, the American National Standards Institute (ANSI) and the International Standards Organization (ISO), currently promote SQL standards to industry. Notes about SQL  SQL is the designated language for getting information from a relational database.  SQL says what information to get, rather than how to get it.  Basic SQL is easy to learn.  SQL empowers people by giving them control over information.  SQL allows people to handle information in new ways.  SQL makes information powerful by bringing it to people when they need it.
  • 43. 35 What Can SQL do?  SQL can execute queries against a database  SQL can retrieve data from a database  SQL can insert records in a database  SQL can update records in a database  SQL can delete records from a database  SQL can create new databases  SQL can create new tables in a database  SQL can create stored procedures in a database  SQL can create views in a database  SQL can set permissions on tables, procedures, and views Data Manipulation Language (DML) Vs Data Definition Language (DDL) SQL can be divided into two parts:  Data Manipulation Language (DML)  Data Definition Language (DDL) Data Manipulation language (DML): is used to retrieve and manipulate data in a relational database. The query and update commands form the Data Manipulation Language (DML) parts of SQL are: SELECT: Extracts data from a database UPDATE: Updates data in a database DELETE: Deletes data from a database INSERT INTO: Inserts new data into a database Data Definition Language (DDL): A part of SQL permits database tables to be created or deleted. It also defines indexes (keys), specifies links between tables, and imposes constraints between tables. The most important DDL statements in SQL are:  CREATE DATABASE: Creates a new Database.  ALTER DATABASE: Modifies a Database.  DROP DATABASE: Deletes a Database.
  • 44. 36  CREATE TABLE : Creates a new Table  ALTER TABLE : Modifies a Table  DROP TABLE : Deletes a Table  CREATE INDEX: Creates an index (search key).  DROP INDEX : Deletes an index
  • 45. 37 LAB1: MS SQLServer:Database creation using Graphical User Interface of SQL Server Management Studio Objective:  To Show how to create a database and Tables using graphical user interface (GUI) in MS SQL Server 2012.  In MS SQL Server, two types of databases are available:  System databases  User Databases System Databases System databases are created automatically when we install MS SQL Server. The followings are system databases of Microsoft SQL Server:  Master  Model  MSDB  Tempdb  Resource (Introduced in 2005 version)  Distribution (It’s for Replication feature only) Table 2: System Databases Database Type Description Master System Database Stores system level information such as user accounts, configuration settings, and info on all other databases. Model System Database This database is used as a template for all other databases that are created. MSDB System Database Used by the SQL Server Agent for configuring alerts and scheduled jobs etc TEMPDB System Database Holds all temporary tables, temporary stored procedures, and any other temporary storage requirements generated by SQL Server.
  • 46. 38 1.1 How to Create Database in Microsoft SQL Server 2012 using SSMS 1. Open Microsoft SQL Management Studio 2. Connect to the database engine using database administrator credentials 3. Expand the server node 4. Right click Databases and select New Database 5 Name your database and click "OK":
  • 47. 39 1.2 Creating a Table 1. Ensuring you have the right database expanded, right click on the "Tables" icon and Click "New Table...“  While you have the above screen open, do the following: 1. Using the values in the screenshot; complete the details in the "Column Name", "Data Type" column "Length" and "Allow Nulls" fields. 2. Make the IndividualId column an "identity column", by setting "Is Identity" to "Yes" (this option is under the "Identity Specification" section in the bottom pane). Note that to set values in the bottom pane, you need to select the column name in the top pane first). This column is going to be an auto-number column - it will contain an incrementing number for each record that is created.
  • 48. 40 3. Save the table by clicking File > Save Table_1:
  • 49. 41 1.3 Editing Table Rows • We can use the "Edit Top 200 Rows" option to add data to our created table. • To use this option, right click on the table you wish to open, and select "Edit Top 200 Rows".
  • 50. 42 LAB 2: Starting writing SQL Statements using SQL Server Management Studio Command line Query Editor Objective:  To show the basics of Standard Query Language Syntaxes using SQL Server Management Studio. Data Types of SQL Server SQL Server supplies a set of system data tyes that define all the types of data that can be used with SQL Server. The Data types in SQL Server are organized into the following categories: 1. Exact numeric 2. Approximate numeric 3. Date and time 4. Character strings 5. Binary strings Table 3: Exact Numeric, Approximate Numeric and Date and Time Data types Data Type Storage Value Range Purpose bigint 8 bytes -2E63 to 2E63-1 Stores very large numbers that can be positive or negative. int 4 bytes -2E31 to 2E31 - 1 Stores whole numbers that can be positive and negatives. smallint 2 bytes -32,768 to 32,767 Stores whole numbers that can be positive and negatives. tinyint 1 bytes 0 to 255 Stores a small range of positive whole numbers.
  • 51. 43 decimal(p,s) 5-17 bytes depending on the precision -10E38 + 1 to -10E38 - 1 Stores decimal up to a maximum of 38 places. numeric (p,s) 5-17 bytes depending on the precision -10E38 + 1 to -10E38 - 1 Functionally equivalent to decimal, and can be used interchangeably with decimal. float(p) 4 0r 8 bytes -2.23E308 to 2.3E308 Stores large floating point numbers that exceed the capacity of decimal data type. real 4 bytes -3.4E38 to 3.4E38 Still valid, but replaced by float to meet the SQL-92 standard. money 8 bytes - 922,337,203,685,477,5808 to 922,337,203,685,477,5807 Stores large currency values. smallmoney 4 bytes -214,748.3648 to 214,748.3647 Stores small currency values datetime 8 bytes January 1, 1753, through December 31, 9999 within an accuracy of 3.33 milliseconds. Stores large date and time values. smalldatetime 4 bytes January 1, 1900, through June 6, 2079 within an accuracy of 1 minute. Stores a small range of date and time values.
  • 52. 44 Table 4: Character and string Data types Data type Storage Number of characters Purpose char(n) 1 up to 8,000 bytes Maximum of 8,000 characters ANSI data type that has fixed width. varchar(n) 1 up to 8,000 bytes Maximum of 8,000 characters ANSI data type that has fixed variable width. varchar(max) Up to 2 GB Maximum of 1,073,741,824 characters ANSI data type that has fixed variable width. text Up to 2 GB Maximum of 1,073,741,824 characters ANSI data type that has fixed variable width. nchar(n) 2 up to 8,000 bytes Maximum of 4000 characters Unicode data type that has fixed width. nvarchar(n) 2 up to 8,000 bytes Maximum of 4000 characters Unicode data type that has fixed variable width. nvarchar(max) Up to 2 GB Maximum of 1,073,741,824 characters Unicode data type that has fixed variable width. ntext Up to 2 GB Maximum of 536,870,912 characters Unicode data type that has fixed variable width. Table 5: Binary Data types Data type Storage Purpose binary(n) 1 up to 8,000 bytes Stores fixed size binary data varbinary(n) 1 up to 8,000 bytes Stores variable size binary data type. varbinary(max) Up to 2 GB Stores variable size binary data type. image Up to 2 GB Stores variable size binary data type.
  • 53. 45 2.1 Create Database Statement To start writing an SQL statement in your SQL Server Management Studio you have three options: 1. Go to the File menu and select New -> Query with current connection. 2. Click New Query from the quick access tool bar.
  • 54. 46 3. Press Ctrl + N keys from your keyboard. After you choose and apply either of the above three options you can start to write a query on the white area of the SQL Server Management Studio window as shown as below. Syntax: CREATE DATABASE database_name; Example: Create a database called University CREATE DATABASE University;
  • 55. 47 You have three options to execute your written Query: 1. Select the statement and go to Query menu and from the given drop down options select Execute. 2. Select your SQL statement and click Execute from the quick access toolbar. 3. Write click on the free space of your SQL editor and select execute from the given options.
  • 56. 48 After you executed the above SQL statement you have to see the message under your editor that says “Command(s) completed successfully.” Which means your University database is created successfully. Now you can find your new created Database which is named as University in Object Explorer window under Databases folder as shown as below.
  • 57. 49 2.2 Create Table Statement Before you going to write an SQL statement to create under in your University Databse first you have to check the current working available is University database or not and you also ave to change the current available working database is University. To check and set your working database as University follows the following steps:  Go to the quick access tool bar and check the available databases list or you can easily access it by pressing Ctrl+U from your keyboard.  As you see in the above figure the current database is master so to use the University database as a current working database drop down the available database list and select University.
  • 58. 50 Syntax: CREATE TABLE table_name; (field1 datatype , field2 datatype, field3 datatype); Example: Using SQL Server Create the following tables under the University Database 1. Department (dno,dname) 2. Student (idNo, fname, lname, age, sex, dnumber) Solution: CREATE TABLE Department ( DeptId int not null, DeptName varchar(15) not null ); CREATE TABLE Student ( idNo varchar(10) not null, FName varchar(15),LName varchar(15), Age int , Sex char(1), DeptId int );  After you write and execute the above SQL statement your Department and Student tables are successfully created under University Database.
  • 59. 51 SQL Alter Table Syntax To add a column in a table, use the following Syntax: ALTER TABLE table_name ADD column_name datatype Example: ALTER TABLE Student ADD GPA float; Changing the Data type of a column in a Relational Database To change the data type of a column in a table, use the following Syntax: SQL Server / MS Access: ALTER TABLE table_name ALTER COLUMN column_name datatype Example: ALTER TABLE Student ALTER COLUMN Sex varchar(6)
  • 60. 52 LAB 3: Implementing Constraints Objectives:  To show how to create constraints in MS SQL server 2012  To show how the relational model supports well defined theory of constraints on attributes or tables. 3.1 Primary Key Constraints 3.1.1 Adding a primary key while creating a Table Example: CREATE DATABASE HumanResource; CREATE TABLE Department. ( DeptId int IDENTITY(1,1) PRIMARY KEY, DeptName varchar(50) NOT NULL ) 3.1.2 Adding a primary key after a Table is created This section shows how to add a primary key to a table, even after the table is created. Syntax: ALTER TABLE table_name ADD CONSTRAINT name_of_the_constraint PRIMARY KEY (list_of_columns_in_the_primary_key); Remark: In SQL Server, the column to be used as a Primary key should defined as NOT NULL. Example: Changing the primary key of a table Department under the University Database. Use University Alter table Department add constraint pk primary key (DeptId);
  • 61. 53 Dropping a primary key constraint Example 1: Alter table department drop constraint pk DeptId; Example 2: Not using the name of the constraint to drop it. alter table department drop primary key; 3.2 Foreign Key Constraints Example: Use HumanResource Create table Employee ( EmpId int primary key, Name nvarchar(15), City varchar(25), DeptId int references Department(DeptId) on update cascade on delete cascade ) OR Use Human Resource Create table Managers ( ManId int primary key, Name nvarchar(15), DeptId int null foreign key (DeptID) references Department(DeptID) on update cascade on delete cascade ) OR Create table Employee ( EMPId int not null, Name nvarchar(15), DeptId int null , City varchar(25), primary key(EmpID),
  • 62. 54 CONSTRAIN fk foreign key(DeptId) references Department(DeptId) ) 3.2.1 SQL FOREIGN KEY Constraint on ALTER TABLE Use University ALTER TABLE Student ADD FOREIGN KEY (DeptId) REFERENCES Department(DeptId) OR Use University ALTER TABLE Student ADD CONSTRAINT fk FOREIGN KEY (DeptId) REFERENCES Department(DeptId) DROP ING a FOREIGN KEY Constraint Use University ALTER TABLE Student DROP CONSTRAINT fk
  • 63. 55 Lab 4: Default Constraints Objective:  To Practice how to use Default constraints in MS SQL server. SQL DEFAULT Constraint:  The DEFAULT constraint is used to insert a default value into a column.  The default value will be added to all new records, if no other value is specified. 4.1 SQL DEFAULT Constraint on CREATE TABLE Now you are expected to know how to create a database and tables so create a database you want which is determined by a table “Persons” and practice Default constraints using the following SQL statements.  A DEFAULT constraint on the "City" column when the "Persons" table is created: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(35) NOT NULL,MiddleName varchar (35) FirstName varchar(35), Address varchar(75), City varchar(25) DEFAULT ‘Addis Ababa' ) 4.2 SQL DEFAULT Constraint on ALTER TABLE To create a DEFAULT constraint on the "City" column when the table is already created, use the following SQL: SQL Server / MS Access: Syntax: ALTER TABLE Table_Name ADD CONSTRAINT DF_SomeDFCName DEFAULT 'Some_Name' FOR Column_Name;
  • 64. 56 Examples: ALTER TABLE Persons ALTER COLUMN City SET DEFAULT 'Adama’ OR Use Human Resource ALTER TABLE Employee ADD CONSTRAINT DF_CityName DEFAULT 'Addis Ababa' FOR City; 4.3 DROP a DEFAULT Constraint • To drop a DEFAULT constraint, use the following SQL: SQL Server / Oracle / MS Access: ALTER TABLE Persons ALTER COLUMN City DROP DEFAULT OR ALTER TABLE Persons DROP CONSTRAINT defaultContsraintName;
  • 65. 57 Lab 5: SQL CHECK Constraint Objective:  Practice CHECK constraint in SQL Server 2012 Relational Database. The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a single column it allows only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row. 5.1 SQL CHECK Constraint on CREATE TABLE The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is created. The CHECK constraint specifies that the column "PId" must only include integers greater than 0. The following SQL statement can be used in Oracle and MS Access in addition to SQL Server: CREATE TABLE Persons ( P_Id int NOT NULL CHECK (P_Id>0), LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar (255), City varchar (255) )  To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL Syntax: MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Addis Ababa') )
  • 66. 58 To create a CHECK constraint on the "PId" column when the table is already created, use the following SQL statement:  MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CHECK (P_Id>0)  To know about how to allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, look the following example: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Addis Ababa') 5.2 DROPING a CHECK Constraint To drop a CHECK constraint, use the following SQL:  SQL Server / Oracle / MS Access: ALTER TABLE Persons DROP CONSTRAINT chk_Person
  • 67. 59 LAB 6: SQL Create Index Statement Objective:  To practice an INDEX statement in SQL Server 2012 Relational Database. The CREATE INDEX statement is used to create indexes in tables. Indexes allow the database application to find data fast; without reading the whole table. Indexes:  An index can be created in a table to find data more quickly and efficiently.  The users cannot see the indexes; they are just used to speed up searches/queries.  Duplicate values are allowed except in unique index: Note: You should only create indexes on columns (and tables) that will be frequently searched against. 6.1 Create an Index Syntax: CREATE INDEX index_name ON table_name (column_name) SQL CREATE UNIQUE INDEX  When a unique index is created on a table, Duplicate values are not allowed. Syntax: CREATE UNIQUE INDEX index_name ON table_name (column_name) Note: The syntax for creating index is varies among different databases. Therefore: Check the syntax for creating indexes in your database.
  • 68. 60 Example: The SQL statement below creates an index named "PIndex" on the "LastName" column in the "Persons" table: CREATE INDEX PIndex ON Persons (LastName) If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas: CREATE INDEX PIndex ON Persons (LastName, FirstName)
  • 69. 61 LAB 7: SQL Drop statements of COLUMN, INDEX, TABLE and DATABASE Objective:  To practice drop statements in SQL Server 2012. A drop statement is used to remove a Column, Table and an entire database when each of them is needed to be deleted respectively. 7.1 Dropping an existing column To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column): ALTER TABLE table_name DROP COLUMN column_name Examples: alter table department drop column sex ALTER TABLE Persons DROP COLUMN Sex 7.2 The DROP INDEX Statement Indexes, tables, and databases can be easily deleted/removed with the DROP statement The DROP INDEX statement is used to delete an index in a table.  DROP INDEX Syntax for MS Access: DROP INDEX index_name ON table_name  DROP INDEX Syntax for MS SQL Server: DROP INDEX table_name.index_name
  • 70. 62 7.3 The DROP TABLE Statement • The DROP TABLE statement is used to delete a table. Syntax: DROP TABLE table_name 7.4 The TRUNCATE TABLE Statement What if we only want to delete the data inside the table, and not the table itself? Then, use the TRUNCATE TABLE statement: Syntax: TRUNCATE TABLE table_name Example: TRUNCATE TABLE Persons
  • 71. 63 LAB 8: Data Manipulation Language (DML) Objectives:  Inserting Records (INSERT SQL Command)  Updating Records (UPDATE SQL Command)  Deleting Records (DELETE Command)  The SELECT statement 8.1 Inserting Records (INSERT SQL Command) Syntax: USE database_name INSERT INTO tablename [(first_column,...,last_column)] VALUES (first_value,...,last_value) Example: • Option 1: USE University INSERT INTO Student (StudID, FirstName, LastName, Sex) VALUES ('AB101', 'Abebe', 'Kebede', 'Male') • Option 2: USE University INSERT INTO Student VALUES ('AB101', 'Abebe', 'Kebede', 'Male')  Option 3: USE University INSERT INTO Student (Sex, FirstName, LastName, StudID) VALUES ('Male', 'Abebe', 'Kebede', 'AB101')
  • 72. 64 8.2 Updating Records (UPDATE SQL Command) Syntax: USE database_name UPDATE tablename SET columnname = “newvalue" ["nextcolumn" = “newvalue2"...] WHERE columnname OPERATOR value [AND|OR columname OPERATOR value] Example: USE University UPDATE Student SET FirstName = 'Almaz', Sex = 'Female' WHERE FirstName = 'Abebe' AND Sex = 'Male' 8.3 Deleting Records (DELETE Command) SYNTAX: USE database_name DELETE [FROM] table_name [WHERE search_condition] Example: USE University DELETE FROM Student WHERE FirstName = 'Almaz' AND Sex = 'Female'  In the Above example you can use “Delete Student” instead of “Delete From Student” keyword.
  • 73. 65 LAB 9: Selecting Data from the Database Tables Objectives:  To show how to retrieve the selected data’s from a Database. Before starting looking the process of selecting data from databases, first you have to download the sample AdventureWorksLT2012 Database (Zip file) from: https://msftdbprodsamples.codeplex.com/releases/view/93587 then extract and add it in to your SQL server 2012 Database lists.
  • 74. 66 Attaching AdventureWorks Sample Database in to the SQL Server 2012R2 1. Go to the directory : C:Program FilesMicrosoft SQLServerMSSQL11.MSSQLSERVERMSSQLDATA and copy the AdventureWorks2012_Data.mdf file. 2. Go to the Microsoft SQL Server Management Studio -> right click on Databases and select attach option from the given lists.
  • 75. 67 3. In the popup attach databases window click the Add button.
  • 77. 69 5. Under “AdventureWorks LT2012” database details select the log file type then click Remove button and finally Click OK.
  • 78. 70 6. Now you can find your AdventureWorksLT2012 database under the databases folder in your Microsoft SQL Server Management Studio.
  • 79. 71 Syntax of selecting data from SQL server 2012 Databases: USE database_name SELECT [ALL | DISTINCT] column1 [, column2] FROM table1 [, table2] [WHERE conditions] [GROUP BY column-list] [HAVING conditions] [ORDER BY column-list [ASC | DESC] ] Example 1: use AdventureWorksLT2012 SELECT * FROM SalesLT.Customer use AdventureWorksLT2012 SELECT FROM SalesLT.Customer use AdventureWorksLT2012 SELECT FirstName,LastName,EmailAddress FROM SalesLT.Customer use AdventureWorksLT2012 SELECT FirstName + ' ' + LastName AS FULLNAME,EmailAddress FROM SalesLT.Customer  Comparison Operators used in the WHERE clause are the following: = Equal > Greater than < Less than >= Greater than or equal <= Less than or equal <> or! = Not equal to Examples 2: Use AdventureWorksLT2012 SELECT FirstName,LastName,EmailAddress FROM SalesLT.Customer WHERE LastName='Vargas'
  • 80. 72 Example 3: Use AdventureWorksLT2012 SELECT FirstName,LastName,EmailAddress FROM SalesLT.Customer WHERE CustomerID=600 Example 4: Use AdventureWorksLT2012 SELECT FirstName,LastName,EmailAddress FROM SalesLT.Customer WHERE CustomerID > 600 Example 5: use AdventureWorksLT2012 SELECT FirstName,LastName,EmailAddress FROM SalesLT.Customer WHERE CustomerID > 600 AND CustomerID < =800 Example 6: use AdventureWorksLT2012 SELECT CustomerID,FirstName,LastName,EmailAddress FROM SalesLT.Customer WHERE CustomerID BETWEEN 600 AND 800
  • 81. 73 Order By clause Syntax: SELECT column1, column2 FROM list-of-tables ORDER BY column-list [ASC | DESC]; Example 1: Use AdventureWorksLT2012 SELECT CustomerID, FirstName, MiddleName, LastName, EmailAddress, CompanyName FROM SalesLT.Customer where MiddleName IS NOT NULL ORDER BY FirstName Example 2: Use AdventureWorksLT2012 SELECT ProductID,Name,Color,ListPrice FROM SalesLT.Product ORDER BY ListPrice Example 3: Use AdventureWorksLT2012 SELECT ProductID,Name,Color,ListPrice FROM SalesLT.Product ORDER BY ListPrice DESC Example 4: Use AdventureWorksLT2012 SELECT ProductID,Name,Color,ListPrice FROM SalesLT.Product WHERE Color is NOT NULL ORDER BY Color,ListPrice DESC
  • 82. 74 LAB 10: IN, NOTIN, LIKE and ISNULL Keywords Objective:  Practice the IN, NOTIN, LIKE and ISNULL keywords of SQL in MS SQL Server 2012. 10.1 The use of IN keyword Example 1: Use AdventureWorksLT2012 SELECT CustomerID,FirstName,LastName,EmailAddress FROM SalesLT.Customer WHERE CustomerID IN ( 600, 700,500,533,800) Example 2: Use AdventureWorksLT2012 SELECT CustomerID,FirstName,LastName,EmailAddress FROM SalesLT.Customer WHERE LastName IN ('Tian','Clark','Harding') 10.2 The use of NOT IN keyword Example: Use AdventureWorksLT2012 SELECT CustomerID,FirstName,LastName,EmailAddress FROM SalesLT.Customer WHERE CustomerID NOT IN (600, 700,500,533,800)
  • 83. 75 10.3 The use of LIKE keyword Example: Use AdventureWorksLT2012 SELECT CustomerID,FirstName,LastName,EmailAddress , CompanyName FROM SalesLT.Customer WHERE CompanyName LIKE 'Metro%' SELECT CustomerID,FirstName,LastName,EmailAddress ,CompanyName FROM SalesLT.Customer WHERE CompanyName LIKE „%Metro%' SELECT CustomerID,FirstName,LastName,EmailAddress , CompanyName FROM SalesLT.Customer WHERE CompanyName LIKE „%_etro%' 10.4 IS NULL Keyword Example: Use AdventureWorksLT2012 SELECT CustomerID, FirstName, MiddleName, LastName, EmailAddress, CompanyName FROM SalesLT.Customer where MiddleName IS NULL Exercises: 1. List all the item numbers along with their order date that are Purchased by a customer whose customerid is 10101, From the items_ordered table Solution: SELECT itemno, ordered_date FROM items_ordered WHERE customerid= 10101
  • 84. 76 2. List the records of all employees whose name beginning with the letter ‘A’ from empinfo Table. Solution: SELECT * FROM empInfo WHERE FirstName like „A%‟;
  • 85. 77 LAB 11: Aggregate functions Objective:  Practice aggregate functions in SQL Server 2012.  Aggregate functions are used to summarize the results of a particular column. These are: MIN(), MAX(), SUM(), AVG() and COUNT() 11.1 Count function Example: Select count(*) as TotalProducts from SalesLT.Product OR Select count(ProductID) from SalesLT.Product select count(*) From SalesLT.Product where Color='Red' LAB 11.2 MAX and MIN functions Select MAX(ListPrice) from SalesLT.Product select MIN(ListPrice) from SalesLT.Product Select MAX(ListPrice) As MaxPrice,MIN(ListPrice) AS MinPrice ,AVG(ListPrice) As AveragePrice from SalesLT.Product 11.3 Average function Example: Select AVG(ListPrice) from SalesLT.Product 11.4 The SUM function Select SUM (TotalDue) From SalesLT.SalesOrderHeader
  • 86. 78 LAB 12: Group by clause Objective:  To show how to collaborate with SELECT statement to arrange identical data into groups. The GROUP BY clause will gather all of the rows together that contain data in the specified column(s) and will allow aggregate functions to be performed on the one or more columns. GROUP BY clause Syntax: SELECT column1[, column2, etc] FROM list-of-tables GROUP BY "column-list"; Example: Select Color,count(*) from SalesLT.Product group by Color 12.1 Having clause Similar to where condition except that HAVING is used with group of records instead of single records. Example 1: Show all the average salaries of departments that are greater than 1200 SELECT dept, AVG (salary) FROM employee GROUP BY dept HAVING AVG (salary) > 1200;
  • 87. 79 Example 2: Select Color,count(*) from SalesLT.Product group by Color having Color is not null Exercises: 1. Display the sum of the salaries of all employees from empInfo Table Solution: SELECT SUM (salary) as TotalSalary FROM empInfo 2. Using empInfo Table, display the max, min, and average salary. Solution: SELECT MAX(salary) as Max , MIN(salary) as Min , AVG(salary) as Average FROM empInfo 3. Display the number of available records in empInfo Table. Solution: SELECT COUNT(*) as count FROM empInfo 4. Using empInfo table, display the number of employees under each department. Solution: SELECT dept, COUNT(*) as count FROM empInfo GROUP BY dept 5. Using empInfo Table, display the Max and Min salaries of employees for each department. Solution: SELECT dept, MAX (salary) as Max, MIN (salary) as Min FROM empInfo GROUP BY dept
  • 88. 80 6. List the records of all employees sorted by First Name then by Last Name in descending order. Solution: SELECT * FROM empInfo ORDER BY FirstName, LastName DESC 12.2 Combining conditions and Boolean Operators The following two keywords are used to combine conditions. 1. AND 3. OR Syntax: SELECT column1 [, column2] FROM list-of-tables WHERE condition1 AND condition2; Example: SELECT EmpID, firstname, lastname, city, salary FROM EmpInfo WHERE salary >= 500.00 AND city = 'A/A' 12.3 The use of DISTINCT Keyword Example: SELECT DISTINCT CountryRegion FROM SalesLT.Address SELECT count(DISTINCT StateProvince) FROM SalesLT.Address
  • 89. 81 LAB 13: Tables Join Objective:  To show how to implement the combination of columns from one or more tables in a Relational Database. Syntax: SELECT list-of-columns FROM table1, table2 WHERE search-condition(s) 13.1 Joining Two Tables Example: Select a.Name, Color, a.ProductCategoryID, b.Name from SalesLT.Product a, SalesLT.ProductCategory b where a.ProductCategoryID=b.ProductCategoryID 13.2 INNER JOIN Example: Select a.Name,Color,a.ProductCategoryID ,b.Name From SalesLT.Product a INNER JOIN SalesLT.ProductCategory b ON a.ProductCategoryID=b.ProductCategoryID 13.3 OUTER JOIN Example: select a.Name,Color,a.ProductCategoryID,b.ProductCategoryID,b.Name from SalesLT.Product a RIGHT OUTER JOIN SalesLT.ProductCategory b ON a.ProductCategoryID=b.ProductCategoryID
  • 90. 82 13.4 Sub Query Example: SELECT FirstName,LastName,CompanyName FROM SalesLT.Customer WHERE CustomerID = (select TOP 1 CustomerID FROM SalesLT.SalesOrderHeader ORDER BY TotalDue DESC ) Exercise Find those Customers who did not place any order? Solution: SELECT FirstName,LastName,CompanyName FROM SalesLT.Customer WHERE CustomerID NOT IN (SELECT DISTINCT CustomerID FROM SalesLT.SalesOrderHeader ) Exercise: Display all customers who have ordered item1 Solution: SELECT c.customerid,FirstName, LastName FROM customers c, oredered_items o Where c.customerid = o.custpmerid
  • 91. 83 LAB 14: View Objective:  To show how to implement Views of a Database. A view is nothing more than a SQL statement that is stored in the database with an associated name. A view is actually a composition of a table in the form of a predefined SQL query. It can contain all rows of a table or select rows from a table. A view can be created from one or many tables which depend on the written SQL query to create a view. Views, which are kind of virtual tables, allow users to do the following: • Restrict access to the data such that a user can see and (sometimes) modify exactly what they need and no more. • · Summarize data from various tables which can be used to generate reports. 14.1 Creating Views • Database views are created using the CREATE VIEW statement. Views can be created from a single table, multiple tables, or another view. • To create a view, a user must have the appropriate system privilege according to the specific implementation. Syntax: CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name WHERE [condition]; • You can include multiple tables in your SELECT statement in very similar way as you use them in normal SQL SELECT query. • Consider the CUSTOMERS table having the following records: | ID | NAME | AGE | ADDRESS | SALARY • Now, following is the example to create a view from CUSTOMERS table. This view would be used to have customer name and age from CUSTOMERS table:
  • 92. 84 CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM CUSTOMERS; • Now, you can query CUSTOMERS_VIEW in similar way as you query an actual table. SQL > SELECT * FROM CUSTOMERS_VIEW WITH CHECK OPTION: • The WITH CHECK OPTION is a CREATE VIEW statement option. • The purpose of the WITH CHECK OPTION is to ensure that all UPDATEs and INSERTs satisfy the condition(s) in the view definition. • If they do not satisfy the condition(s), the UPDATE or INSERT returns an error. CHECK OPTION: Example: CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM CUSTOMERS WHERE age IS NOT NULL WITH CHECK OPTION;  In the above case The WITH CHECK OPTION should deny the entry of any NULL values in the view's AGE column, because the view is defined by data that does not have a NULL value in the AGE column.
  • 93. 85 14. 2 Updating a View  A view can be updated under certain conditions:  The SELECT clause may not contain the keyword DISTINCT.  The SELECT clause may not contain summary functions.  The SELECT clause may not contain set operators.  The SELECT clause may not contain an ORDER BY clause.  The FROM clause may not contain multiple tables.  The WHERE clause may not contain subqueries.  The query may not contain GROUP BY or HAVING.  Calculated columns may not be updated.  All NOT NULL columns from the base table must be included in the view in order for the INSERT query to function.  So if a view satisfies all the above mentioned rules then you can update a view. The Following is an example to update the age of Ramesh: UPDATE CUSTOMERS_VIEW SET AGE = 35 WHERE name='Ramesh'; 14.3 Inserting Rows in a View  Rows of data can be inserted into a view. The same rules that apply to the UPDATE command also apply to the INSERT command.  Here, we can’t insert rows in CUSTOMERS_VIEW because we have not included all the NOT NULL columns in this view, otherwise you can insert rows in a view in similar way as you insert them in a table.
  • 94. 86 14. 4 Deleting Rows in a View Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT commands apply to the DELETE command. The Following is an example to delete a record having AGE= 22. DELETE FROM CUSTOMERS_VIEW WHERE age = 22; 14. 5 Dropping Views: Obviously, where you have a view, you need a way to drop the view if it is no longer needed. The syntax is very simple as given below: DROP VIEW view_name; The Following is an example to drop CUSTOMERS_VIEW from CUSTOMERS table: DROP VIEW CUSTOMERS_VIEW;
  • 95. 87 References: 1. Tutorials: MSDN – Microsoft. (https://msdn.microsoft.com/enus/library/ms167593(v=sql.105).aspx) 2. Tutorials for SQL Server Microsoft Docs. (https://msdn.microsoft.com/library/ms167593.aspx) 3. MS SQL Server Tutorial. (https://www.tutorialspoint.com/ms_sql_server/) 4. SQL Server Tutorial. (https://www.techonthenet.com/sql_server/index.php) 5. Elmasri and Navathe: Fundamentals of Database Systems, 7th Ed.