0 ratings0% found this document useful (0 votes) 52 views18 pagesComputer Science Hotel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
INFORMATICS RAC
“~
62 — Text/String Functions
‘The string functions of MySQL can manipulate the text string in many ways. Some com monly
used string functions are being discussed below.
1. CHAR( )
This function returns the character for each integer passed.
=
CHAR(valuei [, value2 ...])
© retums a string made up of the ASCII representation of the decimal value list.
j © Strings in numeric format are converted to a decimal value.
Null values are ignored.
| Argument types : Integers Return Value : String
EXAMPLE EN) Write a query to create « string from the ASCII values 70, 65, 67, 69.
SOLUTION mysql> SELECTCHAR (70, 65, 67, 69) ;
1 row in set (0.00 sec)
Even if an argument contains a fractional value or a string type number, they are considered as
integers. Consider the following example.
EXAMPLE EI) Write a query to cea String from the ASCII values 65, 67.3, 68.3"
SOLUTION mysql> SELECT CHAR (65, 67.3, '69.3° ) ;
ey
“I char (65, 67.3, '69.3') |
—
| ACE
ane
1 row in set, 1 warning (0.00 sec)
‘See the fractional value 67.5 is ieated as 67
{character C) and the string type number ‘69 5
2. CONCAT
CONCAT (stri, str2, ...)
o Retums argument str1 concatenated with argument str2.
Argument types :String, String Return value : String,INFORMATICS PRACTICES ~ x
5. UPPER / UCASE
This function converts the given string into upper case.
Se
—UPPER(str) -UCASE(str)
© Returns argument str, with all letters uppercase.
© The return value has the same data type as the argument str.
Argument type : String Return value : String
EXAMPLE [lU) Convert and display string ‘Large’ into uppercase.
SOLUTION
mysql> SELECT UPPER('Large') “Uppercase” ; Hiicarcase :
Or pees
mysql> SELECT UCASE( 'Large') "Uppercase" ;6, LTRIM
This function removes leading spaces i.e, spaces from the left of given string.
=
LTRIM(str)
Removes spaces from the left of argument str with initial characters removed.
Argu
ent type : String Return val
String
EXAMPLE [IDI Write a query to remove leading spaces of string’ RDBMS MySQL’.
SOLUTION
mysql> SELECT LTRIM(' RDBMS MySQL") ;
i oe
| Ttrim(t RDBMS MysQL') |
Se ‘that LTRIM( ) removes only the leading
spaces. Spaces in the middle or trailing spaces
remain untouched with LTRIM( )
1 row in set (0.05 sec)
SELECT INSTR( "CORPORATE FLOOR’, OR’) AS Instring ;
1 row in set (0.03 sec)5. SQRT
This function returns the square root of given number.
=
SQRT(n)
© Returns square root of argument n. The value m cannot be negative.
© SQRT returns a “real” result.
Argument type : Numeric Return value : NumericINFORMATICS PRACTICES _
-
EXAMPLE Find out the square root of value 26,
SOLUTION
mysql> SELECT SQRT(26) "Square root" ;
tis is square rot of 26
6. TRUNCATE
This function returns a number with some digits truncated.
TRUNCATE(n, m)
‘© Returns value of argument m truncated to argument m decimal places ;
© if argument m is given as 0 places, m can be negative to truncate (i.e., make zero) m digs
left of the decimal point.
Argument type : Numeric, Numeric
EXAMPLE [BEE Tromcate value 15.79 t0 1 decimal place.
SOLUTION
mysql> SELECT TRUNCATE(15.79, 1) “Truncate” ;
Return value : Numeric
EXAMPLE BERD Trancate value 1579 tenga
SOLUTION
imyegl> SELECT TRUWCATE(25.79, -2) “truncata ,aremmracrrercammmmmmmmmmns ACERT
NCERT Chopter 1 : Querying and SQL Functions
A. Answer the foil
‘Ans. (a) RDBMS is short for the term “Relational Database Management Sys! m’. An RDBMS is a
DBMS designed specifically for relational databases, the databases that store data in a structured
format, using rows and columns,
‘Two popular RDBMS are : MySQL, Oracle
3. Consider the following table named “Product”, showing details of products being sold in a grocery shop.
question + (a) Define RDBMS, Name arry two RDBMS software
[ Peode PName uPrice ‘Manufacturer
Pol WashingPowder 120 Surf
po2 | ToothPaste 54 | Colgate
Pos. Soap 2B Lux
P04 —_| ToothPaste 65 —_| Pepsodant
pos | Soap 38. Dove
P06___| Shampoo 245 Dove
(a) Write SQL queries for the following :
(i) Create the table Product with appropriate data types and constraints.
(Gi), Identify the primary key in Product.
(iii) List the Product Code, Product name and Price in descending order of their Product Name. If PName
is the same then display the data in ascending order of Price. ie mate
(iv) Add a new column Discount to the table Product.
(0) Calculate the value of the discount in the table Product as 10 per
er cent of the UPrice for all those
products where the UPrice is more than 100, otherwise the discount a feo
(vi) Increase the price by 12 per cent for all the eproducts manufactured by Dove.
(vif) Display the total number of products manufactured by each manufacturerChapter 5: MYSQL SQL REVISION TOUR
(0) Write the outputs) produced by executing the following queries on the basis of the information given above
tn the table Product :
(SELECT PName, Average(UPrice) FROM Product GROUP BY Pname;
(i) SELECT DISTINCT Manufacturer FROMProduct ;
‘SELECT COUNT (DISTINCT PName) FROM Product;
(iv) SELECT PName, MAX(UPrice), MIN(UPriice) FROM Product GROUP BY PName;
Ans.
@ CREATE TABLE Product ( (i) PCode
PCode CHAR (4) PRIMARY KEY,
PNameVARCHAR(30) NOT NULL,
Price FLOAT,
Manufacturer VARCHAR(3@) ) ;
(ii) SELECT PCode, PName, UPrice (jo) ALTER TABLE Product
FROM PRODUCT ‘ADD COLUMN Discount Float ;
ORDER BY PNamedesc, UPriceasc;
(©) mysql> UPDATE Product.
-> SET Discount = @.1@ * UPrice
-> WHERE UPrice> 100;
Now the table will be like :
mysql> SELECT * FROM PRODUCT
| Pcode | PNane | price | Manufacturer | Discount |
| P01 | WashingPowder | 120 | Surf 1 wt
| P02 | ToothPaste | 54 | Colgate | Nun 4
| P03 | Soap 1 25 | tux qi mon}
| P04 | ToothPaste | 65 | Pepsodant } oun 4
1 P05 1 Soap 1 38 | Dove 1 wun 4
1 P06 | Shampoo i 245 | dove Hiieeialiey
(i) mysql> UPDATE Product
> SET UPrice = UPrice + UPrice * 0.12
=> WHERE Manufacturer = "Dove' ;
Now the table will be like :
yeqi> SELECT * FROM PRODUCT ;
| Discount |
surt 1 12
'
Colgate 1 wun
Lux } urn 1
Pepsodant 1 un 1
Dove tun 1
Dove i eaINFORMATICS PRACTICES
(wi) mysql> SELECT Manufacturer, Count (Pcode) FROM Product,
=> GROUP BY manufacturer
1
.
1 sure
1 Colgate
1 Lex
| Pepsodant
:
| PName | avg(uPrice) ' \ Manufacturer |
| WashingPowder | 120 1
| ToothPaste 1 59.51
1 Soap | 33. 7800006864551 |
{shampoo | 274,3999938964844 |
)
| CoUNT(DISTINCT Pane) — |
1
@)
' | mrw(verice) |
+ q .
| WashingPoweer | 10 1 cae
| Tootnpeste ! 1 aut
| soap \ sz.36 1 aa
|, Sharpoo ' 2.41 ee
GLOSSARYon computes the average of given data,
“AVG( [DISTINCT | ALL] n)
average value of parameter(s)
type : Numeric Return value : Numeric
Caleulate average salary of all employees listed in
table empl.
‘mysql> SELECT AVG(sal) “Average”
FROM empl 5
| Average
oa
| 2073.928571
1 row in set (0:Chapter 7 : QUERYING USING SQL
4, MIN
This function returns the minimum value from a given column or expression.
MIN( [DISTINCT | ALL] expr)
4 Returns minimum value of expr.
Argument type ; Numeric Return value : Numeric
EXAMPLE [A] Display the Joining date of seniormost employee.
SOLUTION 1 Minimum Hire Date |
mysql> SELECT MIN(hiredate) “Minimum Hire Date” 1 1990-12-1 1
FROM empl ; os
1 row in set (0.06 sec)
5. SUM
This function retums the sum of value in a given column or expression.
SUM( [DISTINCT | ALL] n)
‘4 Returns sum of values of n.
Argument type : Numeric—_— ~~ oy
JOINS AND SET OPERATIONS GAT
’
ing the total order umount for part “Road Wike
SELECT SUM (ord. quantity * pr.price) ‘Total Amount’
PROM order's oF
WHERE ord. partum » pr. partnum
AND pr. description = ‘Road Bike’ ;
°
solution
parts pr
ont onder dts of parts having description Tike “Roud
: ution. SELECT? FROM orders
WHERE partum = (SELECT partum
FROM parts
WHERE description LIKE ‘Roadx?) ;
11 Ina Database Company, there are tro tables given below :
Table :SALES Table : LOCATION
[Sussman NAME sates | Locarionio | | _LOcATIONID | LOCATIONNAME
si__ [ANITA SINGH ARORA] 250000 _| 102 101__| Dethi
2 |YP.SINGH 1300000 | 101 102___| Mumbai
s3_|TINA JAISWAL 1400000 | 103, 103 Kolkata
‘St |GURDEEP SINGH 1250000 | 102 104 | Chennai
ss_|SIMIFAIZAL 1450000 | 103
Write SQL queries for the following
( To display SalesmantD, names of salesmen, LocationID with corresponding location names
{G Todisplay names of salesmen, sales and corresponding location names who have achieved Sales more
‘han 1300000.
(ii), To display names of those salesmen who have ‘SINGH in their names.
(io) Identify Primary key in the table SALES. Give reason for your choice.
{&) Write SQL command to change the LocationtD to 104 of the Salesman with ID as S3 in the table
‘SALES’.
Solution,
(SELECT SALESHANID, NAME, LOCATIONID, LOCATIONNAME
FROM SALES S, LOCATION L
WHERE S. LOCATIONID = L.LOCATIONID 5
(il) SELECT NAME, SALES, LOCATIONNANE
FROM SALES S, LOCATION L
WHERE S. LOCATIONID = L. LOCATIONID AND SALES > 1300000 ;
(ii) SELECT NAME
FROM SALES
WHERE NAME LIKE "SINGHK' ;
(iv) Primary Key : SALESMANID _—_—Reason, It uuniquely identifies all ROWSin the table and
does not contain empty/zero or null values.
[CBSE 00 15]
(0) UPDATE SALES
SET LOCATIONID = 104
WHERE SALESMANID = 'S3' ;INFORMATICS, Pop
42 Pea thetaheee Madrytenes, Mere are thew tables with the following data Write MySOL. queric f
totick en terse! on Ticket Details and AgentDetails : Tang
Table: TieketDetails Table : Agent
{2 To display Tarde, Name and Aname of all the records where the number of tickets sold is more t
(@) To display total number of tickets booked by agent “Mr. Ayush”.
(G2) To display Acade, Aname and corresponding Teode where Aname ends with "k”.
‘Soluton.
( Select Teode, Name, AName (ii) Select Count(*)
FromTicketDetails TD, AgentDetails AD —FromTicketDetails TD, AgentOetails =
Where TD.A_Code = AD.Acode Where TD.A_Code = AD. Acode
AND Tickets >5 5 AND AName = "Mr. Ayush” ;
(ii) Select Acode, AName, Tcode
From TicketDetails TD, AgentDetails AD
Where TD.A_Code = AD.Acode
‘AND AName Like "XK
ee ae ereq
IOMATKS PCTS |
n
32, Falling SQL query i give ERROR, State the room
SELECT * FROM venue
UNTON
SELECT elty FROM veoued}
Solution, The reason for error is that the two SELECT queries in the given SQL slater
"union-compatile, For two queries to be union-compatible, they both must have
type of columns in their select lists,
23. Consider the flowing query. Will it pratuce error? Why / Why not?
SELECT department_id, department_nane
FROM departments
WHERE department_id <= 30
UNION
‘SELECT department_id, department_nane
FROM departments
WHERE departwent_id >= 20;
Solution. The above query will produce no error as their SELECT lists are fully compatible and iti
Possible to UNION rows from the same table.
24 Write an SQL query that lists the common cites in too match-schedule tables namely Scheduled and
Schedule2.
Solution.
‘SELECT city FROM schedule1
INTERSECT
SELECT city FROM schedule2 ;
25, Consider the fellowing query. Which SQL set operator is being simulated by it?
‘SELECT id FROM t1
LEFT 30IN t2
USING (id)
WHERE t2.id IS MULL ;
Solution. The given query is implementing MINUS operator.
atY nop
number
and
ACERT
NCERT Chapter 1 ; Querying and SQL Functions
Answer the flowing questions:
(@_ What do you understand by Cartesian Product?
Ans.
(2) A Cartesian product combines the tuples of one relation with all the tuples ofthe other relation. It
{s created when two tables are joined without any join condition,
5. Consider the following tables Student and Stream in the Streams_of Students databese. The primary key of he
AdiNo (admission
: Sa
ese eet fre nee one The primary key oftheyo1ns AND SET OPERATIONS
8
owt
‘Student Table
Name
Jay NULL
Aditya $03
Diksha S01
Jasqueen 02
Vedika Sol
Ashpreet $03
Write SQL queries for the following
(a) Create the database Streams_Of Students,
(0) Create the table Student by choosing appropriate data types based on the data given in the table.
(©) enti the Primary keys from tables Student and Stream. Also, identify the foreign key from the table Stream.
(@ Jay has now changed his stream to Humanities, Write an appropiate SQL query to reflec this change.
(©) Display the names of students whose names end with the character ‘a’ Also, arrange the students in
alphabetical order.
() Display the names of students enrolled in Science and Humanities stream, ordered by student name in
alphabetical order, then by admission number in ascending order (for duplicating names)
(@) List the number of students in each stream having more than 1 student,
(i) Display the names of students enrolled in different streams, where students are arranged in descending
onder of admission number.
(@) Show the Cartesian product on the Student and Stream table, Also mention the degree and cardinality
produced after applying the Cartesian product.
@) Add ¢ new column “TeacherIncharge” in the Stream table. Insert appropriate data in each row.
() List the names of teachers and students.
© I Cartesian product is again applied on Student and Stream tables, what wil be the degree and cardinality
ofthis modified table?
Ans.
(@) _ mysql>CREATE DATABASE Streams_of_Students ;
NOTE Before atempeing the following questions, we opened the database created above by giving command as
mysql> use Streans_of Students ;
: (©) Creating Stream table with data :
Create Table Stream ( 1
StCodechar(4) primary key,
Stream varchar (30)
%
Insert into Stream Values ( ‘S@1'," Science’ );
Insert into Stream Values ( ‘S@2', ‘Commerce’ );
Insert into Stream Values ( ‘S03’, ‘Humanities’ );
Creating Student table with data :
mysql > Create Table Student (
-> AdmNoint primary key,
=> Name varchar(25),
=> StCodechar(4) references Stream(stcode)
Os‘Tnuert Anto Student values (211, '28y', NULL)
“Insert into Student Values (241, 'Aditya’, 'S03');
Insert into Student Values (298, ‘Diksha’, 'S01");
Insert into Student Values (333, ‘Jasqueen’, 'S02");
Insert into Student Values (356, 'Vedika’, 'S01');
Insert into Student Values (380, ‘Ashpreet’, 'SB3");
{@) Since StCode of Humanities is $03, we can update Student table as :
‘mysql> UPDATE Student
> SET StCode = 'S83"
> WHERE nane = "Jay' 5
(@ mysql> SELECT * FROM student.
=> WHERE name LIKE "ka"
=» ORDER BY name ;
1 namo 1 1 secede |
1 241 | Aditya | 02 t
{290 | Diksha 1 so1 1
1356 4 veaika 1 501 i
) mysql> SELECT nane, stream FROM Student, stream
~> WHERE student. stcode = strean,stcode
22MO streanIN (Sclnce!,‘Humaniies’)_
> ORDERBY nane, adano ;
MOM,
™Joins AND SET OPERATIONS 455
mysql> SELECT Adnno, name, stream FROM student, stream
=> WHERE student .stcode » stream, stcode
=> ORDER BY admnodesc 5
ao | Ashpreet | Humanities |
gs6 | Vedika | Betence |
333 | Jasqueen | Commerce |
290 | Diksha | Setence |
2a | Aditya | Humanities |
air vay | Humanities 1
| AdmNo | Name | Stcede | stcode | stream 1
12a 1 gay } $03, | sot. 1 Science 1
1 211 1 say 1803 | 502 | Commerce 1
} 2a 1 gay | $03) | so3. | Humanities |
| 241 [Aditya = 1503, 1 S011 Science 1
| 241 1 Aditya 1803 | $02 | Commerce 1
| 241 1 Aditya | 1/503) | | 503, | Humanities |
| 290 | vaxsma 1 S01!) Son. 1 setence 1
| 290 { Diksha © 1 S01 | 502, | commerce
| 290 1 Diksha | $01, 1/503 | Humanities |
| 333 |} gasqueen 1502/1 5011 Science 1
| 333 1 Jasqueen 1 $02) || 502. | Commerce 1
1 333 1 gasqueen | 502 | S03. 1 Humanities |
| 356 1 Vedixa 1 801, 1 $01, 1. Science 1
| 356 { Vedixa 1 501 | 502 1 commerce |
| 386 1 Vedixe 1 $01.) 1'303./ 1) Rumanities |
1 380 1 Ashpreet) | 503 | 1501) 1, Seience 1
1 380 1 Ashpreet 1 503, 1 $02, | Commerce |
1380 1 Ashpreet 1 503 | { $03. | Humanities |
Degree : 5 (degree of table student (3) + degree of table stream (2))
Cardinality ; 18 (cardinality of table student (6) x cardinality of table stream (3))
@ mysql > ALTER TABLE stream
~> ADD COLUMN TeacherInchargevarchar(3@) ;
Query OK, @ rows affected (8.03 sec)
Records: @ Duplicates: @ Warnings: 0
mysql> UPDATE stream
~> SET TeacherIncharge = “Ananya Kant*
+> WHERE stream = 'Science’ 5
Query 0K, 1 row affected (2.01 sec)
Rows matched: 1 Changed: 1 Warnings: @
i iERMINE, ty,
> OATH streae :
eer Teacher Incharge © ‘Jomegh Turner
“CHE stream» “Commerce” ;
Query Or, 1 row affected (4.01 466)
Kows matched: 1 Changed: 1 warnings: 6
(mysql> POATE stream
=) SET Teacher Inchar ge © ‘Stuthean C111"
=» WEPE stream = ‘rumanities’ ;
Gury OF, Lom affected (4.01 sec)
fows matched: 1 Changed: 1 warnings: 6
ysl > SELECT * FHM Streca ;
hy wysGl > SELECT nase, Teacher incharge FHM student, stream
9 WERE student. stcode = streas.stcode 5
th dhe exedinaity fcaresian product will remain the same as no new row ia added, however, te
expec A cartesian product will now be 6 ( as one column is addled to the stream tab
GLOSsaAry
eee