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

SQL-The Relational Database Standards

The document provides a comprehensive overview of SQL, covering its introduction, data definition, data types, constraints, and schema change statements. It explains the significance of SQL in relational databases, its standards, and various commands such as CREATE, ALTER, and DROP. Additionally, it details the types of data constraints that can be applied to ensure data integrity within SQL tables.

Uploaded by

msaturn860
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views75 pages

SQL-The Relational Database Standards

The document provides a comprehensive overview of SQL, covering its introduction, data definition, data types, constraints, and schema change statements. It explains the significance of SQL in relational databases, its standards, and various commands such as CREATE, ALTER, and DROP. Additionally, it details the types of data constraints that can be applied to ensure data integrity within SQL tables.

Uploaded by

msaturn860
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 75

SQL-The relational database

standards
 Introduction to SQL
 SQL data definition and data types
 Specfying basic constraints in SQL
 Schema change statements in SQL
 Basic queries in SQL
 More Complex SQL queries
 Additional features in SQL
 Views,Cursor,Triggers,and PL/SQL
programming
Introduction to SQL
 Considered one of the major reasons for the commercial
success of relational databases
 More user friendly than two formal languages
 Structured Query Language(SQL) originally called
Structured English Query Language(SQUEL)
 Designed and implemented at IBM
 The standaradizaton of SQL is joint effort by ANSI
(American National Standards) and ISO(International
Standard Organization)
 The first SQL standard is SQL-86 orSQL1,and later
SQL2 and SQL3 (In 1999 ) released
Introduction to SQL
 SQL is comprehensive database language
 Has data definitions queries, updates. Hence it is both
DDL &DML
 Has the facilities for defining views on the database
by specifying security and authorization, for defining
integrity constraints and for specifying transaction
controls.
 Has rules for embedding SQL statements into general
purpose programming languages such as Java or
C/C++
Introduction to SQL
 SQL is comprehensive database language
 Has data definitions queries, updates. Hence it is both
DDL &DML
 Has the facilities for defining views on the database
by specifying security and authorization, for defining
integrity constraints and for specifying transaction
controls.
 Has rules for embedding SQL statements into general
purpose programming languages such as Java or
C/C++
Introduction to SQL
SQL standards staring with SQL 1999 are divided into
1.Core specialization: Implemented by all RDBMS vendors that
are SQL complaint.
2.Specialized extensions:
Can be implemented as optional modules
To be purchased independently for specific database applications
such datamining, data warehousing etc.
Introduction to SQL
SQL standards staring with SQL 1999 are divided into
1.Core specialization: Implemented by all RDBMS vendors that
are SQL complaint.
2.Specialized extensions:
Can be implemented as optional modules
To be purchased independently for specific database applications
such datamining, data warehousing etc.
SQL data definition and data types

Terminology:
Table, row, and column used for relational model
terms relation, tuple, and attribute
CREATE statement
Main SQL command for data definition
SQL data definition and data types

Schema and Catalog Concepts in SQL contd.


Schema
Schema-Group all tables and other constructs that belongs to the
same database application
SQL schema
 Identified by a schema name
 Includes an authorization identifier-User account who owns the
schema
 also descriptors for each element
Schema elements include
Tables, constraints, views, domains, and other constructs
Each statement in SQL ends with a semicolon
SQL data definition and data types
Schema and Catalog Concepts in SQL contd..

CREATE SCHEMA statement-Used to Create Schema


Ex: CREATE SCHEMA COMPANY
AUTHORIZATION ‘Jsmith’;
Here Schema name is COMPANY and Authorization
Jsmith.
SQL data definition and data types
Schema and Catalog Concepts in SQL contd..
Catalog:A named collection of schemas.
The Create table command in SQL
Schema and Catalog Concepts in SQL contd..
-CREATE TABLE command is used to specify a new relation(table) by giving it a
name and specifying its attributes and initial constraints.

CREATE TABLE table_name (


column1 datatype,
column2 datatype,
column3 datatype,
....
);
EX
1) 2)CRETAE TABLE UNIVARISTY.STUDENT or
CREATE TABLE STUDENT

2)CRETAE TABLE COMPANY.EMPLOYEE or


CREATE TABLE EMPLOYEE
-The relations or tables crated using CREATE stament are called base tables or base
relations
-The table and rows are actually cretaed and stored as a file by the DBMS
Attribute Data Types and Domain
Constriant
Data Types
 Numeric data types
 Character string
 Bit string
 Boolean
 Date
Attribute Data Types and Domain
Constraint
 Numeric data types

• Integer numbers can be declared by using INTEGER,INT


