0% found this document useful (0 votes)
7 views36 pages

DBMS Lab

The document provides comprehensive SQL exercises covering table creation, alteration, data insertion, and various SQL commands including SELECT, UPDATE, DELETE, and TRUNCATE. It also explains SQL joins, subqueries, aggregate functions, and string and date functions, along with examples for each. Additionally, it discusses the use of constraints, operators like UNION and INTERSECT, and the significance of aggregate functions in data analysis.

Uploaded by

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

DBMS Lab

The document provides comprehensive SQL exercises covering table creation, alteration, data insertion, and various SQL commands including SELECT, UPDATE, DELETE, and TRUNCATE. It also explains SQL joins, subqueries, aggregate functions, and string and date functions, along with examples for each. Additionally, it discusses the use of constraints, operators like UNION and INTERSECT, and the significance of aggregate functions in data analysis.

Uploaded by

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

EXERCISE-1

1 creation ,altering and dropping of tables and


inserting rows into a table(use constraints while
creating tables)examples using SELECT
command
SYNTAX:
Create table<tablename>(columnname1
datatype1,columnname2 datatype2….)
EXAMPLE:
Create table tblemployee (empID int,
EmpName varchar(50),gender char(1),salary
Money)

ALTER:
SYNTAX:
Alter table<tablename>Add<column
name>datatype
EXAMPLE:
Alter table tblemployee add mobilenumber
varchar(10)

INSERT:
SYNTAX:
Insert
into<tablename>values(value1,value2,value
3……)
EXAMPLE:
Insert into
tblemployee(3,’John’,’M’,4000),
(2,’Hensy’,’F’,3000)
1
Select * from tblemployee
UPDATE:
SYNTAX:
Update<tablename>
Set col=val
Where col=val
EXAMPLE:
Update tblemployee
Set gender=’M’,
Where Gender=’F’.

DELETE:
SYNTAX:
Delete from <table-name>
Where<column>=<values>
EXAMPLE:
Delete from tblemployee
Where empid=3.
TRUNCATE:
SYNTAX:
Table<table-name>
EXAMPLE:
Truncate table tblemployee

Key constraints:
Primary key
Foreign key
Unique key
Null constraint
Check constraints
Default constraints

2
Create table Department(deptID int
primary key,
DepartmentName varchar(50),
Locations varchar(50))

