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

SQL

Uploaded by

budhah282
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

SQL

Uploaded by

budhah282
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

BIT 6113

Database Management
System
Sushil Bhattarai
[email protected]

Lincoln University College, CN 1221


MSSQL Setup
• Update your Windows.
• Do not Compress your Hard Drives.
• Make sure you are the owner/admin for the drives.
• Make sure you have more than 1 disk drive.
• Install MSSQL Server (any version) Express Edition.
• Install SSMS(Microsoft SQL Server Management Studio).

Remember your password


• install MS Word and MS Excel
MSSQL Server Overview
System Databases
1. Master
• Contains all of the system level information for SQL Server – all of the logins,
linked servers, endpoints, and other system-wide configuration settings
• Stores information about the other databases
• SQL Server cannot start if Master db is not present

2. Model
• Must always exist on a SQL Server system
• Entire contents of the database including database options, are copied to
the new database

3. Msdb
• Used by the SQL Server Agent, database mails and jobs
• Holds history when each database and filegroup was last backed up
4. Tempdb
• global resource that is available to all users connected to the instance
• Re-created every time the SQL Server service is started
• Stores the intermediate results and temporary data
• Vital for SQL Server performance
Architecture of MSSQL Databases
• Data Files
1. Primary Data Files
• All data in the database are stored in the Primary Data Files
• Only one primary data file for a database
• Extension .mdf, i.e. Master Database File
2. Secondary Data Files
• used to spread data across multiple disks
• Can use multiple Secondary Data Files
• Extension .ndf
• Log Files
• useful for the database recovery
• Can have one or more log files
• store the transaction information (insert, update, delete etc.)
• extension of log data file is .ldf
MSSQL Data Files
SQL(Structured Query Language)
• Set of commands/Instructions.
• To access and manipulate data and databases.
• standard language for Relational Database
System; enables user to create, read, update
and delete relational databases and tables.
• SQL depends on tuple relational calculus and
relational algebra.
Create tables in MSSQL
CREATE TABLE Product (
Id INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
Brand VARCHAR(100) NOT NULL,
ProductName VARCHAR(100) NOT NULL,
ProductType VARCHAR(100),
Price DECIMAL (10,2) NOT NULL,
ManufacturedDate DATE,
ExpiryDate DATE,
BatchNo INT
)
Create tables in MSSQL
• Create a table “Citizen” to store data of
Citizens(similar to the data in a Citizenship)

• Create a table named “Contact” to store


contact details of persons(similar to a Phone
Book in a Smart Phone)
Create table Contact (
Id int Primary Key Identity(1,1)
FirstName VARCHAR(200) NOT NULL,
LastName VARCHAR(200) NOT NULL,
Mobile VARCHAR(50) NOT NULL,
HomePhoneNumber VARCHAR(50),
WorkPhoneNumber VARCHAR(50),
Address VARCHAR(200),
DOB DATE,
Email VARCHAR(100)
)
Insert into Contact(FirstName , LastName , Mobile )
Values(‘ram’,’kumar’,’123’)
Insert into Table
SELECT * FROM Product;
-- Insert data in table Product
Insert Into Product(
Brand,
ProductName,
ProductType,
Price,
ManufacturedDate,
ExpiryDate,
BatchNo
)
VALUES(
‘CG',
'Wai Wai',
'Noodles',
20,
'2021/01/01',
'2021/08/01',
185
)

Insert 10 more records in table Product


Query Exercise
• Insert records of 10 people in table “Contact”.
• Select any 3 persons from table “Contact” whose First Name
starts with ‘a’.
• Select 2 persons from table “Contact” who have gmail
accounts.
• Select any 5 persons from table “Contact” whose Last Name
starts with ‘s’.
• Show only 5 “Name” and “Phone Number” from table
“Contact” and sort them alphabetically.
• Show only 2 records from table “Contact” that have valid
values for Work.
• Show only the contact details with no data for “DOB”
• Show only the “Name” and “DOB” of each records that have
valid DOB.
• Show only the Name and Age of each records.
Query Exercise
• Insert records of 10 people in table “Citizen”.

• Select any 5 of the records from table “Citizen”