and SMALLINT
• Floating point numbers can be declared by using
FLOAT,REAL DOUBLE PRECISION
• Foramatted numbers can be declared by using
DECIMAL(i,j) or DEC(i,j) or NUMERIC(i,j)
Where i- Precision i.e total number of decimal
digits
-Default value is defined
j-Scale i.e the number of digits after decimal point
- Default value is 0
• Ex: DECIMAL(10,4) means 123456.7890
Attribute Data Types and Domain
Constraint
 Character string
Fixed length using CHAR(n) or CHARACTER(n)
Where n is the number of characters
Ex: CHAR(10)
Varying length using VARCHAR(n) or CHAR
VARYING(n) or CHARACTER VARYING(n)
Where n is the maximum number of characters
Ex: VARCHAR(25)
Large text value such as documents can specified by
using CLOB(size)
Where size is Kilobytes(k),Megabytes(M) or
GigaBytes(G)
Ex: CLOB(20M)
Attribute Data Types and Domain
Constraint
 Boolean
 It has either true or false and unknown used when NULL
values are used in SQL
 DATE: Has 10 positions i.e YYYY-MM-DD
 TIME: Has at least 8 positions i.e HH:MM:SS
 A TIME WITH TIME ZONE: Has 6 positions
 TIMESTAMP: Includes both DATE and TIME field and
minimum of 6 position for decimal fraction of seconds and an
optional WITH TIME ZONE qualifier EX:TIMESTAMP
‘2014-09-21 09:12:47 64 8302’
 INTERVAL: Specifies relative value that can be used to
increment or decrement an absolute of date time and
timestamp
 Syntax: DATE TIME TIMESTAMP
Attribute Data Types and Domain

Constraint
Bit string
 Bit strings are strings of 1's and 0's.
 They can be used to store or visualize bit masks.
 There are two SQL bit types:
bit(n)
bit varying(n)
where n is a positive integer.

Ex:bit(5)
Literal strings are placed between single quotes but preceded by B to
distinguish from character string
EX: B ‘10001’
Attribute Data Types and Domain
Constraint
• Bit string example
CREATE TABLE test (a BIT(3), b BIT VARYING(5));

INSERT INTO test VALUES (B'101', B'00');


INSERT INTO test VALUES (B'10', B'101');

ERROR: bit string length 2 does not match type bit(3)

INSERT INTO test VALUES (B'10'::bit(3), B'101');


SELECT * FROM test;
a | b -----+-----
101 | 00
100 | 101
Example
• CREATE TABLE STUDENT(NAME
VARHAR(20),USN CHAR(8),DOB DATE)
• CREATE TABLE my_emp( empno NUMBER,
last_name VARCHAR2(30), start_time
TIMESTAMP, end_time TIMESTAMP, PERIOD
FOR user_valid_time (start_time, end_time))
Data type for each attribute can be specified
using domain name
Ex: CREATE DOMAIN USN AS CHAR(9)
Schema Change Statements
• ALTER TABLE statement
 The ALTER TABLE statement allows you to add a column to a table
 add a constraint to a table
 drop a column from a table
 drop an existing constraint from a table
 increase the width of a VARCHAR or VARCHAR FOR BIT DATA
column
 change the increment value and start value of the identity column
 change the null ability constraint for a column
 change the default value for a column
Schema Change Statements in SQL

• ALTER TABLE statement


