0% found this document useful (0 votes)
8 views

Database Lab Manual

The document provides a comprehensive guide on installing and using SQL Server 2019, including downloading the setup, installation steps, and connecting to the SQL Server Database Engine. It also covers SQL fundamentals such as SQL functionalities, data definition and manipulation languages, and how to create and manage databases and tables. Additionally, it explains SQL commands for data retrieval and manipulation, along with examples for clarity.

Uploaded by

forthpyramid111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Database Lab Manual

The document provides a comprehensive guide on installing and using SQL Server 2019, including downloading the setup, installation steps, and connecting to the SQL Server Database Engine. It also covers SQL fundamentals such as SQL functionalities, data definition and manipulation languages, and how to create and manage databases and tables. Additionally, it explains SQL commands for data retrieval and manipulation, along with examples for clarity.

Uploaded by

forthpyramid111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Chapter 1: SQL Server 2019 Installation

1.1 SQL Server Definition


SQL Server is a relational database management system (RDBMS) developed by
Microsoft. SQL Server supports ANSI SQL, which is the standard Structured
Query Language. However, SQL Server comes with its implementation of the
SQL language, T-SQL (Transact-SQL). It is primarily designed and developed to
compete with MySQL and Oracle databases.

1.2 How to download SQL Server Setup


Below is a step by step process on how to download SQL in Windows 10:

Step 1: Go to URL: https://www.microsoft.com/en-in/sql-server/sql-server-


downloads for Microsoft SQL server download

Microsoft provides two specialized free SQL download editions to work on


MS SQL server:

1. Developer – It has all feature which MS SQL server offers but we cannot
use it in production. From the learning perspective, is it an ideal candidate
to start.
2. Express: This is also a free SQL server download version but with the
limited set of features with no business intelligence applications.

We will select the Developer edition MS SQL server download for installation.

Step 2: Click on “Download now”


We will get SQL server installation set up as ‘SQL2019-SSEI-Dev.exe’.

1.3 How to Install SQL Server


Here is a step-by-step process on how to install SQL in Windows 10:
Step 1: Open the .exe file
Double click on “SQL2019-SSEI-Dev.exe”. Below screen will appear with
three options: Basic, Custom and Download files:
 Basic option – It installs only the essential features of SQL Server. It only asks
for the License agreement and installation path.
 Custom option – It allows you to choose the features you want to install.
 Download Media option – It allows you to download all the installations to a
local folder. You install the SQL Server 2019 later without the Internet.
Step 2: Choose the version
Choose the basic version by clicking on the ‘Basic’ option, as it has all default
configuration required to learn MS SQL.
Step 3: Accept the terms
‘Microsoft Server License Terms’ screen will appear. Read the License Terms
and then click ‘Accept.’
Step 4: Choose the location
Next, you need to specify the SQL Server 2019 install location by click
the Browse option. After choosing the path, you need to click Install.
Step 4) Then, it will start to download install package. Once the download is
successful, the installation process will begin.
Step 6: After installing SQL Server 2019, you can start to use it. You can also
choose Connect Now or Install SSMS into your system.

1.4 Install SSMS

1. On the SQL Server 2019 completion screen, click Install SSMS.


2. On the download page, scroll down and click on Download SQL Server
Management Studio (SSMS).

3. Double click the SSMS-Setup-ENU.exe executable from your download


location.
4. The default download location is indicated. To select a different location,
click the Change button.

Click Install.
5. Once SSMS is successfully installed, click Restart.
1.5 Connect to SQL Server Database Engine
1. Click Start and search Microsoft SQL Server Management Studio
or SSMS.
2. From the Object Explorer panel on the left, click Connect.
3. In the Connect to Server dialog box, click Connect with the
default server values.

In this case, Server name is your machine name.


4. You are now connected to MS SQL system database as indicated
with a green arrow in the screenshot.
Chapter 2: Introduction to SQL Server

2.1 SQL Introduction

 SQL (Structured Query Language) is a database computer language


designed for managing data in relational database management systems
(RDBMS).
 SQL is a standardized computer language that was originally developed by
IBM for querying, altering and defining relational databases, using
declarative statements.

