Upload
aisha-khan
View
220
Download
0
Embed Size (px)
Citation preview
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 1/57
Prepared By Ms.Nadia Shah 1
Design and ImplementationDesign and ImplementationBy Lect: Mst. Nadia ShahBy Lect: Mst. Nadia Shah
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 2/57
Prepared By Ms.Nadia Shah 2
An Overview of An Overview of
SQLSQL
SQL stands for SQL stands for SStructuredtructured QQueryuery LLanguage.anguage.
It is the most commonly used relationalIt is the most commonly used relational
database language today.database language today.
SQL works with a variety of different fourthSQL works with a variety of different fourth--
generation (4GL) programming languages,generation (4GL) programming languages,
such as Visual Basic.such as Visual Basic.
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 3/57
Prepared By Ms.Nadia Shah 3
SQL is used for:SQL is used for:
Data ManipulationData Manipulation
Data DefinitionData Definition Data AdministrationData Administration
All are expressed as an SQL statement All are expressed as an SQL statement
or command.or command.
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 4/57
Prepared By Ms.Nadia Shah 4
SQLSQL
RequirementsRequirements
SQL is a free form language so there is noSQL is a free form language so there is no
limit to the number of words per line or fixedlimit to the number of words per line or fixed
line break.line break.
Syntax statements, words or phrases areSyntax statements, words or phrases are
always in lower case; keywords are inalways in lower case; keywords are in
uppercase.uppercase. Not all versions are case sensitive! Not all versions are case sensitive!
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 5/57
Prepared By Ms.Nadia Shah 5
SQL is a Relational DatabaseSQL is a Relational Database
Represent all info in database as tablesRepresent all info in database as tables
Use one highUse one high--level language for structuring,level language for structuring,querying, and changing info in the databasequerying, and changing info in the database
Support the main relational operationsSupport the main relational operations
Support alternate ways of looking at data inSupport alternate ways of looking at data intablestables
Support Mechanisms for integrity, authorization,Support Mechanisms for integrity, authorization,transactions, and recoverytransactions, and recovery
A Fully Relational Database Management System must:A Fully Relational Database Management System must:
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 6/57
Prepared By Ms.Nadia Shah 6
DesignDesign
SQL represents all information in the
form of tables
Supports three relational operations:
selection, projection, and join. These
are for specifying exactly what data you
want to display or use
S Q L
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 7/57
Prepared By Ms.Nadia Shah 7
SQL Data Manipulation Language
(DML)
SQL (Structured Query Language) is a syntax forexecuting queries. But the SQL language also
includes a syntax to update, insert, and deleterecords.These query and update commands together formthe Data Manipulation Language (DML) part of SQL:
SELECT-
extracts data from a database tableUPDATE - updates data in a database tableDELETE - deletes data from a database tableINSERT INTO - inserts new data into adatabase table
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 8/57
Prepared By Ms.Nadia Shah 8
SQL Data Definition Language
(DDL) The Data Definition Language (DDL) part of SQL permits
database tables to be created or deleted. We can also defineindexes (keys), specify links between tables, and impose
constraints between database tables. The most important DDL statements in SQL are:
CREATE TABLE - creates a new database table
ALTER TABLE - alters (changes) a database table
DROP TABLE - deletes a database table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 9/57
Prepared By Ms.Nadia Shah 9
Using SQLUsing SQL
SQL statements can be embedded into a programSQL statements can be embedded into a program
( Visual Basic, MS Access)( Visual Basic, MS Access)
OROR
SQL statements can be entered directly at theSQL statements can be entered directly at the
command prompt of the SQL software beingcommand prompt of the SQL software being
used (such as mySQL)used (such as mySQL)
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 10/57
Prepared By Ms.Nadia Shah 10
Using SQLUsing SQL
To begin, you must first CREATE a database usingTo begin, you must first CREATE a database using
the following SQL statement:the following SQL statement:
CREATE DATABASE database_nameCREATE DATABASE database_name
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 11/57
Prepared By Ms.Nadia Shah 11
Using SQLUsing SQL
To create a table in the current database,
use the CREATE TABLE keyword
CREATE TABLE authorsCREATE TABLE authors(auth_id int(9) not null,(auth_id int(9) not null,auth_name char(40) not null)auth_name char(40) not null)
auth_id auth_name
(9 digit int) (40 char string)
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 12/57
Prepared By Ms.Nadia Shah 12
Data InputData Input
Putting data into a table is accomplishedPutting data into a table is accomplishedusing the keywordusing the keyword INSERT
pub_id pub_name address state
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2nd Street DC
1120 Algodata Infosys 3 3rd Street CA
Table is updated with new informationTable is updated with new information
INSERT INTO publishersINSERT INTO publishers
VALUES (¶0010·, ¶pragmatics·, ¶4 4VALUES (¶0010·, ¶pragmatics·, ¶4 4thth Ln·, ¶chicago·, ¶il·)Ln·, ¶chicago·, ¶il·)
pub_id pub_name address state
0010 Pragmatics 4 4th Ln IL
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2
nd
Street DC1120 Algodata Infosys 3 3rd Street CA
Keyword
Variable
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 13/57
Prepared By Ms.Nadia Shah 13
Using SQLUsing SQL
DROP TABLE authorsDROP TABLE authors
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
The DROP statement is also used to delete
an entire database & Tables as well.
DROP removed the Table and returned
the memory to system
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 14/57
Prepared By Ms.Nadia Shah 14
Rows
describe the
Occurrence of an Entity
Table DesignTable Design
Name Address
Jane Doe 123 Main Street
John Smith 456 Second Street
Mary Poe 789 Third Ave
Columns describe one
characteristic of the entity
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 15/57
Prepared By Ms.Nadia Shah 15
Basic structureBasic structure
of an SQL queryof an SQL query
General
Structure
SELECT, ALL / DISTINCT, *,
AS, FROM, WHERE
Comparison IN, BETWEEN, LIKE "% _"
Grouping GROUP BY, HAVING,
COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )
Display Order ORDER BY, ASC / DESC
LogicalOperators
AND, OR, NOT
Output INTO TABLE / CURSOR
TO FILE [ADDITIVE], TO PRINTER, TO SCREEN
Union UNION
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 16/57
Prepared By Ms.Nadia Shah 16
SQL The SELECT Statement
The SELECT statement is used to select data
from a table. The tabular result is stored in a
result table (called the result-set). Syntax
± SELECT column_name(s)
± FROM table_name
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 17/57
Prepared By Ms.Nadia Shah 17
Using SQLUsing SQL
SELECT auth_name, auth_citySELECT auth_name, auth_city
FROM publishersFROM publishers
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI
000000001 John Smith Taylor MI
auth_name auth_city
Jane Doe Dearborn
John Smith Taylor
If you only want to display the author¶s
name and city from the following table:
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 18/57
Prepared By Ms.Nadia Shah 18
Data Retrieval (Queries)Data Retrieval (Queries)
Queries search the database, fetch info,Queries search the database, fetch info,and display it. This is done using theand display it. This is done using thekeywordkeyword SELECT
SELECT * FROM publishersSELECT * FROM publisherspub_id pub_name address state
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2nd Street DC
1120 Algodata Infosys 3 3rd Street CA
TheThe ** Operator asks for every column inOperator asks for every column in
the table.the table.
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 19/57
Prepared By Ms.Nadia Shah 19
Using the DISTINCT keyword To select ALL values from the column named
"Company" we use a SELECT statement like this:
SELECT DISTINCT Company
FROM OrdersOrders
Company OrderNumber
Sega 3412
W3Schools 2312
Trio 4678
W3Schools 6798
Company
Sega
W3Schools
Trio
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 20/57
Prepared By Ms.Nadia Shah 20
Data Retrieval (WHERE)Data Retrieval (WHERE)
Queries can be more specific with a few moreQueries can be more specific with a few morelines. Operator arelines. Operator are =, <> ,> ,< , >= ,<=, =, <> ,> ,< , >= ,<=,
BETWEEN, LIKE, IN are used in where clauseBETWEEN, LIKE, IN are used in where clause
pub_id pub_name address state
0736 New Age Books 1 1st Street MA
0987 Binnet & Hardley 2 2nd Street DC
1120 Algodata Infosys 3 3rd Street CA
Only publishers in CA are displayedOnly publishers in CA are displayed
SELECT *SELECT *from publishersfrom publishers
where state = ¶CA·where state = ¶CA·
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 21/57
Prepared By Ms.Nadia Shah 21
Comparison Operators
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 22/57
Prepared By Ms.Nadia Shah 22
SELECT Command Involving a
Comparison
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 23/57
Prepared By Ms.Nadia Shah 23
Compound Conditions
Compound conditions
± Formed by connecting two or more simple
conditions ± Uses AND, OR, and NOT operators
AND: all conditions must be true
OR: any one of conditions is true
NOT: reverses the truth of the originalcondition
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 24/57
Prepared By Ms.Nadia Shah 24
SELECT Command Involving an
AND Condition
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 25/57
Prepared By Ms.Nadia Shah 25
SELECT Command Involving an
OR Condition
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 26/57
Prepared By Ms.Nadia Shah 26
SELECT Command Involving a
NOT Condition
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 27/57
Prepared By Ms.Nadia Shah 27
Use of BETWEEN
BETWEEN operator
± Not an essential feature
± Can arrive at same answer without it using AND
± Does make certain SELECT commands
simpler
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 28/57
Prepared By Ms.Nadia Shah 28
SELECT Command Involving a
BETWEEN Condition
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 29/57
Prepared By Ms.Nadia Shah 29
Using an Alias ³AS´
Tables listed in the FROM clause can be
given an alternative name ± Create alias by typing the name of the table
± Press the space bar
± Type the name of the alias (no commas or periods are necessary)
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 30/57
Prepared By Ms.Nadia Shah 30
Using LIKE The following SQL statement will return persons
with first names that start with an 'O':
SELECT * FROM Persons
WHERE FirstName LIKE 'O%'
The following SQL statement will return persons
with first names that end with an 'a':
SELECT * FROM Persons
WHERE FirstName LIKE '%a'
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 31/57
Prepared By Ms.Nadia Shah 31
Using Functions
SQL has functions to calculate
± Sums
± Averages
± Counts
± Maximum values
± Minimum values
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 32/57
Prepared By Ms.Nadia Shah 32
SQL Functions
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 33/57
Prepared By Ms.Nadia Shah 33
SELECT Command to Count
Rows
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 34/57
Prepared By Ms.Nadia Shah 34
SELECT Command to Calculate a
COUNT and a SUM
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 35/57
Prepared By Ms.Nadia Shah 35
Using AVG, MAX, and MIN
AVG, MAX and MIN functions are similar
to the SUM
SUM, AVG, MAX and MIN functions
ignore (eliminate) null values
± Null values can cause strange results whencalculated
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 36/57
Prepared By Ms.Nadia Shah 36
SELECT Command With Several
Functions
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 37/57
Prepared By Ms.Nadia Shah 37
Use of ORDER BY
Use the ORDER BY command to list
data in a specific order The column on which data is to be sorted
is called a sort key or simply key
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 38/57
Prepared By Ms.Nadia Shah 38
ORDER BY
ORDER BY clause is used for data is in
ASC or DESC order
SELECT * FROM mytable
ORDER BY salary ASC
OR
ORDER BY salary DESC
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 39/57
Prepared By Ms.Nadia Shah 39
SQL Query Clauses andOperators
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 40/57
Prepared By Ms.Nadia Shah 40
Types of TablesTypes of Tables
U ser Tables:U ser Tables: contain information that iscontain information that isthe database management systemthe database management system
System Tables:System Tables: contain the databasecontain the database
description, kept up to date by DBMSdescription, kept up to date by DBMSitself itself
There are two types of tables which make upThere are two types of tables which make up
a relational database in SQLa relational database in SQL
Relation Table
Tuple Row
Attribute Column
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 41/57
Prepared By Ms.Nadia Shah 41
Using SQLUsing SQL
UPDATE authorsUPDATE authorsSET auth_name=¶hello·SET auth_name=¶hello·
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI000000001 John Smith Taylor MI
To Update information in a database use
the UPDATE keyword
HelloHello
Sets all auth_name fields to helloSets all auth_name fields to hello
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 42/57
Prepared By Ms.Nadia Shah 42
Using SQLUsing SQL
ALTER TABLE authorsALTER TABLE authorsADD birth_date datetime nullADD birth_date datetime null
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI000000001 John Smith Taylor MI
To change a table in a database use ALTER
TABLE. ADD adds a characteristic.
ADD puts a new column in the table
called birth_date
birth_date
.
.
Type Initializer
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 43/57
Prepared By Ms.Nadia Shah 43
Using SQLUsing SQL
ALTER TABLE authorsALTER TABLE authorsDROP birth_dateDROP birth_date
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI000000001 John Smith Taylor MI
To delete a column or row, use the
keyword DROP
DROP removed the birth_date
characteristic from the table
auth_state
.
.
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 44/57
Prepared By Ms.Nadia Shah 44
Using SQLUsing SQL
DELETE from authorsDELETE from authorsWHERE auth_name=¶John Smith·WHERE auth_name=¶John Smith·
auth_id auth_name auth_city auth_state
123456789 Jane Doe Dearborn MI000000001 John Smith Taylor MI
To delete data from a table, use
the DELETE statement:
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 45/57
Prepared By Ms.Nadia Shah 45
Using GROUP BY
GROUP BY command allows data to be
grouped in a particular order Statistics are calculated on the groups
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 46/57
Prepared By Ms.Nadia Shah 46
Grouping Column
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 47/57
Prepared By Ms.Nadia Shah 47
Query Using a HAVING Clause
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 48/57
Prepared By Ms.Nadia Shah 48
HAVING vs. WHERE
WHERE clause limits rows
HAVING clause limits groups
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 49/57
Prepared By Ms.Nadia Shah 49
Joining Two Tables
JOINS
Two methods
± Find rows in the two tables that haveidentical values in matching columns
and
± Use the appropriate conditions in the
WHERE clause
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 50/57
Prepared By Ms.Nadia Shah 50
Multiple Tables:Multiple Tables:
SQL provides a convenient operation toSQL provides a convenient operation to
retrieve information from multiple tables.retrieve information from multiple tables.
ThisThis operationoperation isis calledcalled join join..
TheThe join join operationoperation willwill combinecombine thethe tablestables intointo
oneone largelarge tabletable withwith allall possible possible combinationscombinations
(Math(Math:: CartesianCartesian Product),Product), andand thenthen itit willwill filter filter
thethe rowsrows of of thisthis combinedcombined tabletable toto yieldyield usefulusefulinformationinformation..
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 51/57
Prepared By Ms.Nadia Shah 51
SQL Joins
Joins are used to combine the contents of two or moretables and produce a result set into a single table thatincorporates rows and columns from each table.Tables are typically joined using data that they have
in common.
Join conditions can be specified in either the FROMor WHERE clauses, specifying them in the FROMclause is recommended. WHERE and HAVINGclauses can also contain search conditions to further filter the rows selected by the join conditions.
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 52/57
Prepared By Ms.Nadia Shah 52
Types of joins
1. Equi joins
i. Inner join
ii. Outer join
a. Left outer join or left joiniii. Right outer join or right join
a. Full outer join or full join
iv. Cross join
v. Self join
2. Non equi joins.
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 53/57
Prepared By Ms.Nadia Shah 53
Equi joins
In equi joins we use equality operator like =
It returns all the columns in both tables, and returns onlythe rows for which there is an equal value in the joincolumn.
Both the tables have a common column .
Examples of equi joins
± Inner join
± Outer join
± Cross join
± Self join
Inner join
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 54/57
Prepared By Ms.Nadia Shah 54
Inner join
An inner join is a join in which the values in the columns being joined arecompared using a comparison operator
Inner joins use a comparison operator to match rows from two tables basedon the values in common columns from each table.
An INNER JOIN query returns one row for each pair or matching rows inthe tables being joined.
The result set of the inner join contains rows having the matched value of thecommon column.
syntax:-
( SELECT * FROM authors INNER JOIN publishers ON authors. city =
publishers. city )Where authors and publishers are the tables and city is the common columnin both the tables.
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 55/57
Prepared By Ms.Nadia Shah 55
Outer join
In case of inner joins the result set contains only those rows which are
having matched values in common column ,but in case of outer join theresult set contains the unmatched value of the common column.
Types of outer joins
± Left outer join
± Right outer join
± Full outer join
Syntax :-
( SELECT * FROM authors OUTER JOIN publishers ON authors.city = publishers. city )
Where authors and publishers are the tables and city is the commoncolumn in both the tables.
8/3/2019 SQL by Nadia
http://slidepdf.com/reader/full/sql-by-nadia 56/57
Prepared By Ms.Nadia Shah 56
Outer Join
LEFT JOIN or LEFT OUTER JOIN
The result set of a left outer join includes all the rows from the left table
specified in the LEFT OUTER clause, not just the ones in which the joinedcolumns match. When a row in the left table has no matching rows in the righttable, the associated result set row contains null values for all select listcolumns coming from the right table.
R IGHT JOIN or R IGHT OUTER JOIN.
A right outer join is the reverse of a left outer join. All rows from the right table
are returned. Null values are returned for the left table any time a right tablerow has no matching row in the left table.
FULL JOIN or FULL OUTER JOIN.
full outer join returns all rows in both the left and right tables. Any time a rowhas no match in the other table, the select list columns from the other tablecontain null values. When there is a match between the tables, the entire resultset row contains data values from the base tables.
SELECT customer.firstname, customer.lastname, purchases.item
FROM customer_info Outer Join purchases
ON customer.customer_no = purchases.customer_no;