• Select only 2 of the records from table “Citizen”
eldest first.
• Select only 5 of the records from table “Citizen”
youngest first.
• Select only Citizens born in “Kathmandu”.
• Select only Citizen s born in “Kathmandu”.
• Show only the Names of Citizens.
• Show only the Name and Birth Places of each Citizen.
Query Exercise
• Show the list of Citizens that were born later than 2001-01-01.
• Show the list of Citizens that were born between 2001-01-01 and 2005-01-01.
• Show the list of Citizens that were born in Pokhara and Kathmandu(Use IN).
Query Exercise
• Insert records of 10 people in table “Contact”.
• Select any 3 persons from table “Contact” whose First Name
starts with ‘a’.
• Select 2 persons from table “Contact” who have gmail
accounts.
• Select any 5 persons from table “Contact” whose Last Name
starts with ‘s’.
• Show only 5 “Name” and “Phone Number” from table
“Contact” and sort them alphabetically.
• Show only 2 records from table “Contact” that have valid
values for Work.
• Show only the contact details with no data for “DOB”
• Show only the “Name” and “DOB” of each records that have
valid DOB.
• Show only the Name and Age of each records.
SQL
Eg:
Create table Student(
Id int Primary key identity(1,1),
FirstName varchar(255) NOT NULL,
LastName varchar(255) NOT NULL,
DOB date,
Weight Decimal(5,2), -- smallest : 0.01, largest 999.99
IsCR Bit
)
SQL
Eg:
Insert into table
Select * from table
Select column names
Order by
where
Like
Update
Delete
Query Processing

• Parser:
 Syntax check and Semantic check
(e.g.: checks if query contains
table name that does not exist)
• Optimizer:
 Query execution plan(way to
implement the SQL request ) are
examined and most efficient plan
is selected.
 The database catalog stores the
execution plans and optimizer passes the lowest cost plan for
execution.
• Execution Engine:
• Finally, run the query and display the results.
Types of SQL Commands
Types of SQL Commands
• DDL(Data Definition Language)
• Used to create and modify the structure of database objects in database
• CREATE – Creates objects in the database
ALTER – Alters objects of the database
DROP – Deletes objects of the database
TRUNCATE – Deletes all records from a table and resets table identity to
initial value.
• DML(Data Manipulation Language)
• Read, store, modify, delete, insert and update data in database
• SELECT - Reads data from a table
INSERT - Inserts data into a table
UPDATE - Updates existing data into a table
DELETE - Deletes records from a table
• DCL(Data Control Language)
• used to create roles, permissions and control access to database
• GRANT – Gives user's access privileges to database
REVOKE – Withdraws user's access privileges
• TCL(Transaction Control Language)
• Manage transactions within the database
• COMMIT – Saves the changes made within the database
ROLLBACK – Revert the changes to the previous state.
DDL Commands
• Create
The following statement creates a new table named "Student“.
Create table Student(
Id int Primary key identity(1,1) NOT NULL,
FirstName varchar(255) NOT NULL,
LastName varchar(255) NOT NULL,
DOB date,
[Weight] Decimal(10,2),
IsCR Bit
)

• Alter
The ALTER TABLE statement is used to add, delete, or modify columns or add and drop various
constraints in an existing table.
. Add column Alter table Student add Email varchar(500)
. Drop Column Alter table Student drop column IsCR;
. Modify column Alter table Student alter column FirstName varchar(500)
Alter statements for Constraints will be studied inside Constraints topic.
• Drop • Truncate
Drops an existing table in a database Delete the data inside a table, but not the table itself.
Drop table Student; Truncate table Student;
DML Commands
• Select
• Insert
• Update
• Delete
Query Exercises
1. Create a table named "Product" to store the details of the laptops in
an office. The table should store the data related to the Brand, Model,
UnitPrice and BoughtDate of the laptops.
2. Insert ten records of laptops bought in different date into the
table "Product".
3. Update the 5th row to have Brand value "Dell" and Model "D153000".
4. Update the 3rd row to have Model value “A-123” and price 85000.
5. Update the 1st row to have price 85000 and BoughtDate to have
current date.
6. Delete the 1st row from the table.
7. Select only one row to show the latest product.
8. Select only one row to show the oldest product.
9. Show the details of the brand name that starts with "S".
Query Exercises
1. Write a query that adds 1000 to each unitprice in table.
2. Write a query that subtracts 500 from each unitprice in table.
3. What would be the price of each product if the price had been doubled?
4. If the tax rate is 10% on each item, what would be the tax to be paid for each
item?
5. If 10% tax is to be paid on each item, what would be the new price of each item.
Show the expensive one first.
6. The price of each Laptop is hiked by 1%. Update the table with new price.
7. Find the Average price of the laptops.
8. Find the Minimum price of a laptop.
9. Find the Maximum price of the laptop.
10. Find the Total price of all the laptops.
11. Find the Average price of Dell laptops.
12. Find the Minimum price of a Dell laptop.
13. Find the Maximum price of a Dell laptop.
14. Find the Total price of all Dell laptops.
15. Find total number of Laptops.
16. Find the number of Dell laptops.
DCL Commands
•Grant​
•Revoke​
•Alter Login