2.2 SQL Functionalities


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

2.3 DBMDs
There are lots of different database systems, or DBMS – Database Management
Systems,
such as:
 Microsoft SQL Server
 Oracle
 MySQL
 Microsoft Access
 IBM DB2
 Sybase

2.4 Data Definition Language (DDL)


The Data Definition Language (DDL) manages table and index structure. The
most basic
items of DDL are the CREATE, ALTER, RENAME and DROP statements:
 CREATE creates an object (a table, for example) in the database.
 DROP deletes an object in the database, usually irretrievably.
 ALTER modifies the structure an existing object in various ways—for
example, adding a column to an existing table.

2.5 Data Manipulation Language (DML)


The Data Manipulation Language (DML) is the subset of SQL used to add, update
and delete data. The acronym CRUD refers to all of the major functions that need
to be implemented in a relational database application to consider it complete.
Each letter in the acronym can be mapped to a standard SQL statement:
Operation SQL Description
Create INSERT INTO inserts new data into a database
Read (Retrieve) SELECT extracts data from a database
Update UPDATE updates data in a database
Delete (Destroy) DELETE deletes data from a database
Chapter 3: Create Database and Drop Database
3.1 SQL Server – Create Database
Database is a collection of objects such as table, view, stored procedure, function,
trigger, etc.
In MS SQL Server, two types of databases are available.
 System databases
 User Databases
3.1.1 System Databases
System databases are created automatically when we install MS SQL Server.
Following is a list of system databases:
 Master
 Model
 MSDB
 Tempdb
3.1.2 User Databases
User databases are created by users (Administrators, developers, and testers who
have access to create databases). Following methods are used to create user
database.
Method 1 – Using T-SQL Script
Following is the basic syntax for creating database in MS SQL Server.

Example:
To create database called ‘Testdb’, run the following query.

Method 2 – Using SQL Server Management Studio


Connect to SQL Server instance and right-click on the databases folder. Click on
new database and the following screen will appear.
Enter the database name field with your database name (example: to create
database with the name ‘Testdb’) and click OK. Testdb database will be created
as shown in the following snapshot.
3.2 SQL Server – Drop Database
To remove your database from MS SQL Server, use drop database command.
Following two methods can be used for this purpose.
Method 1 – Using T-SQL Script
Following is the basic syntax for removing database from MS SQL Server.

Example :
To remove database name ‘Testdb’, run the following query.

Method 2 – Using MS SQL Server Management Studio


Connect to SQL Server and right-click the database you want to remove. Click
delete command and the following screen will appear.
Click OK to remove the database (in this example, the name is Testdb as shown
in the above screen) from MS SQL Server.
Chapter 4: Tables

4.1 Create table


To create a table from MS SQL Server, use Create table command. Following
two methods can be used for this purpose.
Method 1 – Using T-SQL Script
The CREATE TABLE statement is used to create a table in a database.

Syntax:

The data type specifies what type of data the column can hold.

You have special data types for numbers, text dates, etc.
Examples:
• Numbers: int, float
• Text/Stings: varchar(X) – where X is the length of the string
• Dates: datetime
• etc.
Example:

We want to create a table called “INSTRUCTOR” which has the following


columns and data types:
Method 2 – Using MS SQL Server Management Studio
Click on "UNIVERSITY" database and Select “New Table …”:

Next, the table designer pops up where you can add columns, data types, etc.

In this designer we may also specify Column Names, Data Types, etc. Finally,
Save the table by clicking the Save button.
4.2 ALTER TABLE
The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.
To add a column in a table, use the following syntax:

To delete a column in a table, use the following syntax:

To change the data type of a column in a table, use the following syntax:

4.3 SQL Constraints


Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE
statement) or after the table is created (with the ALTER TABLE statement).
Here are the most important constraints:
• PRIMARY KEY
• NOT NULL
• UNIQUE
• FOREIGN KEY
• CHECK
• DEFAULT
• IDENTITY
In the sections below we will explain some of these in detail.
4.3.1 PRIMARY KEY
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values. It is normal to just use running
numbers, like 1, 2, 3, 4, 5, … as values in Primary Key column. Each table should
have a primary key, and each table can have only ONE primary key.
You can easily set the primary Key in a table just by right-click and select “Set
primary Key”.

