SlideShare a Scribd company logo
Chapter 6:
Introduction to SQL
Modern Database Management
10th Edition
Jeffrey A. Hoffer, Mary B. Prescott,
Fred R. McFadden
Introduction
 Also pronounced as “Sequel”
 A de-facto standard for relational DBMS
 Standard accepted by bodies like ANSI
and ISO
Introduction
 First commercial DBMS that support SQL
in 1979 was Oracle
 Another form of query language is
Query-by-Example (QBE) supported by
PC-based DBMSs
History
 Relational data model introduced
by Codd in 1970
 A relational DBMS project started
by IBM was system R that
included sequel as manipulation
language
History
 First commercial DBMS launched
was Oracle in 1979
 Other early DBMSs DB2, INGRES
 ANSI and ISO defined first standard
of SQL in 1986 known as SQL-86
that was further extended to SQL-
89
History
 Later two more standards known as
SQL-92 and SQL-99 were defined
 Almost all of the current DBMSs
support SQL-92 and many support
SQL-99 partially or completely
 SQL today is supported in all sort of
machines
Benefits of Standard SQL
 Reduced training cost
 Application portability
 Application longevity
 Reduced dependence on a single
vendor
 Cross-system communication
SQL
 SQL is used for any type of interaction
with the database through DBMS
 Right from creating database, tables,
views, users
 Insertion, updation, deletion of data in
the database
SQL and DBMSs
 Implementation of SQL always includes
the flavor of the particular DBMS, like in
names of data types
 Proprietary SQLs exist, like T-SQL and
PL-SQL
MS SQL Server
 The DBMS for our course is
Microsoft’s SQL Server 2000
desktop edition
 Two main tools Query Analyzer
and Enterprise Manager; both can
be used
 For SQL practice we will use QA
Terminology of SS
 Instance of SQL Server
 Instance contains different objects
like databases, security, DTS etc.
 Then databases object of SS contains
multiple databases, each database
contains multiple objects like tables,
views, users, roles etc.
Working in SS
 After installing SS, we will create
database using create command
 After this we will create tables and
other objects within this database
DDL
 Create
 Alter
 Drop
Create Command
 Creating database
CREATE DATABASE db_name
Create database exam
 Next step is to create tables
 Two approaches:
 Through SQL Create command
 Through Enterprise Manager
Create Table Command
 Create table command is used to:
 Create a table
 Define attributes of the table with data types
 Define different constraints on attributes, like
primary and foreign keys, check constraint,
not null, default value etc.
Format of Create Table
 CREATE TABLE
[ database_name.[ owner ] . | owner. ] table_name
( { < column_definition >
| column_name AS computed_column_expression
| < table_constraint >
}
| [ { PRIMARY KEY | UNIQUE } [ ,...n ] ]
)
Chevrons Explained
 < column_definition > ::= { column_name data_type }
