0% found this document useful (0 votes)
20 views75 pages

SSA - Class 12 Practical - 25-26

The document is a certification template for cadets at Sainik School Amaravathinagar, confirming the completion of laboratory work in Computer Science for the academic year 2025-26. It includes a detailed table of contents listing various Python programming exercises and their corresponding page numbers. The exercises cover a range of topics, including basic arithmetic operations, functions, exception handling, file operations, and integration with SQL.

Uploaded by

study.sam.6661
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)
20 views75 pages

SSA - Class 12 Practical - 25-26

The document is a certification template for cadets at Sainik School Amaravathinagar, confirming the completion of laboratory work in Computer Science for the academic year 2025-26. It includes a detailed table of contents listing various Python programming exercises and their corresponding page numbers. The exercises cover a range of topics, including basic arithmetic operations, functions, exception handling, file operations, and integration with SQL.

Uploaded by

study.sam.6661
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/ 75

SAINIK SCHOOL AMARAVATHINAGAR

ACADEMIC YEAR 2025-26

SCHOOL ROLL NO :

CBSE ROLL NO :

NAME :

CLASS : XII SECTION :

SUBJECT : COMPUTER SCIENCE

SUB CODE : 083

HOUSE :

MASTER I/c : Mr. PM JIGAJINNI

1
SAINIK SCHOOL AMARAVATHINAGAR

CERTIFICATE

This is to certify that Cadet __________________________________


School Roll No _________ having CBSE Roll No: __________________________ has
successfully completed the laboratory work in Computer Science(083) Python laid
down in the regulations of CBSE for the purpose of AISSCE Practical Examination
2025-26 in Class XII to be held in Sainik School Amaravathinagar on / /2026

(PM Jigajinni)
PGT for Computer Science

Examiners:
1 Name: PM Jigajinni Signature:
(Internal)

2 Name: Signature:
(External)

2
TABLE OF CONTENTS

PAGE
S.NO DATE PROGRAMS SIGN
NO
WRITE A PYTHON PROGRAM THAT WILL ACCEPT THE

01 BASE AND HEIGHT OF A TRIANGLE AND COMPUTE THE 05


AREA.

WRITE A PROGRAM TO IMPLIMENT A CALCULATOR 06


02

WRITE A FUNCTION TO CALCULATE THE FACTORIAL


03 08
OF GIVEN NUMBER

WRITE A FUNCTION WHICH TAKES N AS AN ARGUMENT


04 09
AND PRINT FIBONACCI NUMBERS UPTO N

WRITE A PROGRAM IN PYTHON TO FIND GIVEN


05 10
STRING IS PALINDROME OR NOT

WRITE A FUNCION TO ILLUSTRATE DEFAULT


06 11
ARGUMENT

WRITE A FUNCTION TO ILLUSTRATE THE VARIABLE


07 12
LENGTH ARGUMRNTS

WRITE A FUNCTION TO ILLUSTRATES USE OF


08 13
KEYWORD ARGUMENTS

WRITE A FUNCTION TO ILLUSTRATES USE OF RETURN


09 14
STATEMENT

WRITE A PROGRAM TO ILLISTRATE THE USE OF


10 15
try….except Block – Exception Handling

WRITE A PROGRAM TO ILLISTRATE THE USE of


11 16
Catching Specific Exceptions

PYTHON PROGRAM TO COUNT VOWELS, LINES,


12 17
CHARACTERS IN TEXT FILE

WRITE A PYTHON PROGRAM TO READ A RANDOM LINE


13 19
FROM A FILE.

3
PAGE
S.NO DATE PROGRAMS SIGN
NO
WRITE A PROGRAM TO COPY ALL THE LINES THAT