The primary Key column will then have a small key in front to illustrate that
this column is a Primary Key.

4.3.2 NOT NULL / Required Columns


The NOT NULL constraint enforces a column to NOT accept NULL values. The
NOT NULL constraint enforces a field to always contain a value. This means that
you cannot insert a new record, or update a record without adding a value to this
field.
Chapter 4: Data Manipulation
5.1 INSERT INTO
The INSERT INTO statement is used to insert a new row in a table.

Example:

5.2 UPDATE
The UPDATE statement is used to update existing records in a table.
The syntax is as follows:

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause
specifies which record or records that should be updated. If you omit the
WHERE clause, all records will be updated!

Example:

5.3 DELETE
The DELETE statement is used to delete rows in a table.
Syntax:
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause
specifies which record or records that should be deleted. If you omit the WHERE
clause, all records will be deleted!

Example:

Question 1:
Consider the following UNIVERSITY schema, where the primary keys are
underlined
a. create a database using SQL Server DBMS:

classroom(building, room number, capacity)


department(dept name, building, budget)
course(course id, title, dept name, credits)
instructor(ID, name, dept name, salary)
section(course id, sec id, semester, year, building, room number, time slot id)
teaches(ID, course id, sec id, semester, year)
student(ID, name, dept name, tot cred)
takes(ID, course id, sec id, semester, year, grade)
advisor(s ID, i ID)
time slot(time slot id, day, start time, end time)
prereq(course id, prereq id)

Solution:
create table classroom

(building varchar (15),


room number varchar (7),
capacity numeric (4,0),
primary key (building, room number));
create table department
(dept name varchar (20),
building varchar (15),
budget numeric (12,2) check (budget > 0),
primary key (dept name));

create table course


(course id varchar (8),
title varchar (50),
dept name varchar (20),
credits numeric (2,0) check (credits > 0),
primary key (course id),
foreign key (dept name) references department
on delete set null);

create table instructor


(ID varchar (5),
name varchar (20) not null,
dept name varchar (20),
salary numeric (8,2) check (salary > 29000),
primary key (ID),
foreign key (dept name) references department
on delete set null);

create table section


(course id varchar (8),
sec id varchar (8),
semester varchar (6) check (semester in
(’Fall’, ’Winter’, ’Spring’, ’Summer’)),
year numeric (4,0) check (year > 1701 and year < 2100),
building varchar (15),
room number varchar (7),
time slot id varchar (4),
primary key (course id, sec id, semester, year),
foreign key (course id) references course
on delete cascade,
foreign key (building, room number) references classroom
on delete set null);

b. Provide sample data for each of the relations defined in the previous section.
Chapter 6: SELECT Statement

6.1 The SQL SELECT Statement


The SELECT statement is probably the most used SQL command. The SELECT
statement is used for retrieving rows from the database and enables the selection
of one or many rows or columns from one or many tables in the database. The
data returned is stored in a result table, called the result-set.
So, in the simplest form we can use the SELECT statement as follows:

If we want all columns, we use the symbol “*”

Below is a schema of the "Customers" table in the Northwind sample database:


Customers(CustomerID, CustomerName, ContactName, Address, City,
PostalCode, Country)

Example 1:
selects the "CustomerName" and "City" columns from the "Customers" table

Example 2:
Selects all the columns from the "Customers" table

6.2 The SQL SELECT DISTINCT Statement


The SELECT DISTINCT statement is used to return only distinct (different)
values. Inside a table, a column often contains many duplicate values; and
sometimes you only want to list the different (distinct) values.

Syntax:
The following SQL statement selects all (including the duplicates) values from
the "Country" column in the "Customers" table.

The following SQL statement selects only the DISTINCT values from the
"Country" column in the "Customers" table:

6.3 The SQL WHERE Clause

The WHERE clause is used to filter records. It is used to extract only those records
that fulfill a specified condition.

Syntax:

Example:
Selects all the customers from the country "Mexico", in the "Customers" table