ALTER TABLE table-Name { ADD column-definition |
ADD CONSTRAINT clause | DROP [ COLUMN ] column-
name [ CASCADE | RESTRICT ] DROP { PRIMARY KEY
| FOREIGN KEY constraint-name | UNIQUE constraint-
name | CHECK constraint-name | CONSTRAINT
constraint-name } CASCADE||RESTRICT
Schema Change Statements in SQL
• ALTER TABLE statement
Adding columns
Syntax :ALTER TABLE TABLE-NAME ADD COLUMN -
NAME DATATYPE

Ex: ALTER TABLE STUDENT ADD email varchar(10)


• Dropping columns
ALTER TABLE DROP COLUMN COLUMN-NAME allows
you to drop a column from a table.
EX: ALTER TABLE STUDENT DROP COLUMN email
Schema Change Statements in SQL
ALTER STATEMENT
• Modifying columns
• The column-alteration allows you to alter the named
column by specifying the data type and new size
after the column name.

ALTER TABLE table_name


MODIFY COLUMN datatype;

EX: ALTER TABLE STUDENT MODIFY USN int;


Schema Change Statements in SQL
DROP STATEMENT
• The DROP TABLE statement is used to drop an
existing table in a database.

Syntax: DROP TABLE table_name;


EX:DROP TABLE STUDENT
ALTER STATEMENT
ALTER TABLE statement
• Adding constraints by giving name

ALTER TABLE ADD CONSTRAINT adds a table-level constraint to an existing table.

EXAMPLES
ALTER TABLE STUDENT ADD CONSTRAINT PK_STUD PRIMARY KEY (USN);
Adding constraints without giving name

ALTER TABLE STUDENT ADD PRIMARY KEY (USN);


Or
ALTER TABLE STUDENT MODIFY USN char(8) PRIMARY KEY

• Dropping constraints
ALTER TABLE DROP CONSTRAINT drops a constraint on an existing table.
EX:ALTER TABLE STUDENT DROP PK_STUD;
Specifying constraints in SQL
 Constraints are the rules for the data in a table.
 Constraints Can be specified when the table is
created or after the table is created
 Constraints are classified as follows
1. Specifying attribute constraint and attribute
defaults
2. Specifying key and referential integrity
constraints
3. Giving name to constraint
4. Specifying constraints on tuples using CHECK
Specifying constriants in SQL
1. Specifying attribute constraint and attribute
defaults
NOT NULL Constraint
• By default, a column can hold NULL values.
• The NOT NULL constraint enforces a column to NOT
accept NULL values.
• This enforces a field to always contain a value,
which means that you cannot insert a new record,
or update a record without adding a value to this
field.
Specifying constriants in SQL
1. Specifying attribute constraint and attribute
defaults
NOT NULL Constraint
ON create table
• CREATE TABLE STUDENT(NAME VARCHAR(20) NOT NULL,USN
CHAR(8) NOT NULL,SEM INT);

• INSERT INTO STUDENT (SEM) VALUES(1)//ERROR


ON existing table
CREATE TABLE STUDENT(NAME VARCHAR(20) ,USN CHAR(8)
NOT NULL,SEM INT);
ALTER TABLE STUDENT MODIFY SEM INT NOT NULL;
Specifying constraints in SQL

1. Specifying attribute constraint and attribute defaults


Default Constraint
• The DEFAULT constraint is used to set a default value for a column.
• The default value will be added to all new records, if no other value is specified.
EX:
ON create table

CREATE TABLE STUDENT(NAME VARCHAR(20) NOT NULL,USN CHAR(8) ,SEM INT DEFAULT 1);

INSERT INTO STUDENT(NAME,USN) VALUES(‘Driti’,’2BA16CS9’)//OK

ON existing table

1)CREATE TABLE STUDENT(NAME VARCHAR(20) NOT NULL,USN CHAR(8) );

ALTER TABLE STUDENT ADD SEM INT DEFAULT 1; //if column sem not exist in table
or
2) CREATE TABLE STUDENT(NAME VARCHAR(20) NOT NULL,USN CHAR(8) ,SEM INT);

ALTER TABLE STUDENT MODIFY SEM DEFAULT 1; //if column exist in table

INSERT INTO STUDENT(NAME,USN) VALUES(‘Driti’,’2BA16CS9’)//OK


or
3) CREATE TABLE STUDENT(NAME VARCHAR(20),USN CHAR(8));

ALTER TABLE STUDENT ADD CONSTRAINT DEF_SEM SEM INT DEFAULT 1 //Giving constrint name
Specifying constraints in SQL
1. Specifying attribute constraint and attribute defaults
CHECK CONSTRAINT
• The CHECK constraint is used to limit the value
range that can be placed in a column.
• If you define a CHECK constraint on a column it will
allow only certain values for this column.
• If you define a CHECK constraint on a table it can
limit the values in certain columns based on values in
other columns in the row.
Specifying constraints in SQL
1. Specifying attribute constraint and attribute defaults
• CHECK CONSTRAINT
• ON create table
1) CREATE TABLE STUDENT(NAME VARCHAR(20),USN CHAR(9),SEM INT CHECK (SEM>=1
AND SEM<=8) );

INSERT INTO STUDENT VALUES('SAI','2BA16CS01',9); //ERROR

CHECK (grade in(‘a’,’b’,’c’,’s’));

• ON existing table

2)CREATE TABLE STUDENT(NAME VARCHAR(20),USN CHAR(9),SEM INT );

ALTER TABLE STUDENT ADD CHECK (SEM>=1 AND SEM<=8);


INSERT INTO STUDENT VALUES('SAI','2BA16CS01',9); //ERROR
or
3) CREATE TABLE STUDENT(NAME VARCHAR(20),USN CHAR(8),SEM INT);
ALTER TABLE STUDENT MODIFY SEM CHECK (SEM>=1 AND SEM<=8);
or
4) CREATE TABLE STUDENT(NAME VARCHAR(20),USN CHAR(9),SEM INT );//giving constrint
name
ALTER TABLE STUDENT ADD CONSTRAINT CHECK_SEM CHECK (SEM>=1 AND SEM<=8);
INSERT INTO STUDENT VALUES('SAI','2BA16CS01',9); //ERROR
ALTER TABLE STUDENT DROP CONSTRAINT CHECK_SEM
Specifying constraints in SQL
2)Specifying key and referential integrity constraint

 UNIQUE KEY
 PRIMARY KEY CONSTRAINT
 REFERENTIAL INTEGRITY CONSTRAINT