14 CONTAIN THE CHARACTER `A' IN A FILE AND WRITE 20


IT TO ANOTHER FILE.

WRITE A PROGRAM TO CREATE BINARY FILE AND

15 DISPLAY THE CONTENTS STORED IN BINARY FILE 22


(MAKE USE OF PICKLE MODULE).

WRITE A PROGRAM TO CREATE A BINARY FILE WITH


NAME AND ROLL NUMBER. SEARCH FOR A GIVEN
16 23
ROLL NUMBER AND DISPLAY NAME, IF NOT FOUND
DISPLAY APPROPRIATE MESSAGE.

WRITE A PROGRAM TO UPDATE THE MARKS OF

17 PERTICULAR RECORD OF STUDENT USING BINARY 25


FILES.

WRITE A PROGRAM TO ILLUSTRATE WRITE AND


18 28
READ OPERATIONS ON CSV FILE.

WRITE A PROGRAM TO IMPLEMENT PUSH() AND

19 DISPLAY FUNCTIONS OF A STACK USING A LIST 29


DATA-STRUCTURE.

WRITE A PROGRAM TO IMPLEMENT POP() AND

20 DISPLAY() FUNCTIONS OF A STACK USING A LIST 31


DATA-STRUCTURE.

INTEGRATE PYTHON WITH SQL – TO CONNECT


21 34
DATABASE

INTEGRATE PYTHON WITH SQL – TO FETH RECORDS


22 35
FROM THE TABLE AND DISPLAY IT ON THE SCREEN

23 SQL - STATIONARY AND CONSUMER TABLES 37

24 SQL - ITEM AND TRADERS TABLES 42

25 SQL COMMANDS 47

26 SQL JOINS 71

4
1. WRITE A PYTHON PROGRAM THAT WILL ACCEPT THE BASE AND HEIGHT
OF A TRIANGLE AND COMPUTE THE AREA.

b = int(input("Input the base : "))


h = int(input("Input the height : "))

area = b*h/2

print("area = ", area)

5
2. WRITE A PROGRAM TO IMPLIMENT A CALCULATOR
# This function adds two numbers
def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

# This function divides two numbers


def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")

# check if choice is one of the four options


if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

6
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))
next_calculation = input("Let's do next calculation?
(yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")

7
3. WRITE A FUNCTION TO CALCULATE THE FACTORIAL OF GIVEN NUMBER

# Python program to find the factorial of a number provided by


the user.

# change the value for a different result


num = int(input("Enter first number: "))

# To take input from the user


#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num< 0:
print("Sorry, factorial does not exist for negative numbers")
elifnum == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

8
4. WRITE A FUNCTION WHICH TAKES N AS AN ARGUMENT AND PRINT FIBONACCI
NUMBERS UPTO N
def gen_fibonacci(nterms):
n1, n2 = 0, 1
count = 0
if nterms<= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elifnterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count <nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
def main():
n=int(input("Please enter a positive integer"))
gen_fibonacci(n)
main()

9
5 WRITE A PROGRAM IN PYTHON TO FIND GIVEN STRING IS PALINDROME OR
NOT
#function which return reverse of a string

def isPalindrome(s):
return s == s[::-1]

# Driver code
s = "malayalam"
ans = isPalindrome(s)

if ans:
print("Yes")
else:
print("No")

10
6. WRITE A FUNCION TO ILLUSTRATE DEFAULT ARGUMENT
def greet_msg(name="Mohan"):
print("Hello ", name)

def driver_code():
greet_msg("Karthick")
greet_msg()
driver_code()

11
7. WRITE A FUNCTION TO ILLUSTRATE THE VARIABLE LENGTH ARGUMRNTS

def sum(*n):
total=0
for i in n:
total+=i
print("Sum = ", total)
def driver_code():
sum() #o/p sum=0
sum(10) #o/p sum=10
sum(10,20,30,40) #o/p sum=100
driver_code()

12
8. WRITE A FUNCTION TO ILLUSTRATES USE OF KEYWORD ARGUMENTS

def student(firstname,lastname ='Kavin',standard ='Twelth'):


print(firstname, lastname, 'studies in', standard,'Standard')
# 1 keyword argument
student(firstname ='Ramesh')

# 2 keyword arguments
student(firstname ='Rajesh', standard ='Eight')

# 2 keyword arguments
student(lastname ='Keerthipriyan', firstname ='Prakash')

13
9. WRITE A FUNCTION TO ILLUSTRATES USE OF RETURN STATEMENT

def adder(x,y):
add=x+y
return add

def driver_code():
a=56
b=34
result=adder(a,b)
print("The result is = ",result)
driver_code()

14
10. WRITE A PROGRAM TO ILLISTRATE THE USE OF try….except Block –
Exception Handling

try:
numerator = 10
denominator = 0

result = numerator/denominator

print(result)
except:
print("Error: Denominator cannot be 0.")

# Output: Error: Denominator cannot be 0.

15
11. WRITE A PROGRAM TO ILLISTRATE THE USE of Catching Specific
Exceptions

try:

even_numbers = [2,4,6,8]
print(even_numbers[5])

except ZeroDivisionError:
print("Denominator cannot be 0.")

except IndexError:
print("Index Out of Bound.")

# Output: Index Out of Bound

16
12. PYTHON PROGRAM TO COUNT VOWELS, LINES, CHARACTERS IN TEXT
FILE
def counting(filename):

# Opening the file in read mode


txt_file = open(filename, "r")

# Initialize three variables to count number of vowels,


# lines and characters respectively
vowel = 0
line = 0
character = 0

# Make a vowels list so that we can


# check whether the character is vowel or not
vowels_list = ['a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U']

# Iterate over the characters present in file


for alpha in txt_file.read():

# Checking if the current character is vowel or not


if alpha in vowels_list:
vowel += 1

# Checking if the current character is


# not vowel or new line character
elif alpha not in vowels_list and alpha != "\n":
character += 1

# Checking if the current character


# is new line character or not

17
elif alpha == "\n":
line += 1

# Print the desired output on the console.


print("Number of vowels in ", filename, " = ", vowel)
print("New Lines in ", filename, " = ", line)
print("Number of characters in ", filename, " = ", character)

# Calling the function counting which gives the desired output


counting('Myfile.txt')

18
13. WRITE A PYTHON PROGRAM TO READ A RANDOM LINE FROM A FILE.

import random
def Read_Random_Lines(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)

#Drive Code
def main():
print(Read_Random_Line('robotics.txt'))
main()

19
14 WRITE A PROGRAM TO COPY ALL THE LINES THAT CONTAIN THE CHARACTER
`A' IN A FILE AND WRITE IT TO ANOTHER FILE.

def Write_Lines(Line):
myfile= open("Newtest.txt","a+")
myfile.write("\n"+Line)
myfile.close()

def Read_Lines():
myfile=open("test.txt","r")
Line=myfile.readline()
print(" First Letter : ",Line[0])
while (Line!=""):
if (Line[0]=='a' or Line[0]=='A'):
Write_Lines(Line)
Line=myfile.readline()
print("File Created! Lines Copied")
myfile.close()

#Driver Code

def main():
Read_Lines()
main()

20
OUTPUT:

TEST.txt CONTAINS:

NEW FILE CREATED NAMED NEWTEST.txt AND COPIED LINES STARTS WITH a
OR A LETTER FROM TEST.txt FILE

21
15. WRITE A PROGRAM TO CREATE BINARY FILE AND DISPLAY THE CONTENTS
STORED IN BINARY FILE (MAKE USE OF PICKLE MODULE).
import pickle
def Bin_Write():
import pickle
Mylist=[68,43,42,78,90,53,26,81,90,345]
f=open("myfile.dat",'wb')
pickle.dump(Mylist,f)
print("Binary File Created and List is added!")
f.close()
def Bin_read():
import pickle
f=open("myfile.dat",'rb')
Mylist=pickle.load(f)
print("List stored in Binary File is…………..",Mylist)
f.close()

# Driver Code:
def main():
Bin_Write()
Bin_read()
main()

22
16. WRITE A PROGRAM TO CREATE A BINARY FILE WITH NAME AND ROLL
NUMBER. SEARCH FOR A GIVEN ROLL NUMBER AND DISPLAY NAME, IF NOT
FOUND DISPLAY APPROPRIATE MESSAGE.

