fal Nad
STRUCTURED
QUERY LANGUAGE
Structured Query Language (SQL) is the most popular query language used by Coo
major relational database management systems such as MySQL, ORACLE, S% CHAPTER CHECKLIST
SQL Server, etc. SQL is easy to learn as the statements comprise of descriptive
english words and are not case sensitive, 717
SQL provides statements for defining the structure of the data, manipulating
data in the database, declaring constraints and retrieving data from the database
in various ways, depending on your requirements. .
SQL provides variety of tasks such as
+ Querying data. °
+ Creating, replacing, altering and dropping tables. °
+ Inserting, updating and deleting rows in a table. ®
+ Controlling access to the database.” acl
+ Guaranteeing database consistency and integrity.
Advantages of SQL
+ SQL is portable It is not platform dependent, it can be used in all types of
devices; PCs, laptops and even mobile phones also, .
+ High speed SQL queries can be used to retrieve large amount of records from
a database quickly and efficiently,
+ Eagy to lea and understand SQL generally consists of english language
statements and ic is very easy to learn and understand,
+ SQLs used for relational database SQL is widely used for relational database,
SQL Statements
SQL Data Types
DDLStatements/Commands
DML Statements/Commands|
Working with Null Values
Aggregate Functions
Group By Statement
Having Clause
Joinqured Query Language
ge
ats as both programming language and interactive
seme SQL can do both the jobs of being a
ey seaming language as well asan interactive language
f
pitpesame CE, :
Seenserer language SQL. provides client-server
rretut. Ics used for linking front end computers
aback end databases.
pepo abet based programming With theemergence of
abject based programming, object storage capabilities are
ded to rational database
pisadvantages of SQL.
pificulty in interfacing. Interfacing a SQL database is
pie complex than adding a few lines of code.
| More features implemented in proprietary way Although
sQL databases confirm to ANSI and ISO standards,
some databases go for proprietary extensions to standard
SOL to ensure vendor lock-in,
sQL STATEMENTS
QL command or statement is a special kind of sentence
gutcontains clauses and all end with a semicolon() just as
sentence ends with a period.
‘There are four types of SQL statements
LDDL (Dats Definition Language)
Ic provides statements for creation and deletion of the
database tables, views, etc.
The DDL provides a sec of definitions to specify the storage
structure in a database system.
Some DDL statements are as follows
(i) CREATE used to create new table in the database.
(ii) DROP used to delete tables from the database,
(ii) ALTER used to change the structure of the database
table, This statement can add up additional column,
drop existing, and even change the dara type of
columns involved in a database table.
(iv) RENAME used to rename a table.
2. DML (Data Manipulation Language)
manipulating the database
the databases for information
Ik provides statements for
objects. Ie is used to query ¢
retrieval.
Some DML statements are as follows
(i) INSERT used to insert data into a table.
(ii) SELECT used to retieve daa from a database
199
(iii) UPDATE used to update existing dara within a rable.
(iv) DELETE used to delete all records from a table.
3. DCL (Data Control Language)
Itis used to assign security levels in database, which involves
multiple user setups. They are used to grant defined role
and access privileges to the users.
Some DCL statements are as follows
(i) GRANT used to give user's access privileges to
database.
(ii) REVOKE used to withdraw access privileges given
with grant command.
4. TCL (Transaction Control Language)
Ic is used for controlling the transactions in a database
system. These are also used to manage the changes made by
DML.
Some TCL statements ate as follows
() COMMIT used to save the work done.
(ii) SAVEPOINT used to identify a point in a
transaction to which you can later rollback.
(ii) ROLLBACK used to restore database to original
since the last COMMIT.
(iv) SET TRANSACTION establishes properties for the
current transactions.
In this chapter, we wi
statements.
Rules for SQL commands
Rules for SQL commands are given below
( SQL statements can be typed in lowercase or
uppercase letter. SQL statements are not case
iscuss only DDL and DML
sensitive,
(ii) The statements can be typed in single line or multiple
lines.
(iii) A semicolon ()) is used to terminate the SQL
statements
ww) eer be distributed across the line but
Ww) Acoma () is used co separate parameters without a
clause.
(ci) Characters and date constants of literals
enclosed in single quotes CA). THs Must be
(vil) A command can bi i
characters. ped cither full or First four
__ iva7
200
SQL DATA TYPES
Data types are declared to identify the type of data that will
be stored in a particular field or variable.
The following list of general SQL data types are given below
Data Type Syntax Explanation (f applicable
INTEGER INTEGER A32-bitsigned integer vae
or TNT andits range trom
2147483648 102147409647.
SMALUNT _ SMALLINT 16-bit signed integer valve
and its range trom 327680
ss sora eaeane
NUMERIC NUMERIC Where, pis a precision vale
(ps) and sis a scale valve. ¢9.
numeric (6.2) is a6 digit
number that has 4 dit before
the decimal and 2 digit ater the
decimal is
DECWAL DECIMAL Where, pisaprecisionvalueand
(3) sisascale value, (sameas
7 . NUMERIC)
REAL REAL Single-precision floating point
umber.
DOUBLE DOUBLE ___Doublesprecision floating point
PRECISION PRECISION number on
FLOAT FLOAT(p) Where, pis a precision vaue
CHARACTER CHAR(x) _Where,xistnenumber of
chatacters tobe stored. This
Gsiatype wlloccupy spacetor
NULLvalves. ean hold almost
__255 characters.
CHARACTER VARCHAR(x) Where, xis the number of
VARYING characters to be stored. It wil
‘occupy space for NULL values
TRean hol atmost 2000,
characters and used in ANSI
standard
CHARACTER VARCHAR? Where, xis the number of
VARYING) characters 1 be stored. can
hold 4000 byes of characters
and used only in Oracle.
Dare ATE ‘Stores year, month and day
values
Me TIE Stores hour, minute and
second values,
Check Point 01
4, Write 1wo advantages of SQL.
2, Write he short note on DDL.
3, Write use of semicolon (:) in SQL statements
4, Which language is used to query the database for
information retrieval?
5, Write two disadvantages of SOL.
| Alone | COMPUTER SCIENCE Chass yy,
SQL Command Basics
SQL database is a way of organizing a group of tables
Ske Ses the dae 1 he form of tow and cola M4
To create a bunch of different tables that share a coming,
theme, you would group them into one database to may”
the management process easier. So, for manipulating dar
we need to know about database commands, why a
described below
Creating and Using a Database
Create a database Creating database is an easier task, Yoy
need to just type the name of the database in a CREATE
DATABASE command.
Syntax
CREATE DATABASE CIF NOT
EXISTS]
;
CREATE DATABASE command will create an. emp
database with che specified name and would not contin
any table.
IF NOT EXISTS is an optional part of this seatement which
prevents you from an error if there exists a database with the
given name in the database catalog.
For example, nysq\>CREATE DATABASE BOOK:
Output Query OK, 1 row affected <0.01 sec
Select a Database
Creating database is not enough for use. Before working
with tables, first you have to select the database,
The only thing need to be considered before selecting 2
database is that it must already exist. To select a databise
‘USE command is used.
Syntax USE :;
For example, mysq)>USE ENGBOOK:
‘Where, USE command makes the specified database asa
current working database and EGNBOOK is the database
name.
Output Database changed
Show Databases
To check the names of the existing databases on the sever
you need to use the SHOW command. This will provide
you the information about databases and the contents
available in it.
Syntax
SHOW DATABASES;
For example,
mmysq]>SHOW DATABASES;yr
gostred Query Language
jxtput
Bo0K
ScHOOL j
copies}
stupent }
yopping a Database
prabase, can be removed or deleted using DROP
jonmand. But before deleting a database make sure that
x1 do not need the data stored in different tables of a
Yabase because when you delete a database, all its tables
sho gets removed along with it,
gyntax
OROP DATABASE ;
fir xample,
sysq12DROP DATABASE, SCHOOL:
Output
Query 0K, 1 row affected (0.04 sec)
‘+ Drop command permanently removes the
database.
+ MySQL is not case-sensitive,
'S0 you can write SOL commands either in
GIGO uppercase o: lowercase bul for UNIX MySQL is
case-sensitive,
DDL STATEMENTS/COMMANDS
Some DDL statements are as follows
CREATE Statement
The CREATE statement is used to create a table in a
database. In this command, we need to give information
about table like number of columns, rows and its types
and constraints.
Syntax
CREATE TABLE
q
mn_namel>(()]
uae Coonstraints).
rn_name2><éate_typert()1
ae Ceonstratnts),
e3>)]
anna
Displaying the Table Structure
DESCRIPTION or DESC. command is used 0
the structure of a table that you have created,
‘This command display the column names, available data
items with theie data types.
verify
Syntax
DESCRIBE :;
DESC :
For example, |
DESC PERSONS; k
CA ih nd; |a _
202
Output
Field
Pid
Firstilame
Lastane— { varchar(25)i YES
Address varchar(30)! YES !
f varchar(25): YES
city
DROP Statement
~ The DROP statement is used to remove the table
definition and all data, constraints and permission
Specified for that cable. You have to be careful while using
the DROP command because once the table is deleted,
then all the information available in the table would be
lost forever, But there is a condition for dropping a table;
it must be empry. A table with rows in i¢ cannot be
dropped.
Syntax DROP TABLE table_name
eg. DROP TABLE EMPLOYEE:
‘The above query will delete the table EMPLOYEE and
after this, no rable with Employee name would exist
“We cannot even rollback after dropping a table.
‘TER Statement
‘The ALTER statement is used to add, delete or modi
columns and constraints in the existing table.
To ADD a Column
Syntax
7? ALTER TABLE table_name ADD column_name
data_type: se
/ 0g ALTER TABLE STUDENT ADD ‘Section CHAR:
‘The above query will add column Section to STUDENT
table, whose data type is character.
To DROP Column
Syntax
ALTER TABLE table_name DROP COLUMN
column_name;
eg. ALTER TABLE STUDENT DROP COLUHN location:
‘The above query will delete a column location from
STUDENT table.
To MODIFY Column Data Type
Syntax
ALTER TABLE table_nane MODIFY colunn_name
data_types i
| Allznone | COMPUTER SCIENCE Class 124,
DIFY Fee NUNBER(IS.2):
the data type of Fee column, of
e.g: ALTER TABLE STUDENT MO
‘The above query will modify #
STUDENT table.
To DELETE a Constraint
Syntax
ALTER TABLE table_name
eg ALTER TABLE STUDENT DROP Primary Key:
sy will delete the primary key constraint from
pRop Constraint_Nane:
‘The above quet
STUDENT «able.
RENAME Statement
The RENAME statement is used to rename a table.
Syntax
RENAME old_table_name TO new_table_name:
eg. RENAME STUDENT TO CANDIDATE:
The above query will rename STUDENT table 0
CANDIDATE.
DML STATEMENTS/COMMANDS
Some DML statements are as follows
INSERT Statement
‘The INSERT statement is used to insert a new row/data ina
rable.
Syntax
INSERT INTO table_name VALUES
(valuel, value2, valued...
or
INSERT INTO table_name(columnt, column2.
column3, ...)VALUES(valuel, valuez
value3,...)5
e.g, IF we have the following PERSONS table
Pid LastName FirstN ‘Address Cily
1 Hansen Ola_Timoteivn 10 _Sancines_
Svendson Tove Borgyn 23 Sandnes_
Pettersen Kati_——_Storgt 20 Stavanger
and we want to
ert a new row in the PERSONS rable.
‘We use the following SQL statement
INSERT INTO PERSONS VALUES (4, ‘Nilsen’.
Johan", ‘Bakken 2°, ‘Stavanger’);y
sed Query Language
pgRsONS sible will now look ike this
ire [LastName FirstName Add i
a eo aaron
a ee
Sa mee
aaa ~ soverae
Se
jgert Data Only in Specified Columns
ao posible to add data only in specific columns.
‘The following SQL statement will add a new row, but
‘fi daa only in the P_Id, LastName and the FirstName
ise the following SQL statement
INSERT INTO PERSONS(P_Id, Lastiame,
FirstName)
VALUES(S, ‘Tjessem*, ‘Jakob’ ):
the PERSONS rable will now look like this
Pid LastName FretName Address Oly
1 Hansen Ola ___Timoteivato__Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Peterson K ‘Slorgi 20 Stavanger
"4 Nilsen Johan Bakken 2_ Stavanger
“5 Tiessem dake NULL NULL
SELECT ‘Statement
The SELECT statement is used to select data from a
aabase or view able information. The result is stored in a
teal table, called che result se
‘Syntax.
To select some specify columns
SELECT colunn_name(s) FROM table_nane:
To select all columns
SELECT * FROM toble_nane:
SQ) is nor case sensitive, SELECT isthe same as select. The
See) iv a quick Way of selecting all columns.
Ta SQy SELECT chase wed to lit he atibutes desired
In SQL Sif a query and FROM clause is ued ro list the
the es auch columns are co be extracted.
relations from whic
select the content of che columns named
from the PERSONS table.
ar
eg, If we want (0
iE Ne and Fem
203
‘We have to use thi following SELECT statement
SELECT Lastliame, FirstName FROM PERSONS:
The result set will look like this
‘astame FirstName
~Svendson Tove
Pettersen Kari
eg IF we want to select all the columns from the
PERSONS table.
‘We have to use the following SELECT statement
SELECT * FROM PERSONS:
“The result set will look like cis
“Pid_LastWame FirstName Address _ ity _
1 Hansen Ola ___Timotehm 10 Sandnes_
2 Svendeon Tove Borgn23__ Sandnes
3 Pettersen Kai Slongt20__ Stavanger
‘Odlumn Alias
Colunin alias is used to temporarily rename a table's
column for the purpose of a particular query. This
renaming is a temporary change and the actual column
name does not change in the database.
‘Syritax
SELECT AS FROM
;
Alias_name specifies the reference name of the specified
column.
For example, to selece the DOJ of all the employees
referenced as Joining_Date from the table COMPANY the
query would be like
‘mysql> SELECT 00J AS Joining Date
FROM COMPANY
Query produces the following output
2012-02-06
2002-12-04
2004-08-06
2007-09-06
2001-07-06
2012-05-06
7 rows in set (0.00 sec)204
Operators im SQL
SQL supports different types of operators, some of them are
described below
Arithmetic Operators
These operators are used to perform mathematical
calculations, such as addition, subtraction, multiplication,
division and remainder.
Some most important arithmetic operators used in SQL are
(OPERATOR DESCRIPTION
* (Adaition) ‘Add the two arguments together
— (Subtraction) Subtract the second argument from the first
argument
|| Allznone || COMPUTER SCIENCE Class 194),
“Above query produces the following output
Trow in set (0.03 sec)
Comparison Operators
These operators are used co test or compare the value of twp
operands, ie, between two variables or between a variable
and a constant.
If the condition is false, then the result is zero (0) and if
the condition is true, then the result is non-zero. These
operators are also called relational operators.
Some ofthe comparison/relational operators used in SQL area
~ (wuhipicaton) Multis the two arguments jillna
7(Dhsion) Drie it reer ye sean CREATOR seRTON
% (Modul) Divide the ist argument from the second = Equal to
argument and provides the remainder of 5 ‘Greater han
that operation —aeeae
syntax: > Greater than or equal to
SELECT. 7 aarnan arse
Conner SS pet 80 sng
[WHERE 1: Ke Not less than (not ISO standard)
For example, query to display _ EMP_NAME, > ‘Not greater than (nat ISO standard)
EMP_DEPT_NO and 20% of EMP_SALARY for cach
Syntkew:
employee for social fund.
mysql> SELECT EMP_NAME, EMP_DEPT_NO,
EMP_SALARY*0.20
FROM COMPANY:
Above query produces the following output
op +
EMP_DEPT_NO | EMP_SALARY*0.20 :
fanui Sharma 008 SS«8120
Vikas wives! 003, $200
Puneet Jain} 005 | 4200
sachin vats | poz «f= 4700—S
{ udey singh | 003 $= 8200
Eravi Shukla $001 ©} - 47000 |
{ viney Rana} 003p aan
7 rows in set (0.00 sec)
‘Arithmetic operators can be implemented through simple
SELECT statement without any table, This acts like a
fanction.
For example,
SELECT 35*245; 4
SELECT |*|expression
FROM WHERE
;
For example, query to display EMP_NAME and
EMP_SALARY for those employees whose salary is great
than or equal co 25000.
mysql> SELECT EMP_NAME,EMP_SALARY
FROM COMPANY
WHERE EMP_SALARY> = 25000;
+ =+
Rahul Sharma t
: 2600}
{Vikas Mittal! 26000 fy
{Uday Singh} 26000 |
3 rows in set (0,00 sec) Mar
‘When we use relational operators with character data {YP
< means earlier in the alphabet and > means later in the
alphabet ‘Bangalore ‘<’ ‘Brajl’ as ‘a’ comes before ‘f i®
alphabet.siructured Query Language
sogical Operators
icl operators compare two conditions at a time to
Deere toe be selected for the output,
aa operators are also called boolean operat
ors, because
see operators return a boolean datatype value as TRUE,
oc FALSE.
‘When retrieving data using a SELECT statement, you ean
we these operators in the WHERE clause,
which allows
you to combine more than one condition,
Sone ofthe BooleanlLogical operators wed in SQL are as
OPERATOR DESCRIPTION
NO Loti! AND compares two expressions ang
{etumn tue, when both expressions are roe
AR t29ical OR compares two expressions ang
‘elu tue, when atleast one ofthe,
expressions is rue
NoT NOT takes a single expression as an
‘tgument and changes its value tom false to
tue or rom tu
eto false. You can use an
exclamation poi
int () in place ofthis operator
‘Syntax
SELECT |* |
FROM
WHERE SELECT EMP_CODE, EMP_NAME
FROM COMPANY
WHERE CEMP_DEPT_No=*005* ao
EMP_SALARY 22000);
Query produces the following output
1 rows in set (0.00 see)
fr example, query t disply EMP_CoDE and
EMP_NAME for those employees whose EMP_DEPT_NO
is DOS or ‘EMP_SALARY is greater than 22000,
mysql> SELECT EMP_CODE, EMP_NAME
FROM COMPANY
WHERE(EMP_DEP_NO = ‘005° OR
EMP_SALARY>22000:
205
Above query produces the following output
100 Rahul Sharma
Jor} Vikas mittat
{102} Puneet Jain
£103 | sachin vats
{108 Uday singh
1105 avi Shukla ’
1 Vinay Rana
7 rows in set (0.00 see)
For example, query to display EMP_CODE and
EMP_NAME forthe employee whose EMP_SALARY is not
greater than 22000,
mysql> SELECT EMP_CODE,
FROM COMPANY.
WHERE (NOT EMP_SALARY>22000);
or
mysql> SELECT ENP.
FROM COMPANY
WHERE !(EMP_SALARY>22000) ;
Above query produces the fa
EMP_NAME
"CODE, EMP_NAME
lowing outpue
1 row in set (0.00 sec)
DISTINCT Keyword
In a table, some of the columns may contain duplicate
Values. This is not a problem, however, sometimes you sn
Ment to list only the difftent (distinc values in a table.
The DISTINCT keyword can be
The r used to return i
disiner (different) values in a Particular column or EL
table,
‘Syntax
SELECT DISTINCT column_name(s)
FROM table_name;
cin iy hon
¢ have to i
“Steer piers ee encore
The ress wil lok ke hi :
=a
Sannes| 206
|| Allzzone | COMPUTER SCIENCE cz, 2
th
ALL Keyword
ALL clause result just the same as that when you do no
specify DISTINCT. Ie will give values of selected atribute
from every row of table without considering the duplicate
eg, IF we want to select the persons with alae
alphabetically between “Hansen” and “Poy, ame
from the table PERSONS. eye
‘We use the following SELECT statement
records. SELECT * FROM PERSONS
Syntax WHERE LastName
1 SELECT ALL column_name FROM table_name; BETWEEN ‘Hansen’ AND ‘Pettersen:
Ws WHERE Clause The result set will look like this
ti ‘The WHERE clause is used to extract only those records Pid LastName FirstName Address Ciy
| that fulfil a specified criteria, : 1__Hansen Ola Timoteim 10 Sanangy
| Syntax 3 Pettersen Kari__St0rg1 20 Stavanger
| SELECT colunn_name(s) FROM table_nane RENO
WHERE condition: (ii) NOT BETWEEN Operator selects the daa oui
the range of data berween two values. The val
..g. If we want to select only the persons living in m
ae BS renee ne in che cy be text, numbers or dates. “<
| ““Sandnes” from the table PERSONS,
Hi ‘We use the following SELECT statement Syntax,
SELECT column_name(s)
SELECT * FROM PERSONS
FROM table_name
WHERE City=*Sandnes’; WHERE column_name
| ian NOT BETWEEN valuel AN valuez;
eg. To display the persons outside the range in th
| Pid LastName FirstName Addr previous example, use NOT BETWEEN operat,
: 1 Hansen __Ola__Timoteivn 10 _Sancnes ‘We use the following SELECT statement
i 2 Svendson Tove _Borgyn 23 _Sandnes SELECT * FROM PERSONS
|, See eee WHERE Lastiiame
Ht Quotes Around Text Fields NOT BETWEEN ‘Hansen’ AND ‘Pettersen’;
| SQL uses single quotes around text values (most The resule set will look like this
database systems will also accept double quotes). asiName FirstName Address iy
However, numeric values should not be enclosed
i in quotes. Borgyn 23 _ Sands
i For text values,
This is correct
2. Svendson Tove
(iii) LIKE Operator is used to match a value similar
SELECT * FROM PERSONS NHERE FirstName~"Tov
This is wrong
SELECT * FROM PERSONS WHERE Firstame=Tove:
For numeric values,
This is correct,
SELECT * FROM PERSONS WHERE, Year=1965;
This is wrong
SELECT * FROM PERSONS WHERE Year="1965":
Operators Allowed in the WHERE Clause
@ BETWEEN Operator selects a range of data between
two values. The values can be numbers, text or dates.
Syntax
“SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN valuel AND vatue2;
specific pattern in a column using % and _. The
sign represents zero, one or multiple characes, whi
— represents a single character. It is useful when yo
‘want to search rows to match a specific pater,
when you do not know the entire value,
SELECT column_name FROM table_nane
WHERE column_name LIKE “conditio
To display the FirstName that start with le!
“e.
‘We use the following SELECT statement
SELECT FirstName FROM PERSONS
WHERE FirstName LIKE “TS”
‘The resule set will look like this
“FirstName
Tovegored Query Language
egy Mrwe want to display thesll records, where the
LastName's second eter is ‘a
‘We use the following SELECT statement
SELECT * FROM PERSONS
WHERE LastName LIKE"_ag";
‘The result set will look like this
Zi LastName Fstome Addons
a iainnen imo
City
Timoteivn 10 Sandnes
i) IN Operator checks a value within a set of values
separated by commas and retrieve the rows from: the
table which are matching.
The IN operatorallows you to specify multiple values
ina WHERE clause.
syntax
SELECT column_nane()
FROM table_name
WHERE colunn_name. IN (valuel,value2, «
eg, If we want to select the persons with a last name
equal to “Hansen” or “Pettersen” from the table
PERSONS. 7
‘We use the following SELECT statement
SELECT * FROM PERSONS
WHERE LastName IN
CHansen’ , ‘Pettersen”):
The result set will look like this
Pld LastName FirstName Address City
Hansen Ola ___Timoteivn 10_ Sandnes
3 Pettersen Kari __—_‘Storgt20__ Stavanger
__3__ Pettersen _Kari_Storgt20_Stavanger_
ORDER BY Clause
The ORDER BY keyword is used to sort the result set along
2 specified column with the SELECT command. The
ORDER BY keyword sorts the records in ascending order
by defaule Ifyou wane co sore the records in a descending
cider, you can use the DESC keyword,
Syntax SELECT 601 uan_ame(s)
table_nane
FRO ay gat _nane( s)ASC/OESC:
Eine to select all the persons from the table
$8 MONS however "we want to sort the persons by their
mame in ascending order.
lowing SELECT statement
er FROM. PERSONS
Leer gy Lastlame ASCs
- ‘cil look like this
fuse the fol
Wews ‘SELECT
“The result
207
Fd tastame FIBRE pgaress OY
Henson Oa inate 10 Sandee
3_etersen Kati Sigh 20._ Stanger
Syendson Tove Borg 20 _Sarcnes
Check Point 02
1, SELECT and ALTER are which type of commands?
2, What is unique constraints?
3, Write the syntax to modify the column data type.
4 What is the use of DISTINCT keyword with SELECT
Statement?
jive an example using IN operator.
UPDATE Statement
‘The UPDATE statement is used to update existing records
in a table,
‘The WHERE clause in the UPDATE statement specifies
which record or records that should be updated. IF you omit
the WHERE clause, all records will be updated.
Note Expressions ave also used in the SET clause of the UPDATE
‘command 19 manipulate the values.
5
SyntaxUPOATE table_name
SET colunni=valuel, colunn2=value2...+
WHERE ;
eg. If we want to update the person “Ola Hansen” in the
PERSONS «able
‘We use the following SQL statement
UPDATE PERSONS
SET Address="Missestien 67°,
City =*Sandnes”
WHERE LastName:
FirstNane="Ola 3
‘The PERSONS table will now look like this
Hansen”. AND
LastName FirstNam
‘Address Cily
1. Hansen Ola__Nissestien 67 Sandnes
2 __Svendson Tove ___Borgn23__Sandnes
3 Petersen Kari___‘Storgt20__ Stavanger
SQL UPDATE Warning
Be careful when updating records. If we omit che
: cords. If we omit the WHI
clause in the example above, like this: r ERE
UPDATE PERSONS
SET Address="Nissestien 67°
City="Sandnes*; a208
‘The PERSONS table would have looked like this
Pid LastName FirsiName Address Clty
Hansen Ola__Nissestien67_Sandnes_
ndson Tove __Nissesten 67_Sandnes
Nissesten 67 Sandnes
1
2 Svends
3 Pettersen Kat
DELETE Statement
‘The DELETE statement is used to delete rows in a table
‘The WHERE clause in the DELETE statement specifies,
which records co be deleted. If you omic the WHERE
‘dau, all records will be deleted.
syntax
DELETE FROM table_name WHERE ;
cag fe want ro delete the person “Kari Petersen” inthe
PERSONS table.
We use che following SQL statement
DELETE FROM PERSONS
WHERE LastNane= Pettersen’
|AND FirstName=" Kari":
“The PERSONS table will now look like this
Pd Lasivame Frame Address__Ciy
1 Hansen Ola __Tmotewn 10_ Sandnes
“Hansen __Ola_Timotewn T° SET
2 Svendson Tove __Borgn23_Sandnes
Delete All Rows
Irisposibleo deletes rows ina able without deleting the
table, This means that the table structure, attribures and
indexes will be intact.
Syntax
DELETE FROM table_name;
WORKING WITH
NULL VALUES
In SQL, the empty values are represented as NULL in a
table, Ia table having null values, then you can display
columns with nul values or without null values and you can
replace NULL values with another value.
To handle NULL values in SQL, you should use the
following commands
IS NULL Clause
If we want to search the column whose value is NI i
tie en we ye SNULLGaue, beatae
Syntax
SELECT FROM
WHERE 1S HULL:
| Allinone | COMPUTER SCIENCE Class 144
eg. Let us consider the following table Teacher:
TNO Tname —_TSalary Dos
or maa 7000 20190108
Teka NULL
qa Ravncra NULL 2019-1125
son bustyant_—_16000_2014-0-10
Ts Swat 7900020140219
Query to display column whose value fs NULL
We use the following SQL statement
SELECT * FROM Teacher
WHERE T_Salary 1S NULL:
[Above query produces the following output
T Name TSalary oy
NULL 2013-12-14
<
Ravindra NULL 2018-1123
1S NOT NULL Clause
Ifwe want to search the column whose value is not NULL
ina table then we use IS NOT NULL clause.
Syntax
SELECT FROM
WHERE 1S NOT NULL;
ug. Consider the above table Teacher. Query to diy
column whose value is not NULL.
We use the following SQL statement
SELECT * FROM Teacher
WHERE T_Salary IS NOT NULL;
‘Above query produces the following output
TNo TName _T_Salary Dol
Tor Wadhna 1700020130108
To Dushyant 1600020140110
Tos Sua 900020140240,
AGGREGATE FUNCTIONS
Aggregate functions are also known as group functions
‘Aggregate functions return a result only in single row based
fon group of rows, rather than on single row. It ah
appens in SELECT command and in ORDER BY 204
HAVING clauses. They are commonly used with the
GROUP BY clause in a SELECT statement, Some of
aggregate functions are MIN, MAX, SUM, AVG
COUNT. The SQL aggregate functions recurn si
value, calculated from values in a column,gqructured Query Language
ee ate different types of aggregate Fun
avGQ
| ‘
| phs Function returns the ave ;
| rage value of a specified
gymtax SELECT AYG(column_namey
FRON table_name;
oe Consider the following table PAYMENTS:
Emp_Name
empid Salary Department
m4 Ridhi 20000 ot
_ 2 Rohit 25000 oe
3 Rakesh__20000 De
| 4 Roshan 44000 DT
5 Rohini 15000 03
6 Racha 14000. o1
To display the average of employees salary from
PAYMENTS table eee
SELECT AVG(Salary) FROM PAYMENTS;
Output ——__
AVG (Salary)
23000
COUNT( )
‘This function returns the total number of values or rows of
the specified field or column. COUNT (*) is a special
fanction, as it returns the count of all rows in a specified
table, It includes all the null and duplicate values.
Syntax
SELECT COUNT(*) FROM table_name:
eg. To count the total number of employes from
PAYMENTS table.
SELECT COUNT(*) “Employees” FROM PAYMENTS;
output Employees
nea
a
with COUNT( ) Function
DISTINGT us in removing the
The DISTINCT kerr helps
seven sion COUNT, it reeurns
jn as
T couNT(O!
Fe apse
eg, To count toe
\
a may COUNT pepartme”
‘When it is used with
the number of
column
nt) “Dept!
209
FROM PAYMENTS;
Output
eg. To count distinct values of coh
luc lumn Der fr
PAYMENTS table. ae
SELECT COUNT(DISTINCT Department) “Deptia”
FROM PAYMENTS;
Output
MAX()
This function returns the largest value from the selected
column.
Syntax SELECT MAX(column_name)
FROM table_nane:
eg To find the maximum salary of employee from
PAYMENTS table.
SELECT MAX(Salary) “Maximum”
FROM PAYMENTS:
Output
Maximum
44009
MIN()
“This function returns the smallest value from the selected
column.
Syntax SELECT MIN(colunn_name)
FROM table_nane;
eg. To display the minimum salary of employee from
PAYMENTS table.
SELECT MIN(Salary) “Minimum”
FROM PAYMENTS;
\
Ourpu ‘Minimum:
14000
SUM()
‘This function returns the sum of values in the specified
column. The SUM works on numeric fields only. Null
values are excluded from the result returned.
Syntax SELECT SUM(coluan_name)
FROM table_name;
Mi thistle,210
ce To count sum of employee's salary from PAYMENTS
table.
SELECT SUM(Salary) “Salary”
FROM PAYMENTS:
Output
Salary
1138000
GROUP BY STATEMEN
‘The GROUP BY statement is used with the aggregate
functions to group the result set by one or more columns.
SyntaxSELECT column_name,
aggregate_function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name;
Consider the following ORDERS table
TABLE: ORDERS
Old OrderDate _OrderPrice Custor
1 2ooe/tis12 1000 Hansen
2 2008/10/23 1600 ‘Nilsen
“3 2008/09/02 700 Hansen
__4 2008/09/03 300 Hansen
5 2008/08/30 ___-2000 Jensen
6 2008/10/04 100 Nilsen
e.g, If we want to find the total sum (OrderPrice) of each
customer from table ORDERS.
We use the following SQL statement
SELECT Customer, SUM(OrderPrice)
FROM ORDERS
GROUP BY Customer:
‘The result set will look like this
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000
Ler’s see what happens if we omit the GROUP BY
statement:
SELECT Customer ,SUM(OrderPrice)
FROM ORDERS;
The result set will Look like this
‘SUM(OrderPrice)
5700,
Customer
Hansen
| Allzzone | COMPUTER SCIENCE Class 199,
In the above case, SELECT statement cannot be used
because the SELECT statement above has two column,
specified (Customer and SUM(OrderPrice). ‘The
“SUM(OrderPrice)” returns a single value (chat is the tot
sum of the “OrderPrice” column), while “Customer”
returns 6 values (one value for each row in the “ORDERS?
table). This will therefore not give us the correct resu
However, you have seen that the GROUP BY stacement
solves this problem.
HAVING CLAUSE
“The HAVING clause is used with GROUP BY clause 19
place condition because the WHERE keyword could not be
used with aggregate functions.
Syntax
SELECT column_name,
aggregate_funct jon(colunn_name)
FROM table_name
WHERE condition
GROUP BY colunn_name
HAVING aggregate_funct ion(colunn_nane)
;
eg. If we want to find any of the customers have a toul
order of less than 2000 from table ORDERS.
We use the following SQL statement
SELECT Customer ,SUN(OrderPrice)
FROM ORDERS
GROUP BY Customer
HAVING SUM(OrderPrice)<2000;
The result set will look like this
Customer SUM(OrderPrice)
1700
Nilsen
eg. If we want co find che customers ‘Hansen’ ot ‘Jens!
have a total order of more than 1500.
‘We add an ordinary WHERE clause to the SQL statement
SELECT Customer, SUM(OrderPrice)
FROM ORDERS
WHERE Customer="Hansen’ OR
Customer="Jensen*
GROUP BY Customer )
HAVING SUM(OrderPrice)>1500; ens
The result set will look like this off
'SUM(OrderPrice)
2000
2000
‘Customer
Hansen
Jensengrvetured Query Language
joIN
join is @ query that combines rows from two of more
Ages. In 2 join query, more than one tables ave listed ia
FROM clause. The function of combining data fom
Frliple tables is called joining. SQL ean obtsin data fom
(eral related tables by performing either a. physi. or
eral join on the tables
ins are used when we have o select data from two or more
tbls. Joins are used to extract data from two {or more)
tables, when we need a relationship between cereain
{olumns in these tables.
The SQL Join condition is always used in the WHERE
dause of SELECT, UPDATE and DELETE statements,
‘There are different kind of SQL joins
1, Equi Join
Equi join is a simple SQL join condition that uses equal
sign as a comparison operator.
Syntax SELECT coll, col2, col3
FROM tablel, table2
WHERE tablel.coll table2.coll;
Consider the following tables PERSON and ORDERS
TABLE: PERSON
Pld LastName FirstName City
Sharma Abhay __ Mumbai
2 Gupta Mohan Oehi
3 Verma ‘Akhil Mumbai
TABLE: ORDERS
or Order_No Pid
T4100
T2200
Sig
4 45000 1
see 35000 15
in ewo tables PERSON and ORDERS using a
© To tte Pld of PERSON able is equal tthe Pld
of ORDERS table).
We use the following SQL statement
[ SELECT LastName. First_Name, Order_No
FROM PERSON. ORDERS :
PrP Re PERSON P_JO-ORDERS. PI
eater av pERSON.Last=Non
2il
The query will give us the below result
ahaa se EOE
ines 58
arama a eee oon
cena ns HERE 050
aa a EN
SQL equi joins are further classified into two categories
(i) Inner Join
‘The inner join using either of the equivalent queries gives
the intersection of two tables, ie. it returns us the rows,
which are common in both the tables.
Syntax
SELECT coll, col2
FROM tablel INNER JOIN tablez
ON tablel.colunn_name=table2.colunn_name:
e.g. To perform INNER JOIN on two tables PERSON and
ORDERS.
‘We use the following SQL statement
SELECT Last_Name, FirstName FROM
PERSON INNER JOIN ORDERS ON
PERSON.P_Id=ORDERS.P_Id:
(ii) Outer Join
The outer join include rows in a joined result even when
they have no match in the joined table. An outer join
returns all rows that satisfy the join condition and also
returns those rows from one table for which no rows from
the other satisfy the join condition.
(a) Left Outer Join
The left outer join returns all the rows from the left table,
even if chere are no matches in the right table.
Syntax
SELECT column 1, column 2
FROM tablel LEFT JOIN tablez ON
tablel.column_name = table2.column_name;
£8 To perform LEFT OUTER JOIN ot
PERSON and ORDERS, ; So212
We use the following SQL statement
P.First_Name.0.Order_No
FROM PERSON P
LEFT QOIN ORDERS 0
OW P.P_Id = 0.P_Id ORDER BY
() Right Outer Join
‘The right outer join returns all the rows from the right
table, even if there are no matches in the left table
syntax
SELECT column, columnz
FROM tablel RIGHT JOIN tabie2
ON tablel.column_name=tablez-column_neme:
eg. To perform RIGHT OUTER JOIN on ovo cables
PERSON and ORDERS,
We use the following SQL statement
SELECT P.Last_Name, P.First_Name.
O.order.No FROM PERSON P RIGHT JOIN ORDERS
ow P.P_id = 0.Pta
| AllZnone | COMPUTER SCIENCE Class 124,
‘TABLE: COURSE
e.g. To perform SELF JOIN on COURSE table,
We use the following SQL statement
Sees Si tourse tome as COURSE.
skourse.wame AS Prerequis'te Course
PROM COURSE a. COURSE B
Gnene a Pre_course = b.Course 1d:
Took like this
“The resule set wil
3. Non-Equi Join
Non-equi join is used co return the result from swo or more
Dibiess Where exact join is nor possible. The SQL non-equt
join tser comparison operators instead of, the equal sign
like >, longwith conditions.
syntax
SELECT * FROM tablet. tabiez
WHERE tablel-column > tablez.column:
Consider the following tables
ORDER BY P-Last_Neme: Table: EMP
“The query will give us the below resule ‘empne_ename sa ‘ate
LastName FirstName Order No 410 Priya 709 44-11-2010
‘Sharma Abhay 45000 a4 ‘Seema 14000 15-02-2014
‘Sharma Abhay 5087 351 ‘Sachin _#0000_16.04-2015
Verne ro "25000 342 Deeps 25000 20-05-2015 _
Vverme ra "10050 Table
aa ‘ompno ety orao_
2. Self Join 110 Demi s000 100002
A self join is a join, where we join a particular table to itself. Sa an irene i TGSao Ra zosod = EE
Tiere in this case, ie is necessary to ensure that the join
Suurcment defines an ALIAS name for both the copies of the
fables to avoid column ambiguity. Consider the following
eg. To perform NON-EQUI JOIN on. two cables EMP
Shd SALGRADE.gqructured Query Language
fe use the following SQL statement
SELECT e.empno, e.ename, e.sal
FROM EMP ©, SALGRADE s oe
WHERE e.sa1 BETWEEN s.Towsal AND
s.hisali
‘The resule set will look like this
empnoename ——sal_—_grade
110 Priya 70002
mn Seema 140005
4. Natural Join
‘The natural join is a type of equi join and is structured
jin such a way that, columns with same name of
associated tables will appear once only.
Syntax
SELECT * FROM tablel
NATURAL JOIN table2;
Consider the following tables
TABLE: FOODS
Tomo em Nae emu _Compan i
ec ae ee)
eo eet Pes dal
ager er Mer Siana
tote eee
eee ae
213
TABLE: COMPANY
Company_Name Company City
18 ‘Order All Boston
Jack Hil Lid
To fetch all the unique columns from ‘FOODS’ and
‘COMPANY tables, after joining these tables.
We use the following SQL statement
SELECT * FROM FOODS NATURAL JOIN COMPANY
WHERE FOODS. Company_Id=COMPANY .Company_Id:
‘The resule set will look li
item_| tem_ | Wem | Company.
id | Name | Unit | id
+ |ChexMix| Pes | 16 |AkasFoods| Delhi
6 | cheezit| Pes 15 | JackHil | London
rt)
2 | siscut | Pes 15 | JackHit | London
ud
Munch | Pos 17 | Foodies | London
4 | Rice | Pes 15 | Jack Hit | London
us
s_| cake | - Pes 18 | Oxderan_| Boston
Check Point 03
4. How 10 delete all rows from table?
2. Why do we use DISTINCT keyword with COUNT() function?
4 Name any tvo aggregate functions.
4LHAVING keyword is used with which clause?
{§. What is the difference between left outer join and right outer
join?EXAM PATTERN
EXERCISE
OBJECTIVE Type Questions 6
Directions (Q. Nos. 1-10) There are multiple choice
type questions. Select the correct option.
1. Which of the following is an advantage of SQL?
(a) High speed ne
(0) Client/server language
(©) Easy to learn a
(4) All of the above
Ans. (A) All ofthe above
2. Which statement of SQL provides statements) Ans,
for manipulating the database objects?
(a) DDL. (b) DML. 8.
(Dc. (@TCL
Ans. (>) DML (Data Manipulation Language)
3. Which of the following command is used to Ans,
remove the table definition and all data? 9.
(a) Create (b) Select
(©) Drop (@) None of these
Ans. (¢) Drop
4, Which of the following is a correct syntax to Ans,
add a column in SQL command? o
(@) ALTER TABLE table_name ADD column_name
data_type:
(B)ALTER TABLE ADD column_name data_type:
(©) ALTER table_name ADD column_nane
data_typ ceed
(€) None of the above
‘Ans. (a) ALTER TABLE table_nanie ADD-columi_name.*
data_type: — tt
5, Which keyword can be used to return only Ans.
different values in a particular column or a 2
whole table? .
(a) WHERE
(©) DisTINcT Ans
(0) ALL 13,
(@ BETWEEN
Ans, (b)DISTINCT
Which of the following operator displays
record if either the first condition or the secong
jon is true?
con
(a) AND (b) BETWEEN
(oR (4) None of these
. (c) OR
The keyword sorts the records in
ascending order by default.
(a) LIKE (b) UPDATE.
(c) ORDER (d) ORDER BY
(a) ORDER BY
Aggregate functions are also known as
(b) group method
(d) Add function
(a) group functions
(c) sum function
(@) group functions
Which of the following function returns the
total number of values?
(@) MAX (be) MIN
(©) COUNT (a) SUM
(©) COUNT
Which of the following join gives the
intersection of two tables?
(@) Outer join (©) Inner join
(©) Equijoin (d) None of these
(@) Inner join
Directions (Q. Nos. 11-20) Fill in the blanks.
SQL is running in al
servers,
Provides statements for creation and
deletion of the database tables, views.
DDL (Data Definition Language)
data type stores year, month and day
values.
DATEstructured Query Language
14. The SQL....... is used to add, delete or modify
columns and constraints in the existing table.
ALTER TABLE
The
(asterisk)
The ...... clause is used to extract only those
records that fulfil a specified criteria.
WHERE
Ans.
15.
Ans.
16.
is a quick way of selecting all columns.
Ans.
17.
sperator is used to rhatch a value similar to
specific pattern in a column using % and _.
LIKE
Ans.
18. ...... function returns the largest value from the
selected column,
MAX
‘The ...... statement is used with the aggregate
functions to group the result set by one or more
columns.
GROUP BY
.~ is a simple SQL join condition that uses
‘equal sign as a comparison operator.
Equi join
Ans.
19.
Ans.
20.
Ans.
Directions (Q. Nos. 21-33) Answer the following
questions.
21, Expand the following abbreviation:
(@ SOL
(ii) DML
‘Ans. (i) SQL- Structured Query Language
(i) DML - Data Manipulation Language
22, Mention two characteristics of SOL-
‘Ans, (i) SOLisa very simple and easy to learn.
(3 SOL allows the users to erate, update, delete and
etsieve data from a database
23, Name any two DDL commands.
“Ans, DDL consists of varius commands sucha
(i) Create
Gi) Alter
44, Name any four Transaction Control Lan
* (ret) commands.
(retpk commands ar sted below
() Commit
(i Rollback
iy Savepoint
fi set Transaction
guage
Ans.
25.
Ans.
26.
Ans.
27.
Ans,
28.
Ans.
29.
Ans.
30.
Ans.
3.
Ans.
32.
Ans.
33.
Ans,
215
‘Whaat is the use of Set Transaction command?
Set Transaction command establishes properties for the
current transactions,
Give the SQL statement to create a table Student
with Roll Number, Name, Age and Marks.
CREATE TABLE Student (Rol!_Nunber NUMBER(S)
Primary key. Name CHAR (20), Age Number (2).
Marks Nunber (4)):
Give the syntax of DROP statement.
DROP TABLE table_name:
How will you select the content of the columns
named LastName and FirstName from the
Employee table.
SELECT Lasttiame, Firstliame FROM Employee:
What is the use of WHERE clause in SQL?
“The WHERE clause is used to extract only those records
that fulfil a specified criteria,
Write the query to select all the persons from
the table Persons and sort the persons by their
last name in ascending order.
SELECT * FROM Persons ORDER BY LastName
ASCE
Write the query to count the total number of
‘employees from Payments table.
SELECT COUNT(*) “Employees” FROM Payments:
Give the syntax of Having clause.
SELECT colunn_name, aggregate_function
(column_name)
FROM table_name
WHERE condition
GROUP BY column_name
HAVING aggregate_function (column_name)
:
Name any two logical operators.
And, OR
SHORT ANSWER Type Questions
1
Ans,
2.
Ans.
Write the disadvantages of SQL.
Refer to text on page no 199,
3
Which commands are used to control user's
privileges and how?
‘There are two commands that are used to control a user's
privileges
() GRANT
(ii) REVOKE,216
‘The GRANT command is used to give an existing user
privileges and REVOKE command is used to remove
Privileges. Ifa user does not exist, GRANT will create a
new user at the same time and give them all privileges.
3. Differentiate between COMMIT and ROLLBACK
command.
‘Ans, COMMIT command is used to permanent all the changes
made by DML commands, while ROLLBACK means that
it undoes all changes since the beginning of a transaction
or since a save point.
4, Howto create a database?
Ans. Refer to text on page 200,
5,Write a query on the Salespeople table, whose
output will exclude all salespeople with a rating
>= 100, unless they are located in Delhi.
Ans. SELECT * FROM Salespeople
WHERE rating < 100 OR city = ‘Dethi*;
Or SELECT * FROM Salespeople WHERE NOT
rating > = 100 OR city = ‘Delhi*:
Or SELECT * FROM Salespeople WHERE NOT
(rating > = 100 AND city <> ‘Delhi
6. Explain the use of ORDER BY clause.
Ans, Ae ORDER BY keyword is used to sort the result set
along a specified column with the SELECT command.
‘The ORDER BY keyword sorts the records in ascending
order by default. If you want to sort the records in a
descending order, you can use the DESC keyword.
Syntax
SELECT colunn_name(s)
FROM table_name
ORDER BY colunn_name(s) ASC/DES!
7. Create
FROM
WHERE IS NULL:
9. Differentiate between char(n) and varchar(n)
data types with respect to databases,
(CBSE SOP Term yy
Ans. Differentiate between char(s) and varchar(a) ae ,
follows
Tare aver anga
cs
Ttstores a feed length
string between 1 and 255,
characters.
It the value is of smaller
Fength, then it adds blank
No blanks are added by
varchar(n) even it value sot
spaces. smaller length
‘Some space is wasted init. No wastage of space in
varchar(o),
10. Write the output of the queries (i) to (iv) based
on the table FURNITURE given below.
ICBSE SQP Termin)
Table : FURNITURE
FD NAME OATEQFFURCH Coss piscoue
Boot _DowbieBed eB. 2018 16000 0
O10 Dining Table TOMAR 2020 51000 s
BOO SngleBed —19UL-2001 200000
caus Long back 20-06-2018 12000
char
1006 Gonsle Tale 17NOW2OT9 z
006 Bunkbed —otwaw20e1 28000 te
( SELECT SUM(DISCOUNT) FROM FURNITURE
WHERE COST>15000;
(ii) SELECT MAX(DATEOFPURCHASE) FROM
FURNITURE:
(ii) SELECT ~ FROM FURNITURE WHERE
DISCOUNT>S AND FID LIKE "TZ":
(iv) SELECT DATEOFPURCHASE FROM FURNITURE
WHERE NAME IN (*Dinning Table*.
“Console Table"):
Ans. ()
@siructured Query Language
i
POATEOF
{PURCHASE
ff, What are DDL ana DML?
Ans. DDL. (Data Definition Language
which provides com Ere
dropping the tables Diferon Mane,
CREATE. ALTER, DROr a
ion Language) ia part of SQL,
8s for inserting. deleting sed
i a database, Different Dhl
UPDATE, INSERT
Describe the four data types in SOL.
Refer to the text on page 200
commands are SELECT.
12.
Ans.
;
( Display the price 500 of item having code as
’ » THERE Quantity < 70;
14, Consider th N DESIG, SALARY,
List the rams the EMPLOYEE table HRA ts 25%
aE es is 10% of salary. PF is 5% of
salary. The resul
of salary. ARY, SALARY * 0.25
Name, SALARY.
Ans. SELECT &
<0
fea, SaUaRy
AS Oe ants. 05 AS PF
217
FROM EMPLOYEE
ORDER BY SALARY DESC;
§5. Write a short note on DISTI
an example.
Refer to the text on page no 205,
INCT keyword with
Ans.
16. Define UPDATE command of SOL with its basic
syntax and also give one of its example.
Ans, An UPDATE command is
modify the value stored i
specified record,
Syntax
UPDATE table_name
SET columnl = vatuel,
column2 = valuez,.
used to directly change or
in one or more fields in a
WHERE :
© Consider the table PERSONS to update the address
as Nissestien 67.
UPOATE PERSONS SET Address
issestien 67°;
17. Write a output for SOL queries (i) to (ili), which
are based on the table ITEMS.
e| Company |TCode
120| 11000 xeNITA
Tor
70|8000/santora | to2
50| 2150 |GEOKNOW | To:
10083 DIGITAL CAMERA 12x |160| e000 |DIGICLICK |
1005 |PEN DRIVE 32.68 | 600,
100 |LED SCREEN 40
1004 | CAR GPs system,
To2
4200 |STOREHOME | to3
( SELECT MaKcPrice),
ITEMS;
SELECT Price * Qty AMOUNT
FROM ITEMS WHERE Code=1004;
SELECT DISTINCT TCode FROM ITEMS;
MINCPrice) FROM
w
au
‘Ans. (i)
MAX(Price) __ MIN(Phica)
38000
oy ao
Tou
407500
1200
ay,218
18. Give the output of the following SQL.
statements, which are based on the table
APPLICATNS.
TABLE: APPLICANTS
“Ne. [WaME [FEE | GeNDER| 110 | VOINVEAR
wot /Amandeep |} 20000 | | ag | zoe
1102 [avsha | 25000 | 200
1103] ekam | 0000°} zit
oxo aun | 30000 | a 2009
1025 Jaber | «coo | om | 20
1106 |ela oo00 | 2010
1o17|Nixta | s000 | ore
1108 aura | 0000 | zoe
2109 |snaki | 38000 | zor
tot rat_—_| 25000 | ore
() SELECT NAME, JOINYEAR FROM APPLICANTS:
WHERE GENDER ="F* AND C_ID="A02":
Gi) SELECT MIN(JOINYEAR) FROM APPLICANTS
WHERE GENDER = “Mf
(iii) SELECT AVG(FEE) FROM APPLICANTS WHERE
Ans. (i)
NAME
‘Avisha
@ SS
MIN (JOINYEAR)
2008
Gi)
AVG (FEE)
31656.666
19, Write the output for SQL queries (i) to
which are based on the table CUSTOMER.
TABLE: CUSTOMER
iD ‘CNAME GENDER | SID | AREA
1001 RISHARMA Female | 101 | NORTH
1002 | MATIWARY mate | 102 | SouTH
1003 MK KHAN, mate | 103 | EAST
1008 ‘AK SINGH mate | 102 | EAST
1005 SSEN Female | 101 | west
1008 ROUBEY Mate. | 104 | NORTH
1007 | MAGARWAL, Femate | 104 | NORTH
1008 SAS FEMALE | 103 | SOUTH
1008 RK PATIL, mate | 102 | NORTH
1010 | NkRISHNAMURTY | Mate | 102_| SOUTH
() SELECT COUNT(*), GENDER FROM CUSTOMER
GROUP BY GENDER:
| Allinone | COMPUTER SCIENCE Class 199,
(i) SELECT CNAME FROM CUSTOMER WHERE
CNAME LIKE *L3':
SELECT DISTINCT AREA FROM CUSTOMER,
COUNT(*) GENDER
4 FEMALE
6 MALE
(ii) No rows selected
Gi)
DISTINCT AREA
“NORTH
SOUTH
EAST
west
20. Write the output for SQL queries (i) to (i
which are based on the table CARDEN.
TABLE: CARDEN
Geode [Color | Capac | Charges
501 | A-star | Suzuki | RED 3 ei
502,,| Innova | Toyota | WHITE | 7 | - 15
(SELECT COUNT(DISTINCT Make) FROM
CARDEN;
(i) SELECT COUNT(*) Make FROM CARDEN:
(ii) SELECT Cartiame FROM CARDEN WHERE
Capacity = 4;
Ans. (i)
‘COUNT
(DISTINCT Make)
co)
Git)
CarName
Sx4
C-Class
Atable, ITEM has been created in a database
with the following fields
ITEMCODE, ITEMNAME, QTY, PRICE
Give the SQL command to add a new field,
DISCOUNT (of type Integer) to the ITEM
table.
a. @gructured Query Language
(i) Categorize following commands i
and DML commands? n° PPE
INSERT INTO, DROPTABLE, ALTER TABLE,
SET (CBSE SQP Term
(0 ALTER TABLE ITEM ADD Discount. INT
(i) DDL means ‘Data Definition Language’. It is used to
create and mai the srt of database etn
0, DDL commands are
S01, 0 DROP TABLE, ALTER
DML is ‘Data Manipulation Language’ whi
to manipulate dataitseln. 'e* “hishis used
commands are IN
UPDATE...SET. SERT_ “INTO,
Ans.
22. Charu has to create a database named
MYEARTH in MySQL.
‘She now needs to create a table named CITY in
the database to store the records of various
cities across the globe. The table CITY has the
following structure.
Table : CITY
Field Name Data Type Remarks
ciTyCoDE CHARS)
~~ crrywane cw
SIZE INTEGER,
AVGTEMP. INTEGER
~POPULATIONRATE __NIEGER
POPULATION INTEGER,
Help her to complete the task by suggesting
appropriate SQL commands. [CBSESQP Term]
Command to create database
CREATE DATABASE MYEARTH:
Command to create table
CREATE TABLE CITY(
CITYCODE CHAR(S) PRIMARY KEY,
CITYNAME CHAR(30)
SIZE INT.
ANGTEMP INT.
POPULATIONRATE INT.
POPULATION INT.
d:
e Questions
LONG ANSWER Type (v) on the basis of
swer the questions {i) to
1 Ansroliowing tables SHOPPE and "ACCESSORIES.
TABLE: SHOPPE
Ans.
a ea
1a
Ans.
219
po
ia Same
S008 Tech shoppe _ -_
soot Geeks TeonoSoft_Netmu Pie _
S005 Hiecn Tech Store ___Nefru Place
TABLE: ACCESSORIES
Price id
No Name
01
Mother Board _
fon nes tos
ee eee
ee report oS
“Aor "6000 SOK
Rees
~ Too Mouse 350 $05
Ve 10 Hard Disk 4500 S03
perineal e008
(i) To display Name and Price of all the
Accessories in ascending order of their Price.
(i) To display Id and SName of all Shoppe
located in Nehru Place.
(ii) To display Minimum and Maximum Price of
each Name of Accessories.
(iv) To display Name, Price of all Accessories and
their respective SName, where they are
available.
(v) To display name of accessories whose price is
greater than 1000.
(@ SELECT Name, Price
FROM ACCESSORIES
ORDER BY Price:
(i) SELECT Id, SName
FROM SHOPPE
WHERE Area = ‘Nehru Place’:
SELECT MIN(Price) “Minimum Price”,
MAX(Price) “Maximum Price”, Name
FROM ACCESSORIES
GROUP BY Name:
() SELECT Name, Price, Same
FROM ACCESSORIES A, SHOPPE S
WHERE A.Id = S.1d:
but this query enable to show the
Ald and Sd are not identical. aa eal
(SELECT Name From
ACCESSORIES,
WHERE Price>ioo0;
(ii)You might also like Relational Model-Merged-Pages-1-163,166-211,214-250,253-289,292-343,346-393,396-438 PDF
Relational Model-Merged-Pages-1-163,166-211,214-250,253-289,292-343,346-393,396-438
426 pages