Specifying constraints in SQL
2)Specifying key and referential integrity constraint
contd..
 UNIQUE KEY
• The UNIQUE constraint ensures that all values in a column are
different.
• Both the UNIQUE and PRIMARY KEY constraints provide a
guarantee for uniqueness for a column or set of columns.
• A PRIMARY KEY constraint automatically has
a UNIQUE constraint.
• However, you can have many UNIQUE constraints per table,
but only one PRIMARY KEY constraint per table.
• Specifies alternate (secondary) keys
Specifying constraints in SQL
2)Specifying key and referential integrity constraint contd..
 UNIQUE KEY
On create table
CREATE TABLE STUDENT(NAME VARCHAR(20) NOT NULL,USN CHAR(8) UNIQUE ,SEM INT DEFAULT
1);
or
CREATE TABLE STUDENT(NAME VARCHAR(20) NOT NULL,USN CHAR(8) ,SEM INT DEFAULT
1,CONSTRAINT UNI_USN UNIQUE(USN)); //Giving constraint name

INSERT INTO STUDENT(“JESSICA’,’2BA16CS009’,2);


INSERT INTO STUDENT(“JESSICA’,’2BA16CS009’,2); //ERROR

On existing table
CREATE TABLE STUDENT(NAME VARCHAR(20) NOT NULL,USN CHAR(8) ,SEM INT DEFAULT 1);
ALTER TABLE STUDENT ADD UNIQUE(USN);
Or
ALTER TABLE STUDENT MODIFY USN CHAR(8) UNIQUE
or
ALTER TABLE STUDENT ADD CONSTRAINT UNI_USN UNIQUE(USN); //Giving constraint name
INSERT INTO STUDENT(“JESSICA’,’2BA16CS009’,2);
INSERT INTO STUDENT(“JESSICA’,’2BA16CS009’,2); //ERROR
Specifying constraints in SQL
2)Specifying key and referential integrity
constraint contd..
PRIMARY KEY CONSTRAINT
• The PRIMARY KEY constraint uniquely
identifies each record in a table.
• Primary keys must contain UNIQUE values,
and cannot contain NULL values.
• A table can have only ONE primary key; and in
the table, this primary key can consist of
single or multiple columns (fields).
2)
Specifying constraints in
Specifying key and referential integrity constraint contd..
SQL
Create Table
PRIMARY KEY

CREATE TABLE STUDENT(NAME VARCHAR(20),USN CHAR(8) PRIMARY KEY ,SEM


INT DEFAULT 1);

OR
CREATE TABLE STUDENT(NAME VARCHAR(20),USN CHAR(8),SEM INT
DEFAULT 1,CONSTRAINT USN_PK PRIMARY KEY(USN)); //Giving
constraint name

INSERT INTO STUDENT(NAME,USN) VALUES('A','CS01'); //OK

INSERT INTO STUDENT(NAME,USN,SEM) VALUES('B','CS02',3); //OK

INSERT INTO STUDENT(NAME,USN) VALUES('c','CS02'); //error UNIQUE


Specifying constraints in
Specifying key and referential integrity constraint contd..
2)
SQL
Existing Table
CREATE TABLE STUDENT(NAME VARCHAR(20),USN CHAR(8),SEM INT DEFAULT 1);

ALTER TABLE STUDENT MODIFY USN CHAR(8) PRIMARY KEY

INSERT INTO STUDENT(NAME,USN) VALUES('A','CS01'); //OK

INSERT INTO STUDENT(NAME,USN,SEM) VALUES('B','CS02',3); //OK

INSERT INTO STUDENT(NAME,USN) VALUES('c','CS02'); //error UNIQUE

Or
CREATE TABLE STUDENT(NAME VARCHAR(20),sem int);
ALTER TABLE STUDENT add USN char(8) PRIMARY KEY
//col usn added with pkconstrint
Specifying constraints in SQL
2)Specifying key and referential integrity constraint contd..
Giving Constraint Name

On Existing Table
CREATE TABLE STUDENT(NAME VARCHAR(20),USN CHAR(8),SEM INT
DEFAULT 1);

ALTER TABLE STUDENT ADD CONSTRAINT USN_PK PRIMARY KEY (USN);

INSERT INTO STUDENT(NAME,USN) VALUES('A','CS01'); //OK

INSERT INTO STUDENT(NAME,USN,SEM) VALUES('B','CS02',3); //OK

INSERT INTO STUDENT(NAME,USN) VALUES('c','CS02'); //error UNIQUE