import pickle
#creating the file and writing the data
f=open("records.dat", "wb")
pickle.dump(["Wakil", 1], f)
pickle.dump(["Tanish", 2], f)
pickle.dump(["Priyashi", 3], f)
pickle.dump(["Kanupriya", 4], f)
pickle.dump(["Aaheli", 5], f)
f.close()
#opeining the file to read contents
f=open("records.dat", "rb")
n=int(input("Enter the Roll Number: "))
flag = False
while True:
try:
x=pickle.load(f)
if x[1]==n:
print("Name: ", x[0])
flag = True
except EOFError:
break
if flag==False:
print("This Roll Number does not exist")

23
24
17. WRITE A PROGRAM TO UPDATE THE MARKS OF PERTICULAR RECORD OF
STUDENT USING BINARY FILES.

import pickle
def Writerecord(sroll,sname,sperc,sremark):
with open ('StudentRecord.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,
"SREMARKS":sremark}
pickle.dump(srecord,Myfile)

def Readrecord():
with open ('StudentRecord.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'],'\t
',end='')
print(rec['SPERC'],'\t ',rec['SREMARKS'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)

25
def Modify(roll):
with open ('StudentRecord.dat','rb') as Myfile:
newRecord=[]
while True:
try:
rec=pickle.load(Myfile)
newRecord.append(rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")

newRecord[i]['SNAME']=name
newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark
found =1
else:
found=0

if found==0:

print("Record not found")


with open ('StudentRecord.dat','wb') as Myfile:
for j in newRecord:
pickle.dump(j,Myfile)

26
def main():

while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Update Records')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elifch==2:
Readrecord()
elifch==3:
r =int(input("Enter a Rollno to be update: "))
Modify(r)
else:
break
main()

27
18 WRITE A PROGRAM TO ILLUSTRATE WRITE AND READ OPERATIONS ON
CSV FILE.
import csv
# opening the CSV file for writing contents in it
myfile=open('stud.csv', mode ='w')
stuwriter = csv.writer(myfile)
n=int(input("How many records do you want to enter"))
for i in range(n):
print("Student Record",(i+1))
rno=int(input("Enter Roll No"))
nm=input("Enter Name")
m=int(input("Enter Marks"))
sturec=[rno,nm,m]
stuwriter.writerow(sturec)
myfile.close()
# opening the CSV file for reading
myfile=open('stud.csv', mode ='r',newline='\r\n')
# reading the CSV file
stureader = csv.reader(myfile)
# displaying the contents of the CSV file
for lines in stureader:
print(lines)

28
19 WRITE A PROGRAM TO IMPLEMENT PUSH() AND DISPLAY FUNCTIONS OF A
STACK USING A LIST DATA-STRUCTURE.

#IMPLIMENTATION OF STACK

def isempty(stk):
if stk==[]:
return True
else:
return False

def push(stk,item):
stk.append(item)
top=len(stk)-1

def display(stk):
if isempty(stk):
print('stack is empty')
else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])

#Driver Code

def main():
stk=[]
top=None
while True:
print('''stack operation
1. Push

29
2. Display
3.exit''')
choice=int (input('enter choice:'))
if choice==1:
item=int(input('enter item:'))
push(stk,item)
elif choice==2:
display(stk)
elif choice==3:
break
else:
print('invalid')
exit()
main()

30
20. WRITE A PROGRAM TO IMPLEMENT POP() AND DISPLAY() FUNCTIONS OF
A STACK USING A LIST DATA-STRUCTURE.

#IMPLIMENTATION OF STACK

def isempty(stk):
if stk==[]:
return True
else:
return False

def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item

def display(stk):
if isempty(stk):
print('stack is empty')
else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])

31
#Driver Code

def main():
stk=[12,34,57,89,120]
top=None
while True:
print('''stack operation
1.pop
2.display
3.exit''')
choice=int (input('enter choice:'))

if choice==1:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')

elif choice==2:
display(stk)
elif choice==3:
break
else:
print('invalid')
exit()
main()

32
33
21. INTEGRATE PYTHON WITH SQL – TO CONNECT DATABASE

import mysql.connector as sqltor


mycon=sqltor.connect(host=”localhost”, user=”root”,
password=”root”, databse=”school”)
if mycon.is_connected( ) = = False:
print(“Error connecting to MySQL database”)

else:
print(“ Connected to MySQL database”)

OUTPUT:

Connected to MySQL database

34
22. INTEGRATE PYTHON WITH SQL – TO FETH RECORDS FROM THE TABLE AND
DISPLAY IT ON THE SCREEN
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM student")

myresult = mycursor.fetchall()

for x in myresult:
print(x)

35
MYSQL

36
23. SQL: TO CREATE TWO TABLES FOR STATIONARY AND CONSUMER AND
EXECUTE THE GIVEN COMMANDS USING SQL.

i) To display the details of those Consumers whose Address is Delhi.


ii) To display the details of Stationary whose Price is in the
range of 8 to 15(Both values included).
iii) To display the ConsumerName , Address from table Consumer and
Company and Price.
from table Stationery with their corresponding matching S_ID
iv) To increase the Price of all Stationary by 2.
v) To display distinct Company from STATIONARY.

37
CREATING STATIONARY TABLE:

SQL> CREATE TABLE STATIONARY (S_ID char(5) NOT NULL PRIMARY KEY,
StationaryName char(25), Company char(5), Price int);

INSERTING RECORD/TUPLE IN STATIONARY TABLE:

SQL> INSERT INTO STATIONARY VALUES(“DP01” , “Dot Pen”, “ABC”, 10);


SQL> INSERT INTO STATIONERY VALUES(“PL02” , “Pencil”, “XYZ”, 6);
SQL> INSERT INTO STATIONERY VALUES(“ER05” , “Eraser”, “XYZ”, 7);
SQL> INSERT INTO STATIONERY VALUES(“PL01” , “Pencil”, “CAM”, 5);
SQL> INSERT INTO STATIONERY VALUES(“GP02” , “Gel Pen”, “ABC”, 15);