[ DEFAULT constant_expression ]
[ < column_constraint > ] [ ...n ]
Chevrons Explained
 < column_constraint > ::= [ CONSTRAINT
constraint_name ]
{ [ NULL | NOT NULL ]
| [ { PRIMARY KEY | UNIQUE }
]
| [ [ FOREIGN KEY ]
REFERENCES ref_table [ ( ref_column ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
]
| CHECK( logical_expression )
}
CREATE TABLE Program (
prName char(4),
totSem tinyint,
prCredits smallint)
Create Table Command
CREATE TABLE Student
(stId char(5),
stName char(25),
stFName char(25),
stAdres text,
stPhone char(10),
prName char(4)
curSem smallint,
cgpa real)
Create Table
Command
CREATE TABLE Student (
stId char(5) constraint ST_PK primary key
constraint ST_CK check (stId like
‘S[0-9][0-9][0-9][0-9]'),
stName char(25) not null,
stFName char(25),
stAdres text,
stPhone char(10),
prName char(4),
curSem smallint default 1,
cgpa real)
Create Table with Constraint
stId char(5) constraint ST_PK primary key
stId char(5) primary key
CREATE TABLE Student
(stId char(5) primary key
check (stId like 'S[0-9][0-9][0-9][0-9]'),
stName char(25) not null,
stFName char(25),
stAdres text,
stPhone char(10),
prName char(4),
curSem tinyint default 1,
cgpa real)
Create Table with Constraint
 CREATE TABLE semester (
semName char(5) primary key,
stDate smalldatetime,
endDate smalldatetime,
constraint ck_date_val check
(datediff(days, stDate, endDate) between
100 and 120))
Create Table with Constraint
Alter Table Statement
 Purpose is to make changes in
the definition of a table already
created through Create statement
 Can add, drop attributes or
constraints, activate or deactivate
constraints; the format is
 ALTER TABLE table
{ [ ALTER COLUMN column_name
{ new_data_type [ ( precision [ , scale ] ) ]
[ NULL | NOT NULL ]
]
| ADD
{ [ < column_definition > ]
| column_name AS computed_column_expression
} [ ,...n ]
| DROP
{ [ CONSTRAINT ] constraint_name
| COLUMN column } [ ,...n ]
| { CHECK | NOCHECK } CONSTRAINT
{ ALL | constraint_name [ ,...n ] }
}
ALTER TABLE Student
add constraint fk_st_pr
foreign key (prName) references
Program (prName)
ALTER TABLE program
add constraint ck_totSem
check (totSem < 9)
Alter Table Command
Removing or Changing Attribute
 ALTER TABLE student
ALTER COLUMN stFName char(20)
 Alter table student
drop column curSem
 Alter table student
drop constraint ck_st_pr
Removing Tables
 TRUNCATE TABLE table_name
 Truncate table class
 Delete can also be used
 DROP TABLE table_name
Data Manipulation
Language
 Insert
 Select
 Update
Insert Statement
 To insert records into tables
 INSERT [ INTO] table
{ [ ( column_list ) ]
{ VALUES
( { DEFAULT | NULL | expression } [ ,...n] )
}
}
| DEFAULT VALUES
Insert
 COURSE (crCode, crName, crCredits,
prName)
INSERT INTO course VALUES (‘CS-211',
‘Operating Systems’, 4, ‘MCS’)
INSERT INTO course (crCode, crName)
VALUES (‘CS-316’, Database Systems’)
INSERT INTO course (‘MG-103’, ‘Intro to
Management’, NULL, NULL)
stId stName prName cgpa
S1020 Sohail Dar MCS 2.8
S1038 Shoaib Ali BCS 2.78
S1015 Tahira Ejaz MCS 3.2
S1034 Sadia Zia BIT
S1018 Arif Zia BIT 3.0
STUDENT
prName totSem prCrdts
BCS 8 134
BIT 8 132
MBA 4 65
MCS 4 64
PROGRAM
crCode crTitle crCrdts prName
CS-616 Intro to Database Systems 4 MCS
MG-314 Money & Capital Market 3 BIT
CS-516 Data Structures and Algos 4 MCS
MG-105 Introduction to Accounting 3 MBA
stId crCode semName mTerm sMrks fMrks totMrks grade gPoint
S1020 CS-616 F04 25 12.5 35 72.5 B- 2.7
S1018 MG-314 F04 26.5 10.5 39 76 B 3.1
S1015 CS-616 F04 30 10 40 80 B+ 3.5
S1015 CS-516 F04 32 12 42 86 A- 4.1
COURSE
ENROLL
Select Statement
 Maximum used command in DML
 Used not only to select certain rows but also
the columns
 Also used for different forms of product, that
is, different joins
Select
 Selecting rows from one or more
tables
 SELECT {*|col_name[,….n]}
FROM table_name
Select
Q: Get the data about students
SELECT * FROM student
Database queries
Select
Q: Give the names of the students
with the program name
SELECT stName, prName
FROM student
Database queries
Attribute Alias
 Another Name “Urf” for an attribute
SELECT {*|col_name [[AS] alias] [, …n]}
FROM tab_name
SELECT stName as ‘Student Name’ , prName
‘Program’ FROM Student
Database queries
Expression in Select
 In the column list we can also give the
expression; value of the expression is
computed and displayed
Expression Example
Q: Display the total sessional marks of each
student obtained in each subject
Select stId, crCode, mTerm + sMrks
‘Total out of 50’ from enroll
Database queries
Expression Example
Q: List the names of the students and the
program they are enrolled in, in the format
“std studies in prg”
SELECT stName + ‘ studies in ‘ + prName
FROM student
Database queries
Select Distinct
 The DISTINCT keyword is used to return
only distinct (different) values
 Just add a DISTINCT keyword to
the SELECT statement
 SELECT DISTINCT
column_name(s) FROM
table_name
Select Distinct
Q: Get the program names in which
students are enrolled
SELECT prName FROM Student
Select Distinct
Database queries
Q: Get the program names in which
students are enrolled
SELECT prName FROM Student
SELECT DISTINCT prName FROM
Student
Select Distinct
Database queries
Placing the Checks on
Rows
 Limit rows or to select certain rows, like,
 Programs of certain length, credits;
students with particular names, programs,
age, places etc.
The WHERE Clause
 We used names to limit columns, but rows
cannot be named due to the dynamicity
 We limit the rows using conditions
The WHERE Clause
Conditions are defined on the values of
one or more attributes from one or more
tables and placed in the WHERE clause
Where: Format
 SELECT [ALL|DISTINCT]
{*|culumn_list [alias][,…..n]} FROM
table_name
[WHERE <search_condition>]
< search_condition > ::=
{ [ NOT ] < predicate > | ( < search_condition > ) }
[ { AND | OR } [ NOT ] { < predicate > |
( < search_condition > ) } ]
} [ ,...n ]
< predicate > ::=
{ expression { = | < > | ! = | > | > = | ! > | < | < = | ! < }
expression
| string_expression [ NOT ] LIKE string_expression
| expression [ NOT ] BETWEEN expression AND
expression
| expression IS [ NOT ] NULL
| expression [ NOT ] IN ( subquery | expression [ ,...n ] )
| expression { = | < > | ! = | > | > = | ! > | < | < = | ! < }
{ ALL | SOME | ANY} ( subquery )
| EXISTS ( subquery )
}
Where Example
Q: Display all courses of the MCS program
Select crCode, crName, prName from
course
where prName = ‘MCS’
Database queries
Database queries
Not Operator
Inverses the predicate’s value
Q: List the course names offered to
programs other than MCS
SELECT crCode, crName, prName
FROM course
WHERE not (prName = ‘MCS’)
Database queries
SELECT crCode, crName, prName
FROM course
WHERE (prName != ‘MCS’)
The BETWEEN Operator
Checks the value in a range
Q: List the IDs of the students with course
codes having marks between 70 and 80
SELECT stId, crCode, totMrks
From ENROLL
WHERE totMrks between 70 and 80
Database queries
The IN Operator
 Checks in a list of values
Q: Give the course names of MCS and BCS
programs
SELECT crName, prName
From course
Where prName in (‘MCS’, ‘BCS’)
Database queries
SELECT crName, prName
From course
Where (prName = ‘MCS’) OR (prName =
‘BCS’)
Like Operator
Q: Display the names and credits of CS
programs
SELECT crName, crCrdts, prName FROM
course
WHERE prName like '%CS'
Database queries
“Order By” Clause
 Sorts the rows in a particular order
SELECT select_list
FROM table_source
[ WHERE search_condition ]
[ ORDER BY order_expression [ ASC | DESC ]
[,……n]
]
Order By Example
Q: Display the students’ data in the
ascending order of names
SELECT * from STUDENT
ORDER BY stName
Database queries
Practice Query
Display the name and cgpa of students for
all those students who are in second or
above semester in descending order of
names
Functions in SQL
 Built-in functions are pre-written programs
to perform specific tasks
 Accept certain arguments and return the
result
Categories of Functions
 Depending on the arguments and the return
value, categorized
 Mathematical (ABS, ROUND, SIN, SQRT)
 String (LOWER, UPPER, SUBSTRING, LEN)
 Date (DATEDIFF, DATEPART, GETDATE())
 System (USER, DATALENGTH, HOST_NAME)
 Conversion (CAST, CONVERT)
Using Functions
SELECT upper(stName),
lower(stFName), stAdres,
len(convert(char, stAdres)),
FROM student
Database queries
Aggregate Functions
 Operate on a set of rows and return a
single value, like, AVG, SUM, MAX, MIN,
STDEV
 Attribute list cannot contain other
attributes if an aggregate function is being
used
Aggregate Function Example
 SELECT avg(cgpa) as 'Average CGPA',
max(cgpa) as 'Maximum CGPA' from student
 Output is……
Database queries
Aggregate Function Example
SELECT avg(cgpa) as 'Average
CGPA', max(cgpa) as 'Maximum
CGPA' from student
SELECT convert( decimal(5,2),
avg(cgpa)) as 'Average CGPA',
max(cgpa) as 'Maximum CGPA' from
student
Database queries
Group By Clause
 SELECT stName, avg(cgpa) as
'Average CGPA', max(cgpa) as
'Maximum CGPA' from student
 SELECT prName, max(cgpa) as ‘Max
CGPA', min(cgpa) as ‘Min CGPA'
FROM student GROUP BY prName
Database queries
HAVING Clause
 We can restrict groups by using having
clause; groups satisfying having condition
will be selected
HAVING Clause
SELECT select_list
[ INTO new_table ]
FROM table_source
[ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC |
DESC ] ]
HAVING Example
SELECT prName, min(cgpa), max(cgpa)
FROM student
GROUP BY prName
HAVING max(cgpa) > 3
Where and having can be combined
Accessing Multiple
Tables
 Cartesian Product
 Inner join
 Outer Join
 Full outer join
 Semi Join
 Natural Join
Cartesian Product
 No specific command; Select is used
 Simply give the names of the tables
involved; Cartesian product will be
produced
Cartesian Product
 Produces m x n rows
 Select * from program, course
Database queries
Cartesian Product
 Certain columns can be selected, same
column name needs to be qualified
 Similarly can be applied to more than one
tables, and even can be applied on the
same table
SELECT * from Student, class, program
© Virtual University of
Pakistan
Inner join
 Only those rows from both tables are
merged that have same value for the
common attribute; equijoin
 Implemented by different methods
© Virtual University of
Pakistan
Inner join
 Common attributes need not to have same
name, but must have same domain
 Applied generally between tables having
referential integrity between them
© Virtual University of
Pakistan
© Virtual University of
Pakistan
Inner Join
 SELECT *
FROM course INNER JOIN program
ON course.prName = program.prName
 Select * FROM
Course c inner join program p
ON c.prName = p.prName
© Virtual University of
Pakistan
© Virtual University of
Pakistan
Inner Join
 Can also be performed using the where
clause, like
SELECT * FROM course, program
WHERE
course.prName =
program.prName
© Virtual University of
Pakistan
Outer Join
 Inner join plus the missing rows from one
or more tables
 Left, Right and Full Outer Joins
© Virtual University of
Pakistan
Outer Joins
 Right Outer Join: Inner join plus
rows from the non-matching rows
from right table
 Left outer join performs the same
thing but missing rows of the left
side table
© Virtual University of
Pakistan
Outer Joins
 A Left Outer Join B = B Right Outer Join
A
 Missing values are replaced with NULLs
 Full Outer Join: Inner join plus the non-
matching rows from both tables
© Virtual University of
Pakistan
Outer Join Examples
 Select * from course c LEFT
OUTER JOIN program p on
c.prName = p.prName
 Select * from program p RIGHT
OUTER JOIN course c on c.prName
= p.prName
© Virtual University of
Pakistan
© Virtual University of
Pakistan
Outer Join Examples
Select * from program p LEFT
OUTER JOIN course c on p.prName =
c.prName
Select * from course c RIGHT
OUTER JOIN program p on c.prName
= p.prName
© Virtual University of
Pakistan
Full Outer Join
SELECT * FROM program p FULL OUTER
JOIN
course c
ON p.prName = c.prName
© Virtual University of
Pakistan
© Virtual University of
Pakistan
Subqueries
 A query within a query
 Useful when condition has to be
applied against an unknown value
 Get the names of those students
who have more cgpa than that of
maximum of BCS students
© Virtual University of
Pakistan
Subqueries
 Can be used anywhere where an
expression is allowed
 Given in parentheses
 Generally in where
 Can be nested
© Virtual University of
Pakistan
Subqueries
 Careful about operator; depends whether
subquery returns single or multiple values
SELECT * from student where cgpa
> (select max(cgpa) from student where
prName = 'BCS‘)
© Virtual University of
Pakistan
© Virtual University of
Pakistan
Subqueries
SELECT * from student
WHERE cgpa =
ANY (select max(cgpa)
FROM student
GROUP BY prName)
© Virtual University of
Pakistan
Ad

More Related Content

What's hot (20)

Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Php variables (english)
Php variables (english)Php variables (english)
Php variables (english)
Mahmoud Masih Tehrani
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
topu93
 
structure and union
structure and unionstructure and union
structure and union
student
 
C tutorial
C tutorialC tutorial
C tutorial
Chukka Nikhil Chakravarthy
 
Templates
TemplatesTemplates
Templates
Pranali Chaudhari
 
Structure in c
Structure in cStructure in c
Structure in c
Prabhu Govind
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
Education Front
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
Sumit Satam
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
programming9
 
Files in C
Files in CFiles in C
Files in C
Prabu U
 
Python basics
Python basicsPython basics
Python basics
RANAALIMAJEEDRAJPUT
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
Spotle.ai
 
Basic of the C language
Basic of the C languageBasic of the C language
Basic of the C language
Sachin Verma
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
Emertxe Information Technologies Pvt Ltd
 
Django Templates
Django TemplatesDjango Templates
Django Templates
Willy Liu
 

Similar to Database queries (20)

Lecture-9-10-11-12(a-b).ppt modern database
Lecture-9-10-11-12(a-b).ppt modern databaseLecture-9-10-11-12(a-b).ppt modern database
Lecture-9-10-11-12(a-b).ppt modern database
mee23nu
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
Achmad Solichin
 
Chap 7
Chap 7Chap 7
Chap 7
Karan Patil
 
Les09
Les09Les09
Les09
Sudharsan S
 
MS SQL - Database Programming Concepts by RSolutions
MS SQL - Database Programming Concepts by RSolutionsMS SQL - Database Programming Concepts by RSolutions
MS SQL - Database Programming Concepts by RSolutions
RSolutions
 
Lab
LabLab
Lab
neelam_rawat
 
Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
Pongsakorn U-chupala
 
Fundamentals of Database management system Lab Manual.pptx
Fundamentals of Database management system Lab Manual.pptxFundamentals of Database management system Lab Manual.pptx
Fundamentals of Database management system Lab Manual.pptx
Getnet Tigabie Askale -(GM)
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
Sherif Gad
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).ppt
arjun431527
 
01 basic orders
01   basic orders01   basic orders
01 basic orders
Soufiane Hakam
 
SQL on Linux and its uses and application.pdf
SQL on Linux and its uses and application.pdfSQL on Linux and its uses and application.pdf
SQL on Linux and its uses and application.pdf
bhaveshsethi456
 
DP080_Lecture_2 SQL related document.pdf
DP080_Lecture_2 SQL related document.pdfDP080_Lecture_2 SQL related document.pdf
DP080_Lecture_2 SQL related document.pdf
MinhTran394436
 
SAS Internal Training
SAS Internal TrainingSAS Internal Training
SAS Internal Training
Amrih Muktiaji
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
Shakila Mahjabin
 
Java Database Connectivity (JDBC) with Spring Framework is a powerful combina...
Java Database Connectivity (JDBC) with Spring Framework is a powerful combina...Java Database Connectivity (JDBC) with Spring Framework is a powerful combina...
Java Database Connectivity (JDBC) with Spring Framework is a powerful combina...
demomki4
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using Oracle
Farhan Aslam
 
Dbms sql-final
Dbms  sql-finalDbms  sql-final
Dbms sql-final
NV Chandra Sekhar Nittala
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
Vibrant Technologies & Computers
 
Tactical data engineering
Tactical data engineeringTactical data engineering
Tactical data engineering
Julian Hyde
 
Lecture-9-10-11-12(a-b).ppt modern database
Lecture-9-10-11-12(a-b).ppt modern databaseLecture-9-10-11-12(a-b).ppt modern database
Lecture-9-10-11-12(a-b).ppt modern database
mee23nu
 
Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
Achmad Solichin
 
MS SQL - Database Programming Concepts by RSolutions
MS SQL - Database Programming Concepts by RSolutionsMS SQL - Database Programming Concepts by RSolutions
MS SQL - Database Programming Concepts by RSolutions
RSolutions
 
Fundamentals of Database management system Lab Manual.pptx
Fundamentals of Database management system Lab Manual.pptxFundamentals of Database management system Lab Manual.pptx
Fundamentals of Database management system Lab Manual.pptx
Getnet Tigabie Askale -(GM)
 
chap 7.ppt(sql).ppt
chap 7.ppt(sql).pptchap 7.ppt(sql).ppt
chap 7.ppt(sql).ppt
arjun431527
 
SQL on Linux and its uses and application.pdf
SQL on Linux and its uses and application.pdfSQL on Linux and its uses and application.pdf
SQL on Linux and its uses and application.pdf
bhaveshsethi456
 
DP080_Lecture_2 SQL related document.pdf
DP080_Lecture_2 SQL related document.pdfDP080_Lecture_2 SQL related document.pdf
DP080_Lecture_2 SQL related document.pdf
MinhTran394436
 
Java Database Connectivity (JDBC) with Spring Framework is a powerful combina...
Java Database Connectivity (JDBC) with Spring Framework is a powerful combina...Java Database Connectivity (JDBC) with Spring Framework is a powerful combina...
Java Database Connectivity (JDBC) with Spring Framework is a powerful combina...
demomki4
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using Oracle
Farhan Aslam
 
Tactical data engineering
Tactical data engineeringTactical data engineering
Tactical data engineering
Julian Hyde
 
Ad

More from laiba29012 (9)

1610374430-week15b.pptx
1610374430-week15b.pptx1610374430-week15b.pptx
1610374430-week15b.pptx
laiba29012
 
Lec4.ppt
Lec4.pptLec4.ppt
Lec4.ppt
laiba29012
 
Network_layer_addressing.pptx
Network_layer_addressing.pptxNetwork_layer_addressing.pptx
Network_layer_addressing.pptx
laiba29012
 
Lecture-6(a-b).pptx
Lecture-6(a-b).pptxLecture-6(a-b).pptx
Lecture-6(a-b).pptx
laiba29012
 
Access Methods and File System Mounting.pptx
Access Methods and File System Mounting.pptxAccess Methods and File System Mounting.pptx
Access Methods and File System Mounting.pptx
laiba29012
 
OS memory management
OS memory management OS memory management
OS memory management
laiba29012
 
executive summary ppt ent.pptx
executive summary ppt ent.pptxexecutive summary ppt ent.pptx
executive summary ppt ent.pptx
laiba29012
 
lecture-13.pptx
lecture-13.pptxlecture-13.pptx
lecture-13.pptx
laiba29012
 
GYM SERVICES.pptx
GYM SERVICES.pptxGYM SERVICES.pptx
GYM SERVICES.pptx
laiba29012
 
1610374430-week15b.pptx
1610374430-week15b.pptx1610374430-week15b.pptx
1610374430-week15b.pptx
laiba29012
 
Network_layer_addressing.pptx
Network_layer_addressing.pptxNetwork_layer_addressing.pptx
Network_layer_addressing.pptx
laiba29012
 
Lecture-6(a-b).pptx
Lecture-6(a-b).pptxLecture-6(a-b).pptx
Lecture-6(a-b).pptx
laiba29012
 
Access Methods and File System Mounting.pptx
Access Methods and File System Mounting.pptxAccess Methods and File System Mounting.pptx
Access Methods and File System Mounting.pptx
laiba29012
 
OS memory management
OS memory management OS memory management
OS memory management
laiba29012
 
executive summary ppt ent.pptx
executive summary ppt ent.pptxexecutive summary ppt ent.pptx
executive summary ppt ent.pptx
laiba29012
 
lecture-13.pptx
lecture-13.pptxlecture-13.pptx
lecture-13.pptx
laiba29012
 
GYM SERVICES.pptx
GYM SERVICES.pptxGYM SERVICES.pptx
GYM SERVICES.pptx
laiba29012
 
Ad

Recently uploaded (20)

Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 

Database queries

  • 1. Chapter 6: Introduction to SQL Modern Database Management 10th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden
  • 2. Introduction  Also pronounced as “Sequel”  A de-facto standard for relational DBMS  Standard accepted by bodies like ANSI and ISO
  • 3. Introduction  First commercial DBMS that support SQL in 1979 was Oracle  Another form of query language is Query-by-Example (QBE) supported by PC-based DBMSs
  • 4. History  Relational data model introduced by Codd in 1970  A relational DBMS project started by IBM was system R that included sequel as manipulation language
  • 5. History  First commercial DBMS launched was Oracle in 1979  Other early DBMSs DB2, INGRES  ANSI and ISO defined first standard of SQL in 1986 known as SQL-86 that was further extended to SQL- 89
  • 6. History  Later two more standards known as SQL-92 and SQL-99 were defined  Almost all of the current DBMSs support SQL-92 and many support SQL-99 partially or completely  SQL today is supported in all sort of machines
  • 7. Benefits of Standard SQL  Reduced training cost  Application portability  Application longevity  Reduced dependence on a single vendor  Cross-system communication
  • 8. SQL  SQL is used for any type of interaction with the database through DBMS  Right from creating database, tables, views, users  Insertion, updation, deletion of data in the database
  • 9. SQL and DBMSs  Implementation of SQL always includes the flavor of the particular DBMS, like in names of data types  Proprietary SQLs exist, like T-SQL and PL-SQL
  • 10. MS SQL Server  The DBMS for our course is Microsoft’s SQL Server 2000 desktop edition  Two main tools Query Analyzer and Enterprise Manager; both can be used  For SQL practice we will use QA
  • 11. Terminology of SS  Instance of SQL Server  Instance contains different objects like databases, security, DTS etc.  Then databases object of SS contains multiple databases, each database contains multiple objects like tables, views, users, roles etc.
  • 12. Working in SS  After installing SS, we will create database using create command  After this we will create tables and other objects within this database
  • 14. Create Command  Creating database CREATE DATABASE db_name Create database exam  Next step is to create tables  Two approaches:  Through SQL Create command  Through Enterprise Manager
  • 15. Create Table Command  Create table command is used to:  Create a table  Define attributes of the table with data types  Define different constraints on attributes, like primary and foreign keys, check constraint, not null, default value etc.
  • 16. Format of Create Table  CREATE TABLE [ database_name.[ owner ] . | owner. ] table_name ( { < column_definition > | column_name AS computed_column_expression | < table_constraint > } | [ { PRIMARY KEY | UNIQUE } [ ,...n ] ] )
  • 17. Chevrons Explained  < column_definition > ::= { column_name data_type } [ DEFAULT constant_expression ] [ < column_constraint > ] [ ...n ]
  • 18. Chevrons Explained  < column_constraint > ::= [ CONSTRAINT constraint_name ] { [ NULL | NOT NULL ] | [ { PRIMARY KEY | UNIQUE } ] | [ [ FOREIGN KEY ] REFERENCES ref_table [ ( ref_column ) ] [ ON DELETE { CASCADE | NO ACTION } ] [ ON UPDATE { CASCADE | NO ACTION } ] ] | CHECK( logical_expression ) }
  • 19. CREATE TABLE Program ( prName char(4), totSem tinyint, prCredits smallint) Create Table Command
  • 20. CREATE TABLE Student (stId char(5), stName char(25), stFName char(25), stAdres text, stPhone char(10), prName char(4) curSem smallint, cgpa real) Create Table Command
  • 21. CREATE TABLE Student ( stId char(5) constraint ST_PK primary key constraint ST_CK check (stId like ‘S[0-9][0-9][0-9][0-9]'), stName char(25) not null, stFName char(25), stAdres text, stPhone char(10), prName char(4), curSem smallint default 1, cgpa real) Create Table with Constraint
  • 22. stId char(5) constraint ST_PK primary key stId char(5) primary key
  • 23. CREATE TABLE Student (stId char(5) primary key check (stId like 'S[0-9][0-9][0-9][0-9]'), stName char(25) not null, stFName char(25), stAdres text, stPhone char(10), prName char(4), curSem tinyint default 1, cgpa real) Create Table with Constraint
  • 24.  CREATE TABLE semester ( semName char(5) primary key, stDate smalldatetime, endDate smalldatetime, constraint ck_date_val check (datediff(days, stDate, endDate) between 100 and 120)) Create Table with Constraint
  • 25. Alter Table Statement  Purpose is to make changes in the definition of a table already created through Create statement  Can add, drop attributes or constraints, activate or deactivate constraints; the format is
  • 26.  ALTER TABLE table { [ ALTER COLUMN column_name { new_data_type [ ( precision [ , scale ] ) ] [ NULL | NOT NULL ] ] | ADD { [ < column_definition > ] | column_name AS computed_column_expression } [ ,...n ] | DROP { [ CONSTRAINT ] constraint_name | COLUMN column } [ ,...n ] | { CHECK | NOCHECK } CONSTRAINT { ALL | constraint_name [ ,...n ] } }
  • 27. ALTER TABLE Student add constraint fk_st_pr foreign key (prName) references Program (prName) ALTER TABLE program add constraint ck_totSem check (totSem < 9) Alter Table Command
  • 28. Removing or Changing Attribute  ALTER TABLE student ALTER COLUMN stFName char(20)  Alter table student drop column curSem  Alter table student drop constraint ck_st_pr
  • 29. Removing Tables  TRUNCATE TABLE table_name  Truncate table class  Delete can also be used  DROP TABLE table_name
  • 31. Insert Statement  To insert records into tables  INSERT [ INTO] table { [ ( column_list ) ] { VALUES ( { DEFAULT | NULL | expression } [ ,...n] ) } } | DEFAULT VALUES
  • 32. Insert  COURSE (crCode, crName, crCredits, prName) INSERT INTO course VALUES (‘CS-211', ‘Operating Systems’, 4, ‘MCS’) INSERT INTO course (crCode, crName) VALUES (‘CS-316’, Database Systems’) INSERT INTO course (‘MG-103’, ‘Intro to Management’, NULL, NULL)
  • 33. stId stName prName cgpa S1020 Sohail Dar MCS 2.8 S1038 Shoaib Ali BCS 2.78 S1015 Tahira Ejaz MCS 3.2 S1034 Sadia Zia BIT S1018 Arif Zia BIT 3.0 STUDENT prName totSem prCrdts BCS 8 134 BIT 8 132 MBA 4 65 MCS 4 64 PROGRAM crCode crTitle crCrdts prName CS-616 Intro to Database Systems 4 MCS MG-314 Money & Capital Market 3 BIT CS-516 Data Structures and Algos 4 MCS MG-105 Introduction to Accounting 3 MBA stId crCode semName mTerm sMrks fMrks totMrks grade gPoint S1020 CS-616 F04 25 12.5 35 72.5 B- 2.7 S1018 MG-314 F04 26.5 10.5 39 76 B 3.1 S1015 CS-616 F04 30 10 40 80 B+ 3.5 S1015 CS-516 F04 32 12 42 86 A- 4.1 COURSE ENROLL
  • 34. Select Statement  Maximum used command in DML  Used not only to select certain rows but also the columns  Also used for different forms of product, that is, different joins
  • 35. Select  Selecting rows from one or more tables  SELECT {*|col_name[,….n]} FROM table_name
  • 36. Select Q: Get the data about students SELECT * FROM student
  • 38. Select Q: Give the names of the students with the program name SELECT stName, prName FROM student
  • 40. Attribute Alias  Another Name “Urf” for an attribute SELECT {*|col_name [[AS] alias] [, …n]} FROM tab_name SELECT stName as ‘Student Name’ , prName ‘Program’ FROM Student
  • 42. Expression in Select  In the column list we can also give the expression; value of the expression is computed and displayed
  • 43. Expression Example Q: Display the total sessional marks of each student obtained in each subject Select stId, crCode, mTerm + sMrks ‘Total out of 50’ from enroll
  • 45. Expression Example Q: List the names of the students and the program they are enrolled in, in the format “std studies in prg” SELECT stName + ‘ studies in ‘ + prName FROM student
  • 47. Select Distinct  The DISTINCT keyword is used to return only distinct (different) values
  • 48.  Just add a DISTINCT keyword to the SELECT statement  SELECT DISTINCT column_name(s) FROM table_name Select Distinct
  • 49. Q: Get the program names in which students are enrolled SELECT prName FROM Student Select Distinct
  • 51. Q: Get the program names in which students are enrolled SELECT prName FROM Student SELECT DISTINCT prName FROM Student Select Distinct
  • 53. Placing the Checks on Rows  Limit rows or to select certain rows, like,  Programs of certain length, credits; students with particular names, programs, age, places etc.
  • 54. The WHERE Clause  We used names to limit columns, but rows cannot be named due to the dynamicity  We limit the rows using conditions
  • 55. The WHERE Clause Conditions are defined on the values of one or more attributes from one or more tables and placed in the WHERE clause
  • 56. Where: Format  SELECT [ALL|DISTINCT] {*|culumn_list [alias][,…..n]} FROM table_name [WHERE <search_condition>]
  • 57. < search_condition > ::= { [ NOT ] < predicate > | ( < search_condition > ) } [ { AND | OR } [ NOT ] { < predicate > | ( < search_condition > ) } ] } [ ,...n ] < predicate > ::= { expression { = | < > | ! = | > | > = | ! > | < | < = | ! < } expression | string_expression [ NOT ] LIKE string_expression | expression [ NOT ] BETWEEN expression AND expression | expression IS [ NOT ] NULL | expression [ NOT ] IN ( subquery | expression [ ,...n ] ) | expression { = | < > | ! = | > | > = | ! > | < | < = | ! < } { ALL | SOME | ANY} ( subquery ) | EXISTS ( subquery ) }
  • 58. Where Example Q: Display all courses of the MCS program Select crCode, crName, prName from course where prName = ‘MCS’
  • 61. Not Operator Inverses the predicate’s value Q: List the course names offered to programs other than MCS SELECT crCode, crName, prName FROM course WHERE not (prName = ‘MCS’)
  • 63. SELECT crCode, crName, prName FROM course WHERE (prName != ‘MCS’)
  • 64. The BETWEEN Operator Checks the value in a range Q: List the IDs of the students with course codes having marks between 70 and 80 SELECT stId, crCode, totMrks From ENROLL WHERE totMrks between 70 and 80
  • 66. The IN Operator  Checks in a list of values Q: Give the course names of MCS and BCS programs SELECT crName, prName From course Where prName in (‘MCS’, ‘BCS’)
  • 68. SELECT crName, prName From course Where (prName = ‘MCS’) OR (prName = ‘BCS’)
  • 69. Like Operator Q: Display the names and credits of CS programs SELECT crName, crCrdts, prName FROM course WHERE prName like '%CS'
  • 71. “Order By” Clause  Sorts the rows in a particular order SELECT select_list FROM table_source [ WHERE search_condition ] [ ORDER BY order_expression [ ASC | DESC ] [,……n] ]
  • 72. Order By Example Q: Display the students’ data in the ascending order of names SELECT * from STUDENT ORDER BY stName
  • 74. Practice Query Display the name and cgpa of students for all those students who are in second or above semester in descending order of names
  • 75. Functions in SQL  Built-in functions are pre-written programs to perform specific tasks  Accept certain arguments and return the result
  • 76. Categories of Functions  Depending on the arguments and the return value, categorized  Mathematical (ABS, ROUND, SIN, SQRT)  String (LOWER, UPPER, SUBSTRING, LEN)  Date (DATEDIFF, DATEPART, GETDATE())  System (USER, DATALENGTH, HOST_NAME)  Conversion (CAST, CONVERT)
  • 77. Using Functions SELECT upper(stName), lower(stFName), stAdres, len(convert(char, stAdres)), FROM student
  • 79. Aggregate Functions  Operate on a set of rows and return a single value, like, AVG, SUM, MAX, MIN, STDEV  Attribute list cannot contain other attributes if an aggregate function is being used
  • 80. Aggregate Function Example  SELECT avg(cgpa) as 'Average CGPA', max(cgpa) as 'Maximum CGPA' from student  Output is……
  • 82. Aggregate Function Example SELECT avg(cgpa) as 'Average CGPA', max(cgpa) as 'Maximum CGPA' from student SELECT convert( decimal(5,2), avg(cgpa)) as 'Average CGPA', max(cgpa) as 'Maximum CGPA' from student
  • 84. Group By Clause  SELECT stName, avg(cgpa) as 'Average CGPA', max(cgpa) as 'Maximum CGPA' from student  SELECT prName, max(cgpa) as ‘Max CGPA', min(cgpa) as ‘Min CGPA' FROM student GROUP BY prName
  • 86. HAVING Clause  We can restrict groups by using having clause; groups satisfying having condition will be selected
  • 87. HAVING Clause SELECT select_list [ INTO new_table ] FROM table_source [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ] ]
  • 88. HAVING Example SELECT prName, min(cgpa), max(cgpa) FROM student GROUP BY prName HAVING max(cgpa) > 3
  • 89. Where and having can be combined
  • 90. Accessing Multiple Tables  Cartesian Product  Inner join  Outer Join  Full outer join  Semi Join  Natural Join
  • 91. Cartesian Product  No specific command; Select is used  Simply give the names of the tables involved; Cartesian product will be produced
  • 92. Cartesian Product  Produces m x n rows  Select * from program, course
  • 94. Cartesian Product  Certain columns can be selected, same column name needs to be qualified  Similarly can be applied to more than one tables, and even can be applied on the same table SELECT * from Student, class, program
  • 95. © Virtual University of Pakistan Inner join  Only those rows from both tables are merged that have same value for the common attribute; equijoin  Implemented by different methods
  • 96. © Virtual University of Pakistan Inner join  Common attributes need not to have same name, but must have same domain  Applied generally between tables having referential integrity between them
  • 97. © Virtual University of Pakistan
  • 98. © Virtual University of Pakistan Inner Join  SELECT * FROM course INNER JOIN program ON course.prName = program.prName  Select * FROM Course c inner join program p ON c.prName = p.prName
  • 99. © Virtual University of Pakistan
  • 100. © Virtual University of Pakistan Inner Join  Can also be performed using the where clause, like SELECT * FROM course, program WHERE course.prName = program.prName
  • 101. © Virtual University of Pakistan Outer Join  Inner join plus the missing rows from one or more tables  Left, Right and Full Outer Joins
  • 102. © Virtual University of Pakistan Outer Joins  Right Outer Join: Inner join plus rows from the non-matching rows from right table  Left outer join performs the same thing but missing rows of the left side table
  • 103. © Virtual University of Pakistan Outer Joins  A Left Outer Join B = B Right Outer Join A  Missing values are replaced with NULLs  Full Outer Join: Inner join plus the non- matching rows from both tables
  • 104. © Virtual University of Pakistan Outer Join Examples  Select * from course c LEFT OUTER JOIN program p on c.prName = p.prName  Select * from program p RIGHT OUTER JOIN course c on c.prName = p.prName
  • 105. © Virtual University of Pakistan
  • 106. © Virtual University of Pakistan Outer Join Examples Select * from program p LEFT OUTER JOIN course c on p.prName = c.prName Select * from course c RIGHT OUTER JOIN program p on c.prName = p.prName
  • 107. © Virtual University of Pakistan
  • 108. Full Outer Join SELECT * FROM program p FULL OUTER JOIN course c ON p.prName = c.prName
  • 109. © Virtual University of Pakistan
  • 110. © Virtual University of Pakistan Subqueries  A query within a query  Useful when condition has to be applied against an unknown value  Get the names of those students who have more cgpa than that of maximum of BCS students
  • 111. © Virtual University of Pakistan Subqueries  Can be used anywhere where an expression is allowed  Given in parentheses  Generally in where  Can be nested
  • 112. © Virtual University of Pakistan Subqueries  Careful about operator; depends whether subquery returns single or multiple values SELECT * from student where cgpa > (select max(cgpa) from student where prName = 'BCS‘)
  • 113. © Virtual University of Pakistan
  • 114. © Virtual University of Pakistan Subqueries SELECT * from student WHERE cgpa = ANY (select max(cgpa) FROM student GROUP BY prName)
  • 115. © Virtual University of Pakistan