ALTER TABLE STUDENT DROP CONSTRAINT USN_PK


DROP TABLE STUDENT
• CREATE TABEL COUSRE
Column Datatype Description

COURSE_CO CHARACTER This field should be not null,


DE and should be Primary key

COURSE_NA CHARACTER This field should be not null


ME

CREDITS INT BY DEFAULT 0


• TABEL COUSRE
CREATE TABLE COURSE(COURSE_CODE
VARCHAR(10),C_NAME VARCHAR(10),CREDITS INT
DEFAULT 0);

ALTER TABLE COURSE ADD CONSTRAINT C_CODE_PK


PRIMARY KEY (COURSE_CODE);

INSERT INTO COURSE(COURSE_CODE,C_NAME,CREDITS)


VALUES('UCS401C','DBMS',3);
INSERT INTO COURSE(COURSE_CODE,C_NAME,CREDITS)
VALUES('UCS402C','DSC',3);
• CREATE TABEL ENROLL
Column Datatype Description

COURSE_CODE CHARACTER This field should refer course code

USN CHARACTER This field should refer usn of student

GRADE INT Grade should be iA,B,C,D,E,F and s



Specifying
Referential integrity constraint
constraints in SQL
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign
key column, because it has to be one of the values contained in the parent table.
On Create table
CREATE TABLE ENROLL(USNE CHAR(8) ,C_CODE VARCHAR(10) ,GRADE
CHAR(1) CHECK (GRADE IN ('A', 'B', 'C','D','E')) ,
FOREIGN KEY (USNE) REFERENCES STUDENT(USN) ON DELETE
CASCADE,FOREIGN KEY (C_CODE) REFERENCES
COURSE(COURSE_CODE) ON DELETE CASCADE,PRIMARY
KEY(USNE,C_CODE), UNIQUE(USNE,C_CODE));

ALTER TABLE ENROLL ADD CONSTRAINT C_GRADE CHECK(GRADE


IN('A','B',C','D','E','F','S'))

INSERT INTO ENROLL VALUES('CS01','UCS401C','A');


INSERT INTO ENROLL VALUES('CS01','UCS402C','B');
INSERT INTO ENROLL VALUES('CS02','UCS401C','E');

Specifying constraints
Referential integrity constraint contd…
in SQL
On Create table
CREATE TABLE ENROLL(USNE CHAR(8) ,C_CODE VARCHAR(10) ,GRADE
CHAR(1) CHECK (GRADE IN ('A', 'B', 'C','D','E'),UNIQUE(USNE,C_CODE) ,
CONSTRAINT FK_USNE FOREIGN KEY REFERENCES STUDENT(USN)
ON DELETE CASCADE,

CONSTRAINT FK_CCODE FOREIGN KEY REFERENCES


COURSE(COURSE_CODE) ON DELETE CASCADE,PRIMARY
KEY(USNE,C_CODE));

ALTER TABLE ENROLL ADD CONSTRAINT C_GRADE CHECK(GRADE


IN('A','B',C','D','E','F','S'))

INSERT INTO ENROLL VALUES('CS01','UCS401C','A');


INSERT INTO ENROLL VALUES('CS01','UCS402C','B');
INSERT INTO ENROLL VALUES('CS02','UCS401C','E');

Specifying
Referential integrity constraint
constraints in SQL
On Existing table
CREATE TABLE ENROLL(USNE CHAR(8) ,C_CODE VARCHAR(10) ,GRADE
CHAR(1) CHECK (GRADE IN ('A', 'B', 'C','D','E')), UNIQUE(USNE,C_CODE));

ALTERE TABLE ADD CONSTRAINT FK_USNE FOREIGN KEY


REFERENCES STUDENT(USN) ON DELETE CASCADE,

ALTER TABLE ADD CONSTRAINT FK_CCODE FOREIGN KEY


REFERENCES COURSE(COURSE_CODE) ON DELETE
CASCADE,PRIMARY KEY(USNE,C_CODE)

INSERT INTO ENROLL VALUES('CS01','UCS401C','A');


INSERT INTO ENROLL VALUES('CS01','UCS402C','B');
INSERT INTO ENROLL VALUES('CS02','UCS401C','E');
OUT PUT
Basic Retrieval Queries In SQL
• SELECT statement is used to retrieve information from
database
• It is not same as the select operation of relational algebra.
• There are many options and flavours which are as follows
 Select from where structure
 Ambiguous attribute names, aliasing, renaming and tuple
variables
 Unspecified where clause and use of the asterisk.
 Tables as set in SQL
 Substring pattern matching and arithmetic operators.
Basic Retrieval Queries In SQL contd..
Select from where structure

Select from where block formed with three clause SELECT,FROM,WHERE

General syntax is as follows:


SELECT <attribute list>
FROM< table list>
WHERE< condition>

Where
<attribute list>-list attribute names whose values are to be
retrieved.
< table list>-List of table names or relation names to process
query

< condition>-Boolean expression


Basic Retrieval Queries In SQL contd..
Examples:
1)Retrieve the birth date and address of the employees
whose name is John B Smith

SELECT DOB,ADDRESS
FROM EMPLOYEE
WHERE FNAME=‘JHON’ AND MNAME=‘B’ AND
LNAME=SMITH’
Basic Retrieval Queries In SQL contd..
Examples:
2)Retrieve the name of employees who either work for
department 4 and make over salary 30000 or work for
department 5 and make over salary 28000
SELECT FNAME,MNAME,LNAME
FROM EMPLOYEE
WHERE (DN=4 AND SALARY>30000) OR(DN=5 AND
SALARY>28000)
Basic Retrieval Queries In SQL contd..
TRY TO SOLVE
1)Retrieve the ssn of employee who works on project
more than 20 hours
2)Retrieve the dependent name of employee whose
ssn is 333445555
3)Retrieve the project number and project location of
controlling department 5
4) Retrieve the department location department 5
Basic Retrieval Queries In SQL contd..
 Ambiguous attribute names, aliasing, renaming and tuple variables
 In SQL same name can be used for two or more attributes in different