create table customers(customerId int


primary key,
customerName varchar(50),
age int check(age>0),
mobilenumber varchar(50) unique,
email varchar(50) not null,
address varchar(50) default('NRI
college'),
DepartmenttID int foreign key references
Department(DeptID))

3
4
SQL JOINS
What is SQL join?
Sql join combine rows from more than one table
by using common column in both tables.
Why we use SQL join.
Flexibility: It allows the user to access and
manage record from more than one table.
Data Redundancy: SQL join allows us to keep
data redundancy low so that we can reduce the
amount of data anomalies.
Efficiency: Executes faster and shows results
much more quickly than any other sub query.
TYPES OF JOINS:
1.INNER JOIN.
2.OUTER JOIN.
3.CROSS JOIN.
1.INNER JOIN: Inner join returns a new table by
combining records that only have matching
values in both the tables.
SYNTAX:
Select table1.col_name,table2.col_name,….
From table1
Inner join table2
5
ON table.column=table2,column
2.OUTER JOIN:
1. LEFT OUTER JOIN: Left outer join returns all the
rows from the left table and matching rows from
the right table.
SYNTAX:
Select table1.col_name,table2.col_name,….
From table1
Left outer join table2
ON table1.column=table2.column
2. RIGHT OUTER JOIN: Right join returns all rows
from the right table and all the matching records
from the left table.
SYNTAX:
Select table1.col_name,table2.col_name,….
From table1
Right outer join table2
ON table1.column=table2.column
3. FULL OUTER JOIN: Outer join returns all those
records which are in either the left table(or)right
table.
SYNTAX:
Select table1.col_name,table2.col_name,….

6
From table1
Full outer join table2
ON table1.column=table2.column
3. CROSS JOIN: A cross join is a type of join that
returns the cartesian product of rows from the
tables in the join.In other words,it combine each
row from the first table with each row from the
second table.
SYNTAX:
Select table1.col_name,table2.col_name,….
From table1
Cross join table2
ON table1.column=table2.column

SIGNATURE OF FAUCTLY:

7
EXERCISE -2
Queries (along with Job Queries) wang ANY, ALL,
IN, EXISTS,NOTEXISTS, UNION,INTERSET,
constraints Example: select the roll number and
name of the Student who Secured fourth rank in
the class.
SUB QUERY :(Query within a Query) (or)
Inner Query Embedded within outer Query.
IN and Notin Notin Operator:
The IN is a logical operates in SQL .The IN
Operator returns true if a value is in a set of
values or false otherwise.
Expression In (value1, value2.....)
→To negate the In operator, you use the NOT
Operator.
* The NOT IN Operators returns true if the
Expression does not Equal any Values in the list
or false Otherwise
Expression NOT IN (Valuel, Value 2,....)
Query to retrieve products that are not sold using
sub query
Select [Id], [Name], [Description]
from tblproducts

8
where Id not in (select Distinct Productid from
tblproductsales)
Query to retrieve products that are sold using
Subquery
Select [Id), [Name], [Description]
from tblproducts
where Id in (select Distinct Productid from
tblproductsales)
Any, All & EXISTS Operator:-
*In SQL, the operators ANY,ALL and EXISTS are
used in combination with subqueries to perform
comparisons and logical operations.
ANY OPERATOR:
The ANY Operator is used in combination with
comparison operators to compare a value with a
Set of values returned by a Subquery.
*It returns true if the comparison holds true for
atleast one value in the set.
*The Any Operator is typically used with the
WHERE OF HAVING clause to filter rows
based on specific conditions.
Syntax for Any Operator
Select column name(s)

9
from table-name
WHERE column name operator Anly
(subquery);
Note: The operator must be a Standard
Comparison Operator (=, <>,!=, >, >=, <,<=)
Example: write an SQL query to get all the
teachers data from teachers table whose age is
Equal to any age in the student table.
Select * from Teachers where age = any (select
age from Students);
ALL Operator:
*The All operator is used in combination with
Comparison operators to compare a value with
Set of values returned by the query.
*It returns true if the comparison holds true for all
the Values in the set.
*The All operators is often used with the WHERE
and HAVING Clause.
Syntax for All operators:
Select column name(s)
from table name
WHERE Column name Operator All (subquery);

10
Note: The operator must be a standard
comparison
Operator (=<!>><<=)
Example: write an SQL Query to retrieve all
teachers whose age is greater than the age of all
students.

Select * from teachers where age >all (select age


from students);
EXISTS operators:
*The Exists operator is used to test for the
Existence of any record in Subquery.
*It returns true if the subquery returns one or
more records.
*It is useful when you want to conditionally
retrieve data based on existence of related
records in Same or another table.
* EXISTS Operator generally wed with corelated
Subqueries.
* The EXISTS Operator is typically used in
Combination with the WHERE clause in SQL.
Examples: write a Query to retrieve
Syntax:
The EXISTS operator will return TRUE

11
SELECT (column Names]
FROM [source] WHERE NOT EXISTS (write
subquery to check)
Example: write a Query to retrieve the names of
the students who have received math class.
SELECT
Student-id, first_name, last name
FROM
Student
WHERE EXISTS(
SELECT1
FROM
Student grade
WHERE
Student grade .Student id = student. Student id
AND Student grade. grade = 10 AND
Student grade, class-name=’Math’
)
ORDER BY student.id
SELECT
Student-id, first-name, last-name
from

12
Student
WHERE NOT EXISTS (
SELECT 1
FROM Student grade
WHERE
student-grade. Student- id = student. Student-
ind
AND
student -grade. grade <9
)
ORDER BY student-id.

UNION and UNION ALL operators:


*union and UNION ALL Operators in SQL Server,
are used to combine the result-set of two or
More SELECT queries.
Difference between UNION and UNION ALL
(common interview Question)
* from the output, it is very clear that, UNION
removes duplicate rows, where as UNION All does
not when use UNIONI, to remove the duplicate
rows, SQL server has to do a distinct Sort, which
is time consuming for this reason, UNION ALL is
much faster than UNION.
13
Note: for UNION and UNION ALL, to work, the
number, Datatypes, and the order of the columns
in the Select statements should be Same.
Intersect and Except:
*Intersect Operator retrieves the common
records from both the left and the right query of
the Intersect operator.* EXCEPT Operator returns
unique rows from the left query that aren't in the
right query’s results.
Note: These operators to work the following 2
Conditions must be met.
*The number and the order of the columns must
be same in both the queries.
*The datatypes must be same or atleast
compatible.
Examples:-
Union, Union All, Intersect, Except.
Select * from Table A
UNION ALL
Select * from TableB
2. Select from tableA
UNION
Select * from TableB.
3. Select from TableA
14
Interest
select * from ТableB.
4 Select from Table A
Except
Select from TableB.
Top operators
*The Top keyword in SQL Server is a non-ANSI
Standard Expression to limit query results to
Some Set of Pre-Specified rows
Syntax: SELECT TOP (expresion) [PERCENT]
[WITH THES]
FROM -table-name
ORDER BY Column-name;

15
SIGNATURE OF FACULTY:

EXERCISE-3
Queries wing Aggregate functions(Count,
SUM, AVG, MAX and MIN)GROUP By, Having
and creation and dropping of views .
Sum of sales by product:
Select * from Sales
select product, sum (Sale Amount) as Total
sales from Sales
Group by product
Max of sales by product:
Select * from Sales
Select Product, Max (Sale Amount) as Total
sales
from sales
Group by Product
Min of Sales by product:

16
select * from Sales
Select product, Min (sale Amount) as Total
sales
from Sales
Group by product

Avg of sales by product


select * from Sales
Select Product, Avg (Sale Amount) as Total
sales from Sales
Group by product.
Count of sales by product
Select * from sales
Select product, count (*) as Total count
from Sales
Group by product.
HAVING clause: It is used to filter the
aggregate column
Select product, sum (Sale amount) as Total
sales from Sales
Group by Product
17
Having sum (sale Amount) >1,000
CREATE

SIGNATURE OF
FACULTY :

EXERCISE -4
Queries using conversion functions(to-char, to-
number, and to-date),string
functions(concatenation, l pad, r pad, l trim, r
trim, lower, upper, in it cap, length, sub str and
in
str),datefunctions(Sysdate,next_day,add_months,
last_day,months_between,least,greatest,trunc,ro
und,to_char,to_date) .
AIM:
LTRIM: (characters-Expression) Removes blanks
on the left hand side of the given character
Expression
Eg: Select LTRIM('Hello')
RTIM: (Character Expression) - Removes blanks
on the right hand side of the given character
Expression.

18
Eg: Select RTIM ('Hello ‘)
Lower: (character-Expression) - Converts all the
characters in the given character-Expression, to
lower case letters.
Eg: Select LOWER (CONVERT This string Into
Lower Case')
Upper: (character-Expression)- Converts all the
characters in the given character Expression, to
upper case letters.
Eg: Select UPPER ('CONVERT This string into
Upper Case’)
Reverse: (Any String Expression) - Reverses all
the characters in the given string Expression
Eg: Select
REVERSE(ABCDEFGHIJKLMNOPQRSTUVWXYZ)
LEN: (String Expression)- Returns the count of
total Characters, in the given String Expression,
excluding the blanks at the End of the
Expression.
Eg: Select LEN (‘SQL functions ')
Left (character Expression, Integer. Expression) -
Returns the Specified number of characters from
the left hand Side of the given Character
Expression.
Eg: Select LEFT('ABCDE', 3)

19
Right (Character Expression, Integer Expression)
- Returns the Specified number of characters
from the right hand Side of the given character
Expression.
Eg: Select RIGHT ('ABCDE', 3)
CHARINDEX: (Expression To-find Expression-To-
search' start location') -Returns the starting
position of the Specified Expression in a
character String, Start location
Parameter is optional .
Eg: Select CHARINDEX ('@ ‘,’[email protected]’, 1)
SUB String: ('Expression', 'Start', 'length's As the
name, Suggests, this function returns Substring
(part of the String) from the given Expression.
you specify the Starting location using the 'Start'
Parameters and the number of characters in the
substring using "length" Parameter. All the 3
parameters are mandatory.
Eg:Select SUBSTRING (‘[email protected]’,6,7)
Replicate (string-to-be-Replicated, number of
time. The Replicate)-Repeats the given string, for
the specified number of times.
Eg: SELECT REPLICATE ('DBMS, 3)
Space: (Number of-spaces)- Returns number of
spaces, Specified by the Number-of-spaces
argument.
20
Eg: Select first Name +SPACE (5) + Last name
as full name
from tbl products
Replace (String Expression, pattern,
Replacement-value) Replaces all occurrences of a
specified string Valve with another String Valve.
Eg: Select Email, REPLACE (Email, '.com’,’.
net' )as converted from tbl products.
Stuff: (original-Expression, start, length,
Replacement Expression): Stuff() function inserts
Replacement Expression at the start Position
Specified, along with removing the characters
Specified Using length Parameter.
Eg: Select firstName, LastName, Email, STUFF
(Email, 2,3,’***’) as Stuffed Email
from tbl products

Date time functions:-


Is Date(): checks if the given Value is a valid
date, time, Or datetime Returns I for success, o
for failure.
Eg: Select ISDATE ('DBMS Lab')
Select ISDATE (Get Date())
Dayl(): Returns the Day number of the month of
the given date
21
Eg : Select DAY (GETDATE())
Month(): Returns the month number of the year,
of the given date
Eg: Select Month (GETDATE())
Year(): Returns the years Number of the giver
date
Eg: Select Yeas(GETDATE(1)
Datetime': (Date part, Date). Returns a string,
that represents o Post of the given date. This
function takes 2 parameters. The first Parameter
‘Date part' specified, the part of the date, we
want. The second parameter, is the actual date
from which we want the part of the Date.
Eg: Select DATENAME
DATEPART ABBERVATIO
N (Day, '2022-09-30
12:43:46-837)
Year Yy, yyyy Select
Quarter Qq ,q
DATENAME(Day, EEK
Month Mm ,m
Day Of Year Dy ,y DAY, 2022-04-30
Day Dd ,d 12:43:46-231)
Week Wk ,ww STYLE
Weekday Dw DATEFORMAT
Hour Hh
Minute Mi ,n 101
Second Ss ,s mm/dd/yy
Millisecond Ms 102
Microsecon Mcs yy.mm.dd
d ns
Nanosecon tz 22

d
Tz off set
103 dd/mm/yyyy
104 dd.mm.yy
105

Date part: (Date part, Date). Returns an integer


representing the Specified Date part. This
function is similar to Date Name Date
Name()returns nvarchar, where as Date part() s\
returns an integer
Eg : Select DATEPART(Weekday, 2022-08-30
19:45:31.193)
Select DATEPART (Weekday, 2022-01-30
19:45:31-793)
Date ADD: (Date part, Number To Add, date)-
Returns the Date Time, after adding specified
number to Add, to the date part specified Of the
given date.
Eg: Select Date Add (DAY, 20, GETDATE())
Date Diff (date part, Start date, end date) -
Returns the count of the Specified date part

23
boundaries crossed between the Specified Start
date and end date.
Eg: Select DATEDIFF(MONTH, 11/30/2005,
01/31/2006)
Select DATEDIFF(DAY,
11/30/2005, '01/31/2006)
Conversion function:
*To Convert one data type to another, CAST and
COVERT functions can be used.
* Syntax of CAST and CONVERT functions from
MSDN:
CAST (expression As data type [(length)])
CONVERT (dale-type [length), expression Style])
Eg: Select convert (nvar char), Create date(),103
as Converted DOB
Eg: Select cast (GET Date() as date)
Mathematical functions:
ABS: (numeric Expression) - ABS Stands for
absolute and returns, the absolute (Positive)
number.
Eg: Select ABS (-101.5)
CEILING (numeric-Expression) and floor (numeric
Expression)
* CEILING and floor functions accept o numeric
Expression as a Single Parameter. CEILING()
returns the smallest integer Valve greater than or
Equal to the Parameter, whereas floor() returns

24
the largest integer less than or equal to the
Parameter

Eg: Select CEILING (15.2)


Select CEILING (-152)
Eg: Select Floor (152) S
Select FLOOR (15:2)
power:- (expression, Power) - Returns the power
value of the Specified Expression to the
Specified Power.
Eg: Select POWER (2,3)
SQUARE (Number) -Returns the square of the
given number.
Eg: Select SQUARE(48)
SQRT(Number)-SQRT Stands for square act. The
function returns the Square root of the given
Valve.
Eg: Selelt SORT(81)
ROUND's (numeric Expression, length[,
function])-Round the given numeric Expression
based on the given length. This function takes 3
Parameters.
Eg: Select ROUND (850.556,2)

25
SIGNATURE OF FACULTY:

EXERCISE-5
Create a Simple PL/SQL program which
includes declaration Section, Executable
section and Exception handing section(Eg:
student marks Can be selected from the
table and printed for those who secured first
class and on Exception can be raised it no
records were found).

Variables in SQL:
A Transcat-SQL local Variable is an object
that can hold a single data value of a
Specific type.
*firstly ,If we want to use a Variable in SQL,
server, we have to declare it. The DECLARE
statement is used to declare a Variable in
SOL Server.
* In the second step, we have to specify the
name of

26
the variable-local variables names have to
start with an at (@)sign because this rule is
a syntax necessity
*finally, we defined the data type of the
Variable.
Example:
*Declare Variable
DECLARE @Testvariable AS VARCHAR (100)
*Assign Value to variable
SET @Test Variable = 'one planet one life'
*Print Variable Value
PRINT @TestVariable.
Create table student (Sid Varchar (10),
Sname varchar(20),rank Varchar (10));

Insert into Student Values (501, Ravi',


'second');

Insert into student Values (502, 'Raju’,


'third')

Insert into Student Values (503, Ramu, ‘ ‘);

Declare @student id varchar(10);


27
Declare @studentName varchar(10);
Select @studentid=Sid,@ StudentName =
Sname from
Student where rank = 'first';
If @@ROWCOUNT <=0
Begin
Print # Error: there is no student got first
rank
end
Else
begin
Print ‘Student No:' +is null(@Studentid, ' ') +
'Name:' + is null (@StudentName, ' ') + 'got
first rank';
end

2 Insert data into Student table and use


COMMIT, ROLLBACK and SAVEPOINT in
PL/SQL block.

Transactions in SQL: A transaction is a single


unit of work. If a transaction is a successful,
all of the data modifications made during
the transaction are committed and become
a permanent part of the database. If a
28
Transaction encounters Errors must be
cancelled or rolled back, then all of the data
modifications are Erased.
*In order to define on Explicit
transaction ,we start to Use the BEGIN
TRANSACTION Command because this
Statement identifies the starting point of the
Explicit transaction. It has the following
syntax;
BEGIN TRANSACTION [{transaction-name l@
Tran-name e Variable}
[WITH MARK ['description']]]
Examples
BEGIN TRAN
UPDATE Student
SET Rank = ‘first’,
WHERE Sid=3
SELECT @@TRAN COUNT As open
Transactions.
Commit Transactions,
*COMMIT TRAN Statement applies the data
changes to the database and the changed
data will become Permanent. Now let's
complete the opentransaction with a
COMMIT TRAN statement.

29
Example:
BEGIN TRAN
UPDATE Student
SET Rank='first’,
WHERE sid=3
SELECT @@TRANCOURST AS Open
Transactions
COMMIT TRAN
SELECT TRAN COUNT AS open Transactions
ROLLBACK Transactions:
**The ROLLBACK TRANSACTIONS Statement
helps in undoing all data modifications that
are applied by the transactions
BEGINTRAN
UPDATE Person
SET Rank=’Fourth’,
WHERE SID=502
SELECT * FROM Student WHERE SID=502
ROLLBACK TRAN
SELECT * FROM Student WHERE SI0=502
Save Points in Transactions:-
*Save points can be wed to rollback any
particular part of the transactions rather

30
than the Entire transaction. So that we can
only Rollback any Portion Of the transaction
where between after the save Point and
before the rollback Command. To define a
save point in a transaction we use the SAVE
TRANSACTIONS Syntax and then we add a
name to the Save point.
Examples
Create table tblstudent (id int, name
varchar(50)
Rank Var char (10))
DECLARE @vsecond Insert NCHAR
(50)='secondinsert’
BEGIN TRANACTIONS
Insert INTO tblstudent (ID, name, Rank)
VALUES (1, 'Ravi’, '1')
SAVE TRANSACTIONS FIRST Insert
Insert INTO tblstudent (ID, name, Rank)

VALUES (2, 'Raju','2')


SAVE TRANSACTIONS @vsecond Insert.
Insert INTO tblstudert (ID, name, Rank)
VALUES (3,’Ramu', '3')
ROLLBACK TRANSACTIONS @usecond Insert

31
COMMIT TRANSACTIONS.

SIGNATURE OF FACULTY:
EXERCISE-6
Develop a program that includes the
features NESTED IF, CASE and CASE
Expression. The Program can be Extended
using the NULLIF and COALESCE functions.

Case statement:
The case statement in SQL returns a Value
on a specified Condition. we can use a case
Statement in Select queries along with
where, Order By, and Group By clause. It
can be used in Insert statement as well.
Syntax
CASE Selector

32
WHEN 'Value 1 THEN SI;
WHEN 'Value 2' THEN SE;
WHEN "Valves' THEN $3;
ELSE Sn; default Case
END CASE;
Create table Emp (eno int, ename
varchar(10), loc Varchas (10), Salary
money);
Insert into Emp values (101, 'ali', 'vja',
15000);
Insert into Emp Values (10), 'ravi!, 'hyd’,
25000);

Insert into Enp Valves (103, 'raju', 'gnt,


35000);
Insert into Emp Values (104, 'rakesh; vja,
45000);
Select * from emp;
Select loc, case (loc) when 'vja'
then Salary +2000
when ‘hyd’ then salary +1000 Else Salary
end rev-Salary from emp;
Null IF:

33
*NULLIF: Takes two arguments If the two
arguments are Equal, then Null & returned.
Otherwise the first argument is returned.
* The following shows the syntax of the
NULLIF Expression:
Example!:
SELECT NULLIF(10,10) result;
Example:
SELECT NULLIF (10,20) result;
EXAMPLE:
Select * from emp
Select ename,nullif(‘ali’,’ali’)from emp;
SELECT
NULLIF(10,10) result;
SELECT
NULLIF(20,10) result;
COALESCE:
*The SQL server COALESCE() function is
useful to handle NULL values. The Null
values are replaced with the User-given
Value during the Expression valve
Evaluation Process. The SQL Server
Coalesce function Evaluates the Expression
in a definite order and always results frist

34
not null Value from the defined Expression
list.
Syntax:-
Coalesce ("Expression1", "Expression 2",...);
Properties of the syntax of SQL server
Coalesce function:
*All Expressions must be have some data
type.
*It could have multiple Expressions.
Example:
SELECT COALESCE (NULL, 'x', ‘Y’) AS
RESULT,
SELECT COALESCE (NULL, NULL, NULL,
NULL, NULL, ‘GFG’, 1)
Nested IF Examples:
The transact-SQL statement that allows and
If keyword and its condition is Executed if
the condition is satisfied: the Boolean
Expression returns TRUE. The optional ELSE
keyword Introduces another transact-SQL
statement that is Executed when the If
Condition is satisfied: the Boolean
Expression returns FALSE.
DECLARE @age INT; SET @age=60;
It @age <18

35
PRINT ‘Underage’;
ELSE
BEGIN
If (@age>=18 and @age <50)
PRINT 'you are below 50';
ELSE
PRINT 'Senior';

SIGNATURE OF FACULTY:

36

You might also like