DISPLAYING RECORDS AFTER INSERTION:

SQL> SELECT * FROM STATIONARY;

S_ID StationaryName Company Price

DP01 Dot Pen ABC 10

PL02 Pencil XYZ 6

ER05 Eraser XYZ 7

PL01 Pencil CAM 5

GP02 Gel Pen ABC 15

CREATING CONSUMER TABLE:

SQL> CREATE TABLE CONSUMER (C_ID int , ConsumerName char(25)


Address char(25), S_ID char(5));

38
INSERTING RECORD/TUPLE IN CONSUMER TABLE:

SQL> INSERT INTO CONSUMER VALUES (01, “Good Learner”, “Delhi”,


“PL01”);
SQL> INSERT INTO CONSUMER VALUES(06,”Write Well”,”Mumbai”,”GP02”);
SQL> INSERT INTO CONSUMER VALUES(12,”Topper”,”Delhi”,”PL02”);
SQL> INSERT INTO CONSUMER VALUES(15,”Write & Draw”,”Delhi”,”PL02”);
SQL> INSERT INTO CONSUMER VALUES(15,”Write & Draw”,”Delhi”,”PL02”);

DISPLAYING RECORDS AFTER INSERTION:

SQL> SELECT * FROM CONSUMER;

i) To display the details of those Consumers whose Address is Delhi.


SQL> SELECT * FROM CONSUMER WHERE ADDRESS=”delhi”;
OUTPUT:

39
ii) SELECT * FROM STATIONARY WHERE PRICE BETWEEN 8 AND 15;

OUTPUT:

iii) SELECT CONSUMERNAME, ADDRESS, COMPANY, PRICE FROM STATIONERY,


CONSUMER WHERE STATIONERY.S_ID=CONSUMER.S_ID;

OUTPUT:

iv) UPDATE STATIONERY SET PRICE=PRICE+2; SELECT * FROM STATIONERY;

OUTPUT:

40
v) SELECT DISTINCT(COMPANY) FROM STATIONERY;

OUTPUT:

41
24. SQL: TO CREATE TWO TABLES FOR ITEM AND TRADERS AND EXECUTE THE
GIVEN COMMANDS USING SQL.

i) To display the details of all the items in ascending order of


item names (i.e IName)
ii) To display item name and price of all those items, whose price
is in the range of 10000 and 22000 (both values inclusive)
iii) To display the number of items , which are traded by each
trader. The expected output of this query should be
T01 2
T02 2
T03 1
iv) To display the Price , item name(i.e IName) and quantity(i.e
Qty) of those items which have quantity more than 150.
v) To display the names of those traders, who are either from DELHI
or from MUMBAI.

42
CREATING ITEM TABLE:

SQL> CREATE TABLE ITEM(Code int , IName char(25) , Qty int ,


Price int , Company char(25), TCode char(5));

INSERTING RECORD/TUPLE IN ITEM TABLE:

SQL> INSERT INTO ITEM VALUES(1001,”DIGITAL PAD 121”,120,


11000,”XENTIA”, “T01”);
SQL> INSERT INTO ITEM VALUES(1006,”LED SCREEN 40”,70,
38000,”SANTORA”, “T02”);
SQL> INSERT INTO ITEM VALUES(1004,”CAR GPS SYSTEM”,50,
2150,”GEOKNOW”, “T01”);
SQL> INSERT INTO ITEM VALUES(1003,”DIGITAL CAMERA 12X”,160,
8000,”DIGICLICK”, “T02”);
SQL> INSERT INTO ITEM VALUES(1005,”PEN DRIVE 32GB”,600,
1200,”STOREHOME”, “T03”);

CREATING TRADERS TABLE:

SQL> CREATE TABLE TRADERS(TCode char(5) , TName char(25), City


char(20));

INSERTING RECORD/TUPLE IN TRADERS TABLE:

SQL> INSERT INTO TRADERS VALUES(“T01”,”ELECTRONICS


SALES”,”MUMBAI”);
SQL> INSERT INTO TRADERS VALUES( “T03”,”BUSY STORE CORP”,”DELHI”);
SQL> INSERT INTO TRADERS VALUES( “T02”,”DISP HOUSE INC”,”CHENNAI”);

43
i) select * from ITEM order by IName;

OUTPUT:

ii) select IName , Price from ITEM where Price between 10000
and 22000;

OUTPUT:

iii) select TCode , count(*) from ITEM group by TCode;

OUTPUT:

44
iv) select Price , IName , Qty from ITEM where Qty>150;

OUTPUT:

v) select TName from TRADERS where City in (“DELHI”,”MUMBAI”);

OUTPUT:

45
SQL COMMANDS

46
25. SQL COMMANDS
1. CREATE DATABASE
AIM
Create a Database of name EMPLOYEE.
QUERY

SQL> CREATE DATABASE EMPLOYEE;

2. OPEN COMMAND
AIM
Open the Database using the USE command.
QUERY

SQL> USE DATA

3. CREATE TABLE
AIM
Create table EMP with specified number of rows and columns and
apply necessary constraints.
QUERY

SQL> CREATE TABLE EMP (ENO INTEGER PRIMARYKEY, ENAME VARCHAR (20)
UNIQUE,JOB VARCHAR (20) DEFAULT “CLERK”, GENDER CHAR (1) NOT NULL,
HIRE DATE, SAL FLOAT (6,2) CHECK SAL>2000,COMM INTEGER);

4. INSERT COMMAND
AIM
Insert tuples to the table EMP.

QUERY

SQL> INSERT INTO EMP VALUES(1,’KING’,’MANAGER’,’M’,’1981-11-


17’,5000,NULL);

SQL> INSERT INTO EMP VALUES(2,’BLAKE’,’MANAGER’,’M’,’1981-05-


01’,2850,NULL);

47
SQL> INSERT INTO EMP VALUES(3,’JASMIN’,’SALESMAN’,’F’,’1982-12-
09’,2450,300);

SQL> INSERT INTO EMP VALUES(4,’JONES’,’SALESMAN’,’M’,’1983-01-


12’,2975,500);