tables
 Then qualify the attribute name with the relation name to prevent
ambiguity.

1)Retrieve the fname ,lname and address of all employees who work for the
Research department

SELECT FNAME,LNAME,ADDTESS
FROM EMPLOYEE,DEPARTMENT
WHERE DEPARTMENT.DNAME=‘RESEARCH’ AND
DEPARTMENT.DNO=EMPLOYEE.DNO
A query that involves selection, projection attributes and join conditions is
called select-project-join query
Basic Retrieval Queries In SQL contd..
 Ambiguous attribute names, aliasing, renaming and
tuple variables
Ambiguity of attribute names also arises if queries that
refer to same relation twice
Then aliasing can be used.
In following example E and S can be used as aliases
1)For each employee retrieve the employees first and last
name and first and last name of his or her immediate
supervisor
SELECT E.FNAME,E.LNAME, S.FNAME,S.LNAME
FROM EMPLOYEE E,EMPLOYEE S
WHERE E.SSSN=S.SSN
Basic Retrieval Queries In SQL contd..

 Ambiguous attribute names, aliasing, renaming and tuple


variables
1)Retrieve fname,lname and address of employee who is
working for department Research
SELECT E.FNAME as FN,E.LNAME
FROM EMPLOYEE E,DEPARTMENT D
WHERE D.DNO=E.DNO AND D.DNAME=‘Research’

Here E and D are alias names for EMPLOYEE and DEPARTMENT


FN is renamed name for attribute E.FNAME
Basic Retrieval Queries In SQL contd..

Try to solve.
 Retrieve the fname and lname of the employee who
is manager for the department located at Houstan.
 Retrieve the fname and lname of the employee
whose dependent name is Alice .
 Retrieve the name of the department which is
controlling the projects Product X and
computerization .
 Retrieve the name of employees who are working on
project number 3
Basic Retrieval Queries In SQL contd..
 Unspecified where clause and use of the asterisk.
Unspecified where clause
-A missing WHERE clause indicates no condition on
tuple selection
-Hence all tuples of the relation specified in the FROM
clause qualify and are selected from the query result
-If more than one relation is specified FROM clause and
there is no WHERE clause then the cross product –all
possible tuple combinations of these relation is
selected
Basic Retrieval Queries In SQL contd..
 Unspecified where clause and use of the asterisk contd..
Unspecified where clause examples
1)Retrieve all employee ssn
SELECT SSN
FROM EMPLOYEE
2)Retrieve name of employee and department name ofall
combination of employee and department database

SELECT SSN,DNAME
FROM EMPLOYEE,DEPARTMENT
Basic Retrieval Queries In SQL contd..
 Unspecified where clause and use of the asterisk contd…
use of the asterisk.
Asterisk is used to retrieve all the attribute values
1)Retrieve details of employee who works for department 5

SELECT *
FROM EMPLOYEE
WHERE DNO=5
2) Retrieve all details of employee who works for department Research

SELECT *
FROM EMPLOYEE,DEPARTMENT
WHERE DNAME=‘Research’ AND EMPLOYEE.DNO=DEPARTMENT.DNO
3) Retrieve all combination of details of employee with department

SELECT *
FROM EMPLOYEE,DEPARTMENT
Basic Retrieval Queries In SQL contd..
 Tables as set in SQL
