DBMS Lab
DBMS Lab
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))
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.
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.
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
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
d
Tz off set
103 dd/mm/yyyy
104 dd.mm.yy
105
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
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));
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)
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);
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