SQL> INSERT INTO EMP VALUES(5,’CLARK’,’ANALYST’,’M’,’1983-01-


23’,1250,NULL);

SQL> INSERT INTO EMP VALUES(6,’GEETHA’,’CLERK’,’F’,’1981-02-


22’,1600,NULL);

5. SELECT COMMAND
AIM
Display all employee details.
QUERY

SQL> SELECT * FROM EMP;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM

1 KING MANAGER M 1981-11-17 5000.00 NULL


2 BLAKE MANAGER M 1981-05-01 2850.00 NULL
3 JASMIN SALESMAN F 1982-12-09 2450.00 300
4 JONES SALESMAN M 1983-01-12 2975.00 500
5 CLARK ANALYST M 1983-01-23 1250.00 NULL
6 GEETHA CLERK F 1981-02-22 1600.00 NULL

AIM
Display ENO, ENAME and JOB of all Employees.
QUERY

SQL> SELECT ENO,ENAME,JOB FROM EMP;

48
OUTPUT
ENO ENAME JOB

1 KING MANAGER
2 BLAKE MANAGER
3 JASMIN SALESMAN
4 JONES SALESMAN
5 CLARK ANALYST
6 GEETHA CLERK

6. USING DISTINCT KEYWORD


AIM
Display job of employee by eliminating redundant data.
QUERY

SQL> SELECT DISTINCT JOB FROM EMP;

OUTPUT
DISTINCT JOB

MANAGER
SALESMAN
ANALYST
CLERK

7. USING WHERE CLAUSE


AIM
Display all details of employee who is having job as salesman.
QUERY

SQL> SELESCT * FROM EMP WHERE JOB=’SALESMAN’;

49
OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM

3 JASMIN SALESMAN F 1982- 2450.00 300


12-09
4 JONES SALESMAN M 1983- 2975.00 500
01-12

8. RELATIONAL OPERATOR
AIM
Display the details of employee whose name is not ‘KING’.

QUERY

SQL> SELECT * FROM EMP WHERE ENAME< >’KING’;

OUTPUT

ENO ENAME JOB GENDER HIRE SAL COMM


2 BLAKE MANAGER M 1981-05-01 2850.00 NULL
3 JASMIN SALESMAN F 1982-12-09 2450.00 300
4 JONES SALESMAN M 1983-01-12 2975.00 500
5 CLARK ANALYST M 1983-01-23 1250.00 NULL
6 GEETHA CLERK F 1981-02-22 1600.00 NULL

AIM
Display the details of employee ENO,ENAME,SAL of people whose salary
is above 2500.
QUERY

SQL> SELECT ENO,ENAME,SAL FROM EMP WHERE SAL>2500;

50
OUTPUT
ENO ENAME SAL

1 KING 5000.00
2 BLAKE 2850.00
4 JONES 2975.00

9. LOGICAL OPERATORS
AIM
Display the details of employee whose job is manager or gender is
male.

QUERY

SQL> SELECT * FROM EMP WHERE JOB=’MANAGER’ OR GENDER=’M’;

OUTPUT

ENO ENAME JOB GENDER HIRE SAL COMM


1 KING MANAGER M 1981-11-17 5000.00 NULL
2 BLAKE MANAGER M 1981-05-01 2850.00 NULL
4 JONES SALESMAN M 1983-01-12 2975.00 500
5 CLARK ANALYST M 1983-01-23 1250.00 NULL

AIM
Display the ENO, ENAME and COMM of employees with commission.

QUERY

SQL> SELECT ENO,ENAME,COMM FROM EMP WHERE COMM IS NOT NULL;

OUTPUT
ENO ENAME SAL JOB

3 JASMIN 2450.00 SALESMAN


4 JONES 2975.00 SALESMAN

51
AIM
Display the details of employees whose job is not salesman.
QUERY

SQL> SELECT * FROM EMP WHERE JOB NOT=’SALESMAN’;

OUTPUT

ENO ENAME JOB GENDER HIRE SAL COMM


1 KING MANAGER M 1981-11-17 5000.00 NULL
2 BLAKE MANAGER M 1981-05-01 2850.00 NULL
5 CLARK ANALYST M 1983-01-23 1250.00 NULL
6 GEETHA CLERK F 1981-02-22 1600.00 NULL

10. USING BETWEEN- AND CLAUSE


AIM
Display the details of employees whose salary is between 2000 and
5000.

QUERY

SQL> SELECT * FROM EMP WHERE SAL BETWEEN 2000 AND 5000;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM

1 KING MANAGER M 1981-11-17 5000.00 NULL


2 BLAKE MANAGER M 1981-05-01 2850.00 NULL
3 JASMIN SALESMAN F 1982-12-09 2450.00 300
4 JONES SALESMAN M 1983-01-12 2975.00 500

52
AIM
Display the details of employees whose salary is not between 2000
and 5000.
QUERY

SQL> SELECT * FROM EMP WHERE SAL NOT BETWEEN 2000 AND 5000;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM
5 CLARK ANALYST M 1983-01-23 1250.00 NULL
6 GEETHA CLERK F 1981-02-22 1600.00 NULL

11. CONDITION BASED ON A LIST


AIM
Display the details of employees having job as manager, salesman
and clerk.

QUERY

SQL> SELECT * FROM EMP WHERE JOB IN(‘MANAGER’,’SALESMAN’,’CLERK’);

OUTPUT

ENO ENAME JOB GENDER HIRE SAL COMM

1 KING MANAGER M 1981-11-17 5000.00 NULL


2 BLAKE MANAGER M 1981-05-01 2850.00 NULL
3 JASMIN SALESMAN F 1982-12-09 2450.00 300
4 JONES SALESMAN M 1983-01-12 2975.00 500
6 GEETHA CLERK F 1981-02-22 1600.00 NULL

53
AIM
To display the details of employees except people having job as
Salesman, Manager and Clerk.
QUERY

SQL> SELECT * FROM EMP WHERE JOB NOT