-Usually treats a table as a set not a set but as multiset
-Therefore duplicate tuples appear more than once in a
table and in the result of a query
-SQL dose not automatically eliminate duplicate tuples in
the result of queries for the following reasons
• Duplication elimination is expensive operation. One
way to implement is sort the tuples first and the
eliminate duplicates
• User may want to see duplicate tuples in the result
query
• when an aggregate function is applied to tuples
Basic Retrieval Queries In SQL contd..
 Tables as set in SQL contd..
1)DISTINCT keyword can be used to eliminate duplicate
tuples from relation
Retrieve the all distinct salary of employee
SELECT DISTINCT SALARY
FROM EMPLOYEE.
2)ALL keyword doesn’t eliminate duplicate tuples from
relation
Retrieve the all salary of employee
SELECT ALL SALARY
FROM EMPLOYEE.
Basic Retrieval Queries In SQL contd..
 Tables as set in SQL contd..
Try to solve
1)Retreive distinct salaries of employees who is working for
department 5;
SELECT DISTINCT SALARY
FROM EMPLOYEE
WHERE DNO=5

2)Retreive all salaries of employees who is working for


department 5;
SELECT ALL SALARY
FROM EMPLOYEE
WHERE DNO=5
Basic Retrieval Queries In SQL contd..
 Tables as set in SQL contd..
3)UNION,EXCEPT and INTERSECT-Are set operations
-also eliminate duplicate tuples from relation
-These set operations apply only to type compatible
relations that is attributes names in relation must be
same and also order of appetence in relation
-SQL also has multiset operation which is followed by
the keyword ALL(UNION ALL,EXCEPT ALL and
INTERSECT ALL)
Basic Retrieval Queries In SQL contd..
 Tables as set in SQL contd..
1)Retrieve the SSN of the employee who has no dependent
SELECT SSN
FROM EMPLOYEE
EXCEPT
SELECT ESSN as SSN
FROM DEPENDENT
2) Retrieve the SSN of the employee who has dependent
SELECT DISTINCT SSN
FROM EMPLOYEE
INTERSECT
SELECT DISTINCT ESSN as SSN
FROM DEPENDENT
Basic Retrieval Queries In SQL contd..
 Tables as set in SQL contd..
1)Retrieve the SSN of the employee who has no dependent
SELECT SSN
FROM EMPLOYEE
EXCEPT
SELECT ESSN as SSN
FROM DEPENDENT
2) Retrieve the SSN of the employee who has dependent
SELECT DISTINCT SSN
FROM EMPLOYEE
INTERSECT
SELECT DISTINCT ESSN as SSN
FROM DEPENDENT
Basic Retrieval Queries In SQL contd..
 Tables as set in SQL contd..
3)Make list of all the ptoject numbers for project that involves
an employee whose name is Smith either as a worker or as a
manager of the department that controls the project
SELECT DISTINCT PNO
FROM EMPLOYEE E,DEPARTMENT D,PROJECT P
WHERE LNAME=‘SMITH’ AND E.DNO=D.DNO AND
D.MGR_SSN=E.SSN
UNIOIN
SELECT DISTINCT PNO
FROM EMPLOYEE E,PROJECT P,WORKS_ON W
WHERE LNAME=‘SMITH’ AND E.SSN=W.ESSN AND
W.PNO=P.PNO
Basic Retrieval Queries In SQL contd..
 Substring pattern matching and arithmetic
operators.
1)LIKE comparison operator is used to compare
conditions on only part of character string.
-This can be used for pattern matching.
-Partial strings are specified using two reserved
characters those are as follows
% replaces an arbitrary number of zero or
more characters
_ replaces a single character.
Basic Retrieval Queries In SQL contd..
 Substring pattern matching and arithmetic
operators contd…
Examples:
1)Retrieve all employees whose address is in Houstan
Texas
SELECT FNAME,MNAME
FROM EMPLOYEE
WHERE ADDRESS LIKE ‘%Houstan Texas%’
2)Retrieve all employees who born during the 1970
SELECT FNAME,MNAME
FROM EMPLOYEE
WHERE ADDRESS LIKE ‘_ _ 7_ _ _ _ _’
Basic Retrieval Queries In SQL contd..
 Substring pattern matching and arithmetic
operators contd…
Try to solve
1)Retrieve all employees whose name starts
with A
select *from employee where fname like'A%'
2) Retrieve all employees whose name ends
with e
select *from employee where fname like'%e’
Basic Retrieval Queries In SQL contd..
 Substring pattern matching and arithmetic
operators contd…
Allows arithmetic operators can be applied on
attributes with numeric domain
Examples:
1)Retrieve name salaries of employees who are
working on product x project is given 15% raise
SELECT F E.NAME,E.MNAME,0.15*E.SALARY AS INC_SAL
FROM EMPLOYEE E,WORKS_ON W,PROJECT P
WHERE E.SSN=W.ESSN AND W.PNO=P.NO AND
P.PNAME=‘product x’
Basic Retrieval Queries In SQL contd..
 Substring pattern matching and arithmetic