-- Create user and login first​
CREATE LOGIN Mylogin WITH PASSWORD = 'abcd';
go
CREATE USER Tester FOR LOGIN Mylogin;
-- Grant​
GRANT SELECT, UPDATE ON Student TO Tester
-- GIVE permissions(SELECT, UPDATE) on the table(Student) for users(Tester ) of database​

-- REVOKE​
REVOKE UPDATE ON Student FROM Tester
take back permission(UPDATE ) from users(Tester)​

-- Alter Login
ALTER LOGIN MyLogin WITH PASSWORD = '123' OLD_PASSWORD = 'abcd';
Data type Storage
Data Types Description
Integer from -2^63 (-9 223 372 036 854 775 808) to 2^63-1 (9 223 372 036
bigint 8 bytes 854 775 807)
int 4 Integer from -2^31 (-2 147 483 648) to 2^31-1 (2 147 483 647)
smallint 2 Integer from -2^15 (-32 768) to 2^15-1 (32 767)
tinyint 1 Integer from 0 to 255
bit 1 bit Integer 0 or 1.

5-17 depending Numeric data type with fixed precision and scale (accuracy 1-38, 18 by default
decimal(precision, scale) on p and s and scale 0-p, 0 by default).

Data type representing date and time from 1.1.1753 to 31.12.9999 with
datetime 8 precision about 3 ms. Values are rounded to .000, .003 and .007.

Data type representing date and time from 1.1.1900 to 6.6.2079 with
precision of 1 minute. Values up to 29.998 are rounded down and values from
smalldatetime 4 29.999 are rounded down to the nearest minute.
char n Text string of fixed length (maximum length of 8000 chars).
varchar n Text string of variable length (maximum length of 8000 chars)
Text string of variable length (maximum length of 2^31-1 = 2 147 483 647
text n chars)

Numeric Data Type


Date Time Data Type
Alpha Numeric Data Type
Operators
• Comparision
Comparison operators compares whether two expressions are the same

Operator Meaning
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
Operators
• Logical
Operator
Operator Meaning
Meaning
= Equal to
AND > TRUEGreater than
if both Boolean expressions are TRUE.
< Less than
OR >= TRUEGreater
if eitherthan
Boolean expression
or equal to is TRUE.
BETWEEN<= TRUELessif thethan or equal
operand to a range.
is within
<> Not equal to
EXISTS TRUE if a subquery contains any rows.
TRUE if the operand is equal to one of a list of
IN
expressions.
LIKE TRUE if the operand matches a pattern.
NOT Reverses the value of any other Boolean operator.
Operators
• Arithmetic
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
Returns the integer remainder of a division. For example, 5 % 3
% (Modulo)
= 2 because the remainder of 5 divided by 3 is 2.
Operators
• Compound
Operator Action
Adds some amount to the original value and sets
+=
the original value to the result.
Subtracts some amount from the original value and
-=
sets the original value to the result.
Multiplies by an amount and sets the original value
*=
to the result.
Divides by an amount and sets the original value to
/=
the result.
Divides by an amount and sets the original value to
%=
the modulo.

Find yourself what these operators do


Constraints
• SQL constraints are used to specify rules for the data in a table. These can be
specified when tables are created or after it has been created.
• Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.

Common Constraints:
NOT NULL - Ensures that a column cannot have a NULL value
UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
FOREIGN KEY - Uniquely identifies a row/record in another table
CHECK - Ensures that all values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column when no value is specified

Constraints
NOT NULL
• This enforces a field to always contain a value, which means that you cannot insert
a new record, or update a record without adding a value to this field.
• When creating a table
CREATE TABLE Student(
ID INT NOT NULL,
FirstName VARCHAR(255) NOT NULL,
LastName VARCHAR (255) NOT NULL,
Age INT
);
• If table has been already created
ALTER TABLE Person
ALTER COLUMN Age INT NOT NULL;
• To remove the constraint
ALTER TABLE Person
ALTER COLUMN Age INT NULL;