IN(‘MANAGER’,’SALESMAN’,’CLERK’);

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM
5 CLARK ANALYST M 1983-01-23 1250.00 NULL

12. CONDITION BASED ON A PATTERN MATCH


AIM
Display the details of Employee whose ENAME starts with ‘J’;
QUERY

SQL> SELECT * FROM EMP WHERE ENAME LIKE ‘J%’;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM

3 JASMIN SALESMAN F 1982-12-09 2450.00 300


4 JONES SALESMAN M 1983-01-12 2975.00 500

AIM
Display the details of Employees whose ENAME ends with ‘S’;

QUERY

SQL> SELECT * FROM EMP WHERE ENAME LIKE ‘%S’;

OUTPUT

ENO ENAME JOB GENDER HIRE SAL COMM

4 JONES SALESMAN M 1983-01-12 2975.00 500

54
AIM
Display the details of Employee whose job contains “AL” string.

QUERY

SQL> SELECT * FROM EMP WHERE JOB LIKE “%AL%”;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM
3 JASMIN SALESMAN F 1982-12-09 2450.00 300
4 JONES SALESMAN M 1983-01-12 2975.00 500
5 CLARK ANALYST M 1983-01-23 1250.00 NULL

AIM
To display the details of Employees whose ENAME contains exactly 5
letters.
QUERY

SQL> SELECT * FROM EMP WHERE ENAME LIKE “-----“;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM

2 BLAKE MANAGER M 1981-05-01 2850.00 NULL


4 JONES SALESMAN M 1983-01-12 2975.00 500
6 GEETHA CLERK F 1981-02-22 1600.00 NULL

AIM
To display the details of Employees whose ENAME contains at least
6 characters.
QUERY

SQL> SELECT * FROM EMP WHOSE ENAME LIKE “------%”;

55
OUTPUT

ENO ENAME JOB GENDER HIRE SAL COMM

3 JASMIN SALESMAN F 1982-12-09 2450.00 300


6 GEETHA CLERK F 1981-02-22 1600.00 NULL

13. SEARCH FOR NULL


AIM
Display ENO,ENAME,COMM from Employee who doesn’t have commission.

QUERY

SQL> SELECT ENO,ENAME,COMM FROM EMP WHERE COMM IS NULL;

OUTPUT
ENO ENAME COMM

1 KING NULL
2 BLAKE NULL
5 CLARK NULL

AIM
Display the ENO,ENAME and COMM of employees with commission.

QUERY

SQL> SELECT ENO,ENAME,COMM FROM EMP WHERE COMM IS NOT NULL;

OUTPUT
ENO ENAME COMM

3 JASMIN 300
4 JONES 500

56
14. SORTING RESULTS BY ORDER BY
AIM
Display the details of Employees according to the alphabetical
order of their ENAME;
QUERY

SQL> SELECT * FROM EMP ORDER BY ENAME ASC;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM

2 BLAKE MANAGER M 1981-05-01 2850.00 NULL


5 CLARK ANALYST M 1983-01-23 1250.00 NULL
6 GEETHA CLERK F 1981-02-22 1600.00 NULL
3 JASMIN SALESMAN F 1982-12-09 2450.00 300
4 JONES SALESMAN M 1983-01-12 2975.00 500
1 KING MANAGER M 1981-11-17 5000.00 NULL

AIM
Display the details of Employee by descending order of ENAME.

QUERY

SQL> SELECT * FROM EMP ORDER BY ENAME DESC;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM

1 KING MANAGER M 1981-11-17 5000.00 NULL


4 JONES SALESMAN M 1983-01-12 2975.00 500
3 JASMIN SALESMAN F 1982-12-09 2450.00 300
6 GEETHA CLERK F 1981-02-22 1600.00 NULL
5 CLARK ANALYST M 1983-01-23 1250.00 NULL
2 BLAKE MANAGER M 1981-05-01 2850.00 NULL

57
AIM
Display the details of Employee by descending order of ENAME and
SAL in ascending order.
QUERY

SQL> SELECT * FROM EMP ORDER BY ENAME DESC, SAL ASC;

OUTPUT

ENO ENAME JOB GENDER HIRE SAL COMM

1 KING MANAGER M 1981-11-17 5000.00 NULL


4 JONES SALESMAN M 1983-01-12 2975.00 500
3 JASMIN SALESMAN F 1982-12-09 2450.00 300
6 GEETHA CLERK F 1981-02-22 1600.00 NULL
5 CLARK ANALYST M 1983-01-23 1250.00 NULL
2 BLAKE MANAGER M 1981-05-01 2850.00 NULL

15. SIMPLE CALCULATIONS


AIM
Perform simple calculations.

QUERY

SQL> SELECT 5*7 FROM DUAL;

OUTPUT
5*7

35

16. DATE FUNCTIONS


AIM
Display the date with time.
QUERY

SQL> SELECT SYSDATE() FROM DUAL;


58
OUTPUT
SYSDATE()

2021-08-19 10:34:20

AIM
Display the current system date.
QUERY

SQL> SELECT CURDATE();

OUTPUT
CURDATE()

2021-08-19

AIM
Display current date and time.

QUERY

SQL> SELECT NOW();

OUTPUT
NOW()

10:34:20

AGGREGATE FUNCTIONS

17. SUM FUNCTIONS


AIM
Display the sum of salary of employees having job as Manager.

QUERY

SQL> SELECT SUM(SAL) FROM EMP WHERE JOB=’MANAGER’;

59
OUTPUT
SUM(SAL)

7645.00

18. GROUP BY
AIM
Display the total salary of Employees in each Department
QUERY
SQL> SELECT JOB<SUM(SAL) FROM EMP GROUP BY JOB;

OUTPUT
JOB SUM(SAL)
ANALYST 1250.00
CLERK 1600.00
MANAGER 7850.00
SALESMAN 5245.00

AIM
Display the total Salary of Female.
QUERY
SQL> SELECT GENDER<SUM(SAL) FROM EMP GROUP BY GENDER