The following operators can be used in the WHERE clause:


operator description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal
Between Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values for a column

6.4 The SQL AND, OR and NOT Operators

The WHERE clause can be combined with AND, OR, and NOT operators.

The AND and OR operators are used to filter records based on more than one
condition:

 The AND operator displays a record if all the conditions separated


by AND are TRUE.
 The OR operator displays a record if any of the conditions separated
by OR is TRUE.

The NOT operator displays a record if the condition(s) is NOT TRUE.

AND Syntax

OR Syntax

NOT Syntax

AND Example
selects all fields from "Customers" where country is "Germany" AND city is
"Berlin"

OR Example
selects all fields from "Customers" where city is "Berlin" OR "München"

Example
selects all fields from "Customers" where country is "Germany" OR "Spain"

NOT Example
selects all fields from "Customers" where country is NOT "Germany"

You can also combine the AND, OR and NOT operators.

Example:
selects all fields from "Customers" where country is "Germany" AND city must
be "Berlin" OR "München"

Example:
selects all fields from "Customers" where country is NOT "Germany" and NOT
"USA"
6.5 SQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set in ascending or descending


order. The ORDER BY keyword sorts the records in ascending order by default.
To sort the records in descending order, use the DESC keyword.

Syntax:

Example:
selects all customers from the "Customers" table, sorted by the "Country" column

Example :
selects all customers from the "Customers" table, sorted DESCENDING by the
"Country" column

Example:
selects all customers from the "Customers" table, sorted by the "Country" and the
"CustomerName" column. This means that it orders by Country, but if some rows
have the same Country, it orders them by CustomerName.
Example:
selects all customers from the "Customers" table, sorted ascending by the
"Country" and descending by the "CustomerName" column
Chapter 7: SQL Joins

7.1 SQL JOIN

A JOIN clause is used to combine rows from two or more tables, based on a
related column between them. There are the different types of the JOINs in SQL
as followed:

 INNER JOIN: returns records that have matching values in both tables.
 LEFT OUTER JOIN: returns all records from the left table, and the
matched records from the right table.
 RIGHT OUTER JOIN: returns all records from the right table, and the
matched records from the left table.
 FULL OUTER JOIN: returns all records when there is a match in either left
or right table.

7.2 SQL INNER JOIN

The INNER JOIN selects records that have matching values in both tables.

Syntax:

Example:
selects all orders with customer information

Example:

selects all orders with customer and shipper information

7.3 SQL LEFT JOIN

The LEFT JOIN returns all records from the left table (table1), and the matching
records from the right table (table2). The result is all records from the left table
and 0 records from the right side, if there is no match.

Syntax:

Example:

select all customers and any orders they might have

7.4 SQL RIGHT JOIN

The RIGHT JOIN returns all records from the right table (table2), and the
matching records from the left table (table1). The result is all records from the
right table and 0 records from the left side, if there is no match.
Syntax:

Example:

return all employees, and any orders they might have placed.

7.5 SQL FULL OUTER JOIN

The FULL OUTER JOIN returns all records when there is a match in left (table1) or right
(table2) table records. Note that FULL OUTER JOIN and FULL JOIN are the same.

Syntax:

Example:

selects all customers, and all orders.

7.6 SQL Self Join

A self Join is a regular join, but the table is joined with itself.

Syntax:
Where T1 and T2 are different table aliases for the same table.

Example:

Select customers that are from the same city.


Chapter 8: SQL Views

8.1 SQL Views

A view is a virtual table based on the result-set of an SQL statement. A view


contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database. You can add SQL statements and
functions to a view and present the data as if the data were coming from one
single table.

8.2 Create View

A view is created with the CREATE VIEW statement.

Syntax:

Example1: create a view that shows all customers from Brazil:

Example2: create a view that selects every product in the "Products" table with
a price higher than the average price:

8.3 Updating a View


A view can be updated with the CREATE OR REPLACE VIEW statement.

Syntax:

Example: add the "City" column to the "Brazil Customers" view:

8.4 Drop a View

A view is deleted with the DROP VIEW statement.

Syntax:

Example: drop the "Brazil Customers" view:

You might also like