Constraints 32
UNIQUE Constraint
• Unique Constraint ensures all values in a column are different.
• When creating a table
CREATE TABLE Teacher(
ID INT NOT NULL,
FirstName VARCHAR(255) NOT NULL,
LastName VARCHAR(255) NOT NULL,
Phone VARCHAR(255) UNIQUE
);
• OR
CREATE TABLE Teacher(
ID INT NOT NULL,
FirstName VARCHAR(255) NOT NULL,
LastName VARCHAR(255) NOT NULL,
Phone VARCHAR(255),
CONSTRAINT UK_Phone UNIQUE (Phone)
);
• If table has been already created
ALTER TABLE Student
ADD CONSTRAINT UK_Phone UNIQUE(Phone);
• To remove the constraint
ALTER TABLE Student
Constraints 33
DROP CONSTRAINT UK_Phone;
PRIMARY KEY Constraint
• Primary keys uniquely identifies each record in a table.
• A Primary key must contain UNIQUE values, and cannot contain NULL values.
• A table can have only one primary key, which may consist of single or multiple
fields.
• When creating a table
CREATE TABLE Person(
ID INT PRIMARY KEY NOT NULL,
FirstName VARCHAR(255) NOT NULL,
LastName VARCHAR(255) NOT NULL,
Age INT
);
• If table has been already created
ALTER TABLE Person
ADD CONSTRAINT PK_ID PRIMARY KEY (ID);
• To remove the constraint
ALTER TABLE Person
DROP CONSTRAINT PK_ID;
Constraints 34
FOREIGN KEY Constraint
• A Foreign Key is a key used to link two tables together.
• A Foreign Key is a field in one table that refers to the PRIMARY KEY in another table.
• When creating a table
CREATE TABLE Orders (
ID INT PRIMARY KEY NOT NULL,
OrderNumber INT NOT NULL,
PersonID INT FOREIGN KEY REFERENCES Person(ID)
);
• OR
CREATE TABLE Orders (
ID INT PRIMARY KEY NOT NULL,
OrderNumber INT NOT NULL,
PersonID INT,
CONSTRAINT FK_PersonOrders FOREIGN KEY (PersonID)REFERENCES Person(ID)
);
• If table has been already created
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrders FOREIGN KEY (PersonID) REFERENCES Person(ID);
• To remove the constraint
ALTER TABLE Orders
Constraints 35
DROP CONSTRAINT FK_PersonOrders;
CHECK Constraint
• The CHECK constraint is used to limit the value range that can be placed in a
column.
• When creating a table
CREATE TABLE Customer(
ID INT NOT NULL,
FirstName varchar(255) NOT NULL,
LastName varchar(255) NOT NULL,
Age INT CHECK (Age>=18)
);
• If table has been already created
ALTER TABLE Person
ADD CONSTRAINT CHECK_PersonAge CHECK (Age>=18);
• To remove the constraint
ALTER TABLE Person
DROP CONSTRAINT CHECK_PersonAge;

Constraints 36
DEFAULT Constraint
• The DEFAULT constraint is used to provide a default value for a column.
• The default value will be added to the new records if no value is specified.
• When creating a table
CREATE TABLE Students(
ID INT NOT NULL,
FirstName varchar(255) NOT NULL,
LastName varchar(255) NOT NULL,
Age INT,
City VARCHAR(255) DEFAULT 'Kathmandu‘
);
Or
CREATE TABLE Students(
ID INT NOT NULL,
FirstName varchar(255) NOT NULL,
LastName varchar(255) NOT NULL,
Age INT,
City VARCHAR(255) CONSTRAINT DEFAULT_City DEFAULT 'Kathmandu‘
);
• If table has been already created Constraints 37
Assignment
1. Create a Table named MobileNumber to store Person’s Name and Mobile
Numbers. The table should be able to check if the length of the entered phone
number is greater or equal to 10.

Insert into MobileNumber (FirstName, LastName, MobileNumber)


Values(‘Ram’, ’Kumar’, ’1234’)

Insert into MobileNumber (FirstName, LastName, MobileNumber)


Values(‘Shyam’, ’Kumar’, ‘1234567890’)

2. Create a Table named Payment to store the payment records in a store. The
table should contain columns Product, Price and date of payment. The table
should check if the price is greater than 0. And the default date for date of
payment should be today’s date.
Insert into Payment(Product, Price, PaymentDate)
Values(‘Book’, 0.1, ‘2020-01-01’)

Insert into Payment(Product, Price)