GENDER SUM(SAL)
F 4050.00
M 12075.00

19.USING HAVE CLAUSE


AIM
Display the sum of salary in each job whose number of employees
more than 2.
QUERY
SQL> SELECT JOB<SUM(SAL) FROM EMP GROUP BY JOB HAVING
COUNT(*)>=2;
60
OUTPUT
JOB SUM(SAL)
MANAGER 7850.00
SALESMAN 5425.00

AIM
Display Eno,Ename,Job and increase salary by 1000 whose job is
Salesman.
QUERY
SQL> SELECT ENO,ENAME,JOB,SAL+1000 FROM EMP WHERE JOB=’SALESMAN’;

OUTPUT
ENO ENAME JOB SAL+1000
3 JASMIN SALESMAN 3450.00
4 JONES SALESMAN 3975.00

20.PUTTING TEXT IN QUERY


AIM
Display Eno,Ename,Job, modify Salary into Sal*100 and add a
column’$’ in the Employee table;
QUERY
SQL> SELECT ENO.ENAME,JOB,SAL*100,”$” FROM EMP;

OUTPUT
ENO ENAME JOB SAL*100 $
1 KING MANAGER 500000 $
2 BLAKE MANAGER 285000 $
3 JASMIN SALESMAN 245000 $
4 JONES SALESMAN 297500 $
5 CLARK ANALYST 125000 $
6 GEETHA CLERK 160000 $

61
21.CREATING TABLE FROM EXISTING TABLE
AIM
Create a Salary Table from the base table(Employee).
QUERY
SQL> CREATE TABLE SALARY1 AS(SELECT ENO,ENAME,SAL FROM EMP WHERE
COMM IS NULL);

SQL> SELECT * FROM SALARY1;

OUTPUT
ENO ENAME SAL
1 KING 5000
2 BLAKE 2850
5 CLARK 1250
6 GEETHA 1600

22.UPDATE COMMAND
AIM
Update the salary of an employee from EMP table.
QUERY
SQL> UPDATE EMP SET SAL=2000 WHERE ENO=2;

SQL> SELECT * FROM EMP;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM
1 KING MANAGER M 1981-11-17 5000 NULL
2 BLAKE MANAGER M 1981-03-01 2850 NULL
3 JASMIN SALESMAN F 1982-12-09 2450 300
4 JONES SALESMAN M 1983-01-12 2975 300
5 CLARK ANALYST M 1983-01-23 1250 NULL
6 GEETHA CLERK F 1981-02-22 1600 NULL

62
AIM
Display the table Salary1 after Updating the Salary as 2000 whose
Eno is 2.
QUERY
SQL> UPDATE SALARY1 SET SAL=2000 WHERE ENO=2;

SQL> SELECT * FROM SALARY1;

OUTPUT
ENO ENAME SAL
1 KING 5000
2 BLAKE 2000
5 CLARK 1250
6 GEETHA 1600

AIM
Update the salary as 200 and Comm as 200 whose Eno is 1 and
Display it.
QUERY
SQL> UPDATE EMP SET VAL=2000,COMM=200 WHERE ENO=1;

SQL> SELECT * FROM EMP;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM
1 KING MANAGER M 1981-11-17 5000 200
2 BLAKE MANAGER M 1981-03-01 2000 NULL
3 JASMIN SALESMAN F 1982-12-09 2450 300
4 JONES SALESMAN M 1983-01-12 2975 300
5 CLARK ANALYST M 1983-01-23 1250 NULL
6 GEETHA CLERK F 1981-02-22 1600 NULL

63
23.USING EXPRESSIONS IN UPDATE
AIM
Update the salary with current Salary+1000 whose job is Salesman
and displat it.

QUERY
SQL> UPDATE EMP SET SAL=SAL+1000 WHERE JOB=’SALESMAN’;

SQL> SELECT * EMP;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM
1 KING MANAGER M 1981-11-17 2000 200
2 BLAKE MANAGER M 1981-03-01 2000 NULL
3 JASMIN SALESMAN F 1982-12-09 3450 300
4 JONES SALESMAN M 1983-01-12 3975 300
5 CLARK ANALYST M 1983-01-23 1250 NULL
6 GEETHA CLERK F 1981-02-22 1600 NULL

24.UPDATING TO NULL VALUES


AIM
Update the Salary of an employee having job as Clerk to null.
QUERY
SQL> UPDATE EMP SET SAL=NULL WHERE JOB=’CLERK’;

SQL> SELECT * FROM EMP;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM
1 KING MANAGER M 1981-11-17 2000 200
2 BLAKE MANAGER M 1981-03-01 2000 NULL
3 JASMIN SALESMAN F 1982-12-09 3450 300
4 JONES SALESMAN M 1983-01-12 3975 300
5 CLARK ANALYST M 1983-01-23 1250 NULL
6 GEETHA CLERK F 1981-02-22 NULL NULL

64
25.DELETE COMMAND
AIM
Remove the details of Employee whose Salary is above 3000 and
Display it.

QUERY
SQL> DELETE FROM SALARY1 WHERE SAL>3000;

SQL> SELECT * FROM SALARY1;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM
2 BLAKE MANAGER M 1981-03-01 2000 NULL
5 CLARK ANALYST M 1983-01-23 1250 NULL
6 GEETHA CLERK F 1981-02-22 NULL NULL

26.VIEW COMMAND
AIM
Create a table COMM1 containing EMPNO,EMPNAME,EJOB, SALARY,
HIRE,GEN,COMM and COMM is NULL and display it.
QUERY
SQL> CREATE VIEW COMM1(EMPNO,EMPNAME,EJOB,GEN,HIRE,SALARY,COM)

AS SELECT * FROM EMP WHERE COMM IS NULL;


SQL> SELECT * FROM COMM1;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM
2 BLAKE MANAGER M 1981-03-01 2000 NULL
5 CLARK ANALYST M 1983-01-23 1250 NULL
6 GEETHA CLERK F 1981-02-22 NULL NULL