operators contd…
2)Between
Another comparison operator which can be used
to select values in the range
1)Retrieve all employees in department 5 whose
salary is between 30000 and 40000
SELECT *
FROM EMPLOYEE
WHERE (SALARY BETWEEN 30000 AND 40000) AND
DNO=5
Basic Retrieval Queries In SQL contd..
 Substring pattern matching and arithmetic
operators contd…
Try to solve
1)Retrieve name of employees whose name ends
with ie
2)Retrieve name of employees who is working in
department research and salaries between 30000
to 50000
3) Retrieve name and salary of employees who is
working on projects more than 20 hours is given by
10%raise
Basic Retrieval Queries In SQL contd..
 Ordering of query results
Order by-
Allows the user to order the tuples in the result of a query by the values of one or more of the
attributes appear in query result in ascending or in descending order
1)Retrieve name and salary of employees ordered alphabetically by name.
SELECT FNAME,SALARY
FROM EMPLOYEE
ORDER BY FNAME
By default the order is ascending
DESC -can be used to specify ascending
ASC- can be used to specify descending
2) Retrieve name, department name of employees working for department order by
department number ,first name
SELECT E.DNO,E.FNAME
FROM EMPLOYEE E,DEPARTMENT D
WHERE E.DNO=D.DNUMBER
ORDER BY E.DNO ,E.FNAME
In above query result is sorted in ascending order based on dno.
If multiple rows of having same row then result can be sorted based on name
Basic Retrieval Queries In SQL contd..
 Ordering of query results
Order by-
Try to solve
1)Retrieve name of employees working for department order
by department name and name of employee

SELECT E.DNO,D.DNAME
FROM EMPLOYEE E,DEPARTMENT D
WHERE E.DNO=D.DNUM
ORDER BY D.DNAME,E.FNAME DESC
2) Retrieve name, department name and department location
of employees working for department order by department
number ,first name,dlocation
Basic Retrieval Queries In SQL contd..

SUMMARY OF BASIC SQL QUERIES


SELECT <attribute-list>
FROM <Table-list>
[WHERE <condition>]
[ORDER BY <attribute-list<]
Insert,Delete and update statements in SQL
Insert:
-Used to add single row to a relation
-The values should be listed in the same order corresponding to attributes specified in
CREATE label command.
-Examples
INSERT INTO EMPLOYEE
VALUES('AHMAD','V','JABBAR','987987987','03-29-1969','980 HOUSTAN
TX','M',25000,'987654321',4)
or
INSERT INTO
EMPLOYEE(FNAME,MNAME,LNAME,SSN,BDATE,ADDRESS,GENDER,SALARY,SSSN,DNO)
VALUES('AHMAD','V','JABBAR','987987987','03-29-1969','980 HOUSTAN
TX','M',25000,'987654321',4)
Or

INSERT INTO
EMPLOYEE(FNAME,MNAME,LNAME,SSN,BDATE,ADDRESS,GENDER,SALARY,SSSN,DNO)
VALUES(:FNAME,:MNAME,:LNAME,SSN,:BDATE,:ADDRESS,G:ENDER,:SALARY,:SSSN,:DNO)

Last insert example Used in Oracle 11g to read input from keyboard
Insert,Delete and update statements in SQL
Delete
-Used to delete tuples from relation
-Has where clause to select the tuples to be deleted
-Deletion may be propagated if referential triggered actions are
specified in the referential integrity constraint of the DDL.
1)Delete the employee tuple whose last name is Brown
DELETE FROM EMPLOYEE
WHERE LNAME=‘Brown’
2) Delete the employee tuple who is working for the department dno
5
DELETE FROM EMPLOYEE
WHERE DNO=5
3) Delete the employee tuple who is working for the department
located at Stafford
DELETE FROM EMPLOYEE E,DEPT_LOCATION D
Insert,Delete and update statements in SQL
Update
-Used to modify attribute values of one or more selected tuples
-Has where clause to select the tuples to be updated
-Updating primary key value msay propagate to the foreign key values of tuples of
other relations if referential triggered actions are specified.
1)Update the employee salary by incrementing 5% of salary who is working for
dno 5
UPDATE EMPLOYEE
SET SALARY=SALARY+SALARY*0.5
WHERE DNO=5
2) Update the employee fname to Jack whose ssn is 333445555
UPDATE EMPLOYEE
SET FNAME=‘Jack’
WHERE SSN= 333445555
-It is also possible to specify NULL or default as the new attribute value

You might also like