Values(‘Book’, 0.01)
IDENTITY COLUMN
• IDENTITY column is used to automatically generate key values based on a provided
starting point and increment.
• Often this is the primary key.
CREATE TABLE Student(
ID int PRIMARY KEY IDENTITY(1,1) ,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
• Insert into table
INSERT INTO Persons (FirstName,LastName)
VALUES (‘Ram’,’Kumar');

Identity Column 39
INDEX
• An index is used to speed up searching in the database.
• A database index is, after all, very much like the index at the end of a book.
• Indexes are automatically created when creating Primary Keys.
• Create index on single column
CREATE INDEX idx_Age
ON Person (Age);
• create an index on a combination of columns
CREATE INDEX idx_name
ON Person(FirstName,LastName);
• To remove the constrain
DROP INDEX Person.idx_name;
• Indexed columns should be used on where clause and joins.
• Index should be wisely used else may make data INSERT and UPDATE slow.

Index 40
Aggregate Function
• Aggregate functions perform a calculation on a set of values and return a single
value.
• Common Aggregate Functions are:
– AVG – calculates the average of a set of values.

– COUNT – counts rows in a specified set of values.

– MIN – gets the minimum value in a set of values.

– MAX – gets the maximum value in a set of values.

– SUM – calculates the sum of values.

Aggregate Function 41
Aggregate Function Examples
• Average
SELECT AVG(UnitPrice) Average_Unitprice
FROM Product
WHERE SupplierId=20
• Count
SELECT COUNT(*) Count_Product
FROM Product
WHERE SupplierId=20
• Min and Max
SELECT MIN(UnitPrice) Min_Unitprice, MAX(UnitPrice)Max_UnitPrice
FROM Product
WHERE SupplierId=20
• Sum
SELECT SUM(UnitPrice) Total_Unitprice
FROM Product
WHERE SupplierId=20

Aggregate Function 42
Some SQL Clauses
Group By
• The GROUP BY clause denotes that rows should be grouped according to the
columns in the select statement.
• GROUP BY must be specified when there are columns along with the aggregate
functions in the SELECT statement.
SELECT Column1, Column2, ... Column_n,
aggregate_function (aggregate_expression)
FROM table
[WHERE conditions]
GROUP BY Column1, Column2, ... Column_n

• Example
SELECT FirstName, LastName,
AVG(Age) Average_Age
FROM Person
GROUP BY FirstName, LastName

Some SQL Clauses 43


Some SQL Clauses
Having
• The Having clause is Used to specify conditions on Aggregate Functions.
• This is used instead of ‘Where’ when Aggregate Functions are used.
SELECT column_name(s)
FROM table_name
[WHERE condition]
GROUP BY column_name(s)
HAVING condition;

• Example
SELECT FirstName, LastName, AVG(Age) Average_Age
FROM Person
GROUP BY FirstName, LastName
HAVING AVG(Age)>=18

Some SQL Clauses 44


Some SQL Clauses
Order by
• The ORDER BY clause specifies how records should be sorted.
• Default ORDER BY sorts columns in Ascending Order whereas ORDER BY DESC sorts
the record on Descending order.
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

• Example
SELECT *
FROM Person
ORDER BY FirstName
SELECT *
FROM Person
ORDER BY FirstName DESC

Some SQL Clauses 45


Exercise
1. Write a SQL statement to find the maximum price of each brand of
laptops.

2. Write a SQL statement to find the minimum price of each brand of


laptops. List the brands if the minimum price more than 40000.

3. Write a SQL statement to find the average price of each brand only if
the average price is greater than 50000.

4. Write a SQL statement to find the number of laptops of each brand.


List the brands that have more than 5 laptops.
JOINS
• Joins are used when data from 2/more tables need to be extracted.
• Types of JOIN:
1. INNER JOIN
2. LEFT OUTER JOIN
3. RIGHT OUTER JOIN
4. FULL OUTER JOIN

Joins 47
INNER JOIN
• Most common type of join
• Returns all rows if condition is met.
SELECT columns
FROM table1 t1
INNER JOIN table2 t2
ON t1.column = t2.column;

• Example
SELECT C.FirstName, C.LastName, O.totalamount
FROM [Order] O
INNER JOIN Customer C ON C.id=O.CustomerId

SELECT C.FirstName, C.LastName, SUM(O.totalamount) totalamount


FROM [Order] O
INNER JOIN Customer C ON C.id=O.CustomerId
GROUP BY C.FirstName, C.LastName

Joins 48
LEFT OUTER JOIN
• This type of join returns all rows from the LEFT-hand table specified in the
condition and only those rows from the RIGHT-hand table where the join condition
is met.

SELECT columns
FROM table1 t1
LEFT OUTER JOIN table2 t2
ON t1.column = t2.column;

• Example
SELECT C.FirstName, C.LastName, O.OrderNumber, O.TotalAmount
FROM Customer C
LEFT JOIN [Order] O
ON O.CustomerId = C.Id

Joins 49
RIGHT OUTER JOIN
• This type of join returns all rows from the RIGHT-hand table specified in the
condition and only those rows from the LEFT-hand table where the join condition
is met.
SELECT columns
FROM table1 t1
RIGHT OUTER JOIN table2 t2
ON t1.column = t2.column;

• Example
SELECT C.FirstName, C.LastName, O.OrderNumber, O.TotalAmount
FROM [Order] O
RIGHT JOIN Customer C
ON C.Id = O.CustomerId

Joins 50
FULL OUTER JOIN
• This join returns all rows from the LEFT-hand table and RIGHT-hand table with nulls
in place where the join condition is not met.
SELECT columns
FROM table1 t1
FULL OUTER JOIN table2 t2
ON t1.column = t2.column;

• Example
SELECT *
FROM [Order] O
FULL OUTER JOIN Customer C
ON C.Id = O.CustomerId

SELECT C.FirstName, C.LastName, C.Country,


S.Country, S.CompanyName
FROM Customer C
FULL JOIN Supplier S
ON C.Country = S.Country
Joins 51
Query Exercises on Joins

1. Create a table named Shipment to store the details of


shipped laptops. The table should contain the columns
LaptopID(FK referencing the PK of Product Table), Country,
Shipped Date, Shipping charges.
2. Insert any 5 records to show the laptops have been shipped
to different countries.
3. Show the list of Brands that have already been shipped.
4. Show the list of Brands and the countries that are shipped
to. If the laptops are not shipped yet, show “Not Shipped
Yet”.
Query Exercises on Joins

1. Create a table named TuitionFee to store the details of Fee


paid by Student. The table should contain the columns
StudentID(FK referencing the PK of Student Table), Amount,
Description and DateofPayment. You should be able to store
those amounts that are greater than Zero(use Check). The
default value to DateofPayment should be today’s date.
2. Insert at least 5 records to show the fee paid by students.
3. Create a table named Project to store the details of Project.
The table should contain StudentId (FK referencing the PK of
Student Table), Project, Department, Supervisor, StartDate
and EndDate.
4. Insert at least 5 records to show projects of each Students.
Query Exercises on Joins
1. Show the list of Students that have paid fee.
2. Show the list of Students that are involved in a Project.
3. Show the list of Students and total amount they have paid. The
student with highest paying fee should show on top and lowest on
bottom.
4. Show the list of Students and Total Fee they have paid only if the total
fee is greater than 4000.
5. Show the list of Students and number of Projects they are involved in.
6. Show number of students involved in the each project.
7. Show number of students involved in the each project only if multiple
Students(Number of Students>1) are involved.
8. Show the list of Students that have paid fee and are involved in a
Project.
Query Exercises on Joins
1. Show the list of Students and Total amount they have paid. Show 0 if they have not paid.
2. Show the list of Students that have not paid Fee.
3. Show the list of Students that are involved in a Project. If not involved show 'Not Involved'
in Project Name.
4. Show the list of Students that are not involved in any Project.
5. Show the list of Students that have paid Fee but are not involved in any Project.
6. Show the list of Students that are involved in a Project but have not Paid any Fee.

7. Show the list of Students and amount they have paid. The student with highest paying fee
should show on top and lowest on bottom.
8. Show the list of Students and amount they have paid only if the total fee is greater than
4000.
9. Show the list of Students and number of Projects they are involved in.
10. Show number of students involved in the each project.
11. Show number of students involved in the each project only if the multiple Students(Number
of Students>1) are involved.
12. Show the list of Students that have paid fee and are involved in a Project
ROW_NUMBER()
Write a query to find Duplicate Rows from the table Student.

Select * From (
SELECT
[FirstName]
,[LastName]
,[BirthDate]
,[Gender]
,[Class]
,[Point]
,ROW_NUMBER() OVER(PARTITION BY [FirstName], [LastName],
[BirthDate], [Gender], [Class],[Point] ORDER BY [FirstName]) sn
FROM [Student]
)b
Where b.sn>1

You might also like