65
AIM
Create the sample to display the detail of employee like
EMPNO,EMPNAME,SALARY and whose COMM is NULL and Display it.
QUERY
SQL> CREATE VIEW SAMPLE(EMPNO,EMPNAME,SAL) AS SELECT
ENO,ENAME,SAL+100 FROM EMP WHERE COMM IS NULL;

OUTPUT
ENO ENAME SAL
2 BLAKE 2000
5 CLARK 1250
6 GEETHA NULL

27.BUILT-IN FUNCTIONS
AIM
Convert the given string into Lower Case.
QUERY
SQL> SELECT LOWER(“HELLO”) FROM DUAL;

OUTPUT
LOWER(“HELLO”)
hello

AIM
Convert the given string into Upper case.
QUERY
SQL> SELECT UPPER(“hello”) FROM DUAL;

66
OUTPUT
LOWER(“HELLO”)
HELLO

AIM
Display the sub string of the given string.

QUERY
SQL> SELECT SUBSTR(“POINTER”,3,2) FROM DUAL;

OUTPUT

SUBSTR(“POINTER”,3,2)

IN

28.DDL COMMANDS
ALTER COMMAND
AIM
Remove column Salary from salary table and display the table
QUERY
SQL> ALTER TABLE SALARY1 DROP COLUMN SAL;

SQL> SELECT * FROM SALARY1;

OUTPUT
ENO ENAME
2 BLAKE
5 CLARK
6 GEETHA

67
AIM
Add a new Column AGE to Employee table and Display it.
QUERY
SQL> ALTER TABLE EMP ADD(AGE INT(2));

SQL> SELECT * FROM EMP;

OUTPUT
ENO ENAME JOB GENDER HIRE SAL COMM AGE
1 KING MANAGER M 1981-11-17 2000 200 NULL

2 BLAKE MANAGER M 1981-03-01 2000 NULL NULL

3 JASMIN SALESMAN F 1982-12-09 3450 300 NULL

4 JONES SALESMAN M 1983-01-12 3975 300 NULL

5 CLARK ANALYST M 1983-01-23 1250 NULL NULL

6 GEETHA CLERK F 1981-02-22 NULL NULL NULL

68
AIM
Modify the size of the column ENAME into CHAR(25) using ALTER
command and display the table structure.
QUERY
SQL> ALTER TABLE EMP MODIFY ENAME CHAR(25);

SQL> DESCRIBE EMP;

OUTPUT
FIELD TYPE NULL KEY DEFAULT EXTRA
ENO int(11) NO PRI NULL
ENAME char(25) YES UNI NULL
JOB varchar(25) YES CLERK
GENDER char(1) NO NULL
HIRE date YES NULL
SAL float(6,2) YES NULL
COMM int(11) YES NULL
AGE int(2) YES NULL

AIM
Add Primary key constraints to the column ENO in the SALARY1 table
and Describe it.
QUERY
SQL> ALTER TABLE SALARY1 ADD PRI03Y KEY(ENO);

SQL> DESCRIBE SALARY1;

OUTPUT
ENO Int(11) NO PRI NULL
ENAME Varchar(20) YES NULL

69
SQL JOINS

70
JOINS
AIM
Display Cid, Ename, Pid, Pname, Manufac From client and Product
table whose having matching PID.
QUERY
SQL> SELECT CID,ENAME,CLIENT.PID,PNAME,MANUFAC

FROM CLIENT,PRODUCT WHERE CLIENT PID=PRODUCT.PID;

OUTPUT

CID ENAME PID PNAME MANUFAC

16 DREAMS TP01 TALCOM POWDER LAK

1 COSMETIC SHOP FW05 FACE WASH ABC

6 TOTAL HEALTH BS01 BATH SOAP ABC

12 LIVE LIFE SH06 SHAMPOO XYZ

15 PRETTY WOMAN FW12 FACE WASH XYZ

71
INNER JOIN

The INNER JOIN keyword selects records that have matching


values in both tables.

AIM
IMPLIMENT INNER JOIN ON TABLES

CUSTOMER TABLE

CustomerID CustomerName ContactName Country


1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico

3 Antonio Moreno Taquería Antonio Mexico


Moreno

ORDER TABLE
OrderID CustomerID OrderDate
10308 2 18-09-1996
10309 37 19-09-1996
10310 77 20-09-1996

QUERY
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
OUTPUT:

OrderID CustomerName OrderDate


10308 Ana Trujillo Emparedados y helados 9/18/1996
10365 Antonio Moreno Taquería 11/27/1996
10383 Around the Horn 12/16/1996
10355 Around the Horn 11/15/1996
10278 Berglunds snabbköp 08-12-1996

72
OUTER JOIN
The LEFT JOIN keyword returns all records from the left table
(table1), and the matching records (if any) from the right table
(table2).

AIM
IMPLIMENT OUTER JOIN ON TABLES

QUERY

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

OUTPUT:

The LEFT JOIN keyword returns all records from the left table
(Customers), even if there are no matches in the right table
(Orders).

73
RIGHT JOIN
The RIGHT JOIN keyword returns all records from the right
table (table2), and the matching records (if any) from the left
table (table1).

AIM
IMPLIMENT RIGHT JOIN ON TABLES

QUERY

SELECT Orders.OrderID, Employees.LastName, Employees.FirstName


FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;

OUTPUT:

The RIGHT JOIN keyword returns all records from the right
table (Employees), even if there are no matches in the left table
(Orders).

74
CROSS JOIN

The CROSS JOIN keyword returns all records from both tables
(table1 and table2).

AIM
IMPLIMENT CROSS JOIN ON TABLES

QUERY

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
CROSS JOIN Orders;
OUTPUT:

The CROSS JOIN keyword returns all matching records from both
tables whether the other table matches or not. So, if there are
rows in "Customers" that do not have matches in "Orders", or if
there are rows in "Orders" that do not have matches in "Customers",
those rows will be listed as well.

If you add a WHERE clause (if table1 and table2 has a


relationship), the CROSS JOIN will produce the same result as
the INNER JOIN clause:

75

You might also like