Sie sind auf Seite 1von 63

SQL PRIMARY KEY

• The PRIMARY KEY constraint uniquely


identifies each record in a table.
• Primary keys must contain UNIQUE values,
and cannot contain NULL values.
Persons Table
Id First Name Last Name Age Address
1 Vince Paul 20 Delhi
2 John Selwin 21 Hyderabad
3 Bibu Basara 23 Mumbai
4 Samson Dev 24 Jaipur
5 Praveen Fhani 25 Chennai
SQL PRIMARY KEY on CREATE TABLE

• CREATE TABLE Persons (


ID int NOT NULL PRIMARY KEY,
LastName varchar(20),
FirstName varchar(20),
Age int, Address varchar(20)
);
• Insert into persons values
(1,’vince’,’paul’,20,’Delhi);
• And insert remaining values
• Select * from persons;
SQL FOREIGN KEY

• A FOREIGN KEY is a key used to link two tables


together.
• A FOREIGN KEY is a field (or collection of
fields) in one table that refers to the PRIMARY
KEY in another table.
"Persons" table:

PersonID LastName FirstName Age


1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20

“Orders" table

OrderID OrderNumber PersonID


1 77895 3
2 44678 3
3 22456 2
4 24562 1
• Notice that the "PersonID" column in the
"Orders" table points to the "PersonID"
column in the "Persons" table.
• The "PersonID" column in the "Persons" table
is the PRIMARY KEY in the "Persons" table.
• The "PersonID" column in the "Orders" table is
a FOREIGN KEY in the "Orders" table.
• create table orders(id number primary
key,O_n number not null,person_Id number
references persons(person_Id));
SQL FOREIGN KEY on ALTER TABLE

• To create a FOREIGN KEY constraint on the


"PersonID" column when the "Orders" table is
already created, use the following SQL:
• ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES
Persons(PersonID);
DROP a FOREIGN KEY Constraint

• ALTER TABLE Orders


DROP CONSTRAINT FK_PersonOrder;
Practice SQL
Table – Worker
WORKER_ID FIRST_NAME LAST_NAME SALARY JOINING_DA DEPARTMENT
TE
001 Monika Arora 100000 2014-02-20 HR
09:00:00
002 Niharika Verma 80000 2014-06-11 Admin
09:00:00
003 Vishal Singhal 300000 2014-02-20 HR
09:00:00
004 Amitabh Singh 500000 2014-02-20 Admin
09:00:00
005 Vivek Bhati 500000 2014-06-11 Admin
09:00:00
006 Vipul Diwan 200000 2014-06-11 Account
09:00:00
007 Satish Kumar 75000 2014-01-20 Account
09:00:00
008 Geetika Chauhan 90000 2014-04-11 Admin
09:00:00
• CREATE TABLE Worker ( WORKER_ID INT NOT
NULL PRIMARY KEY, FIRST_NAME
VARCHAR2(25), LAST_NAME VARCHAR2(25),
SALARY INT(15), JOINING_DATE DATETIME,
DEPARTMENT VARCHAR(25) );
• INSERT INTO Worker (WORKER_ID, FIRST_NAME,
LAST_NAME, SALARY, JOINING_DATE, DEPARTMENT) VALUES
(001, 'Monika', 'Arora', 100000, '14-02-20 09.00.00', 'HR'),
(002, 'Niharika', 'Verma', 80000, '14-06-11 09.00.00', 'Admin'),
(003, 'Vishal', 'Singhal', 300000, '14-02-20 09.00.00', 'HR'),
(004, 'Amitabh', 'Singh', 500000, '14-02-20 09.00.00', 'Admin'),
(005, 'Vivek', 'Bhati', 500000, '14-06-11 09.00.00', 'Admin'),
(006, 'Vipul', 'Diwan', 200000, '14-06-11 09.00.00', 'Account'),
(007, 'Satish', 'Kumar', 75000, '14-01-20 09.00.00', 'Account'),
(008, 'Geetika', 'Chauhan', 90000, '14-04-11 09.00.00',
'Admin');
Datatype Use
used for columns which will
INT
store integer values.
used for columns which will
FLOAT
store float values.
used for columns which will
DOUBLE
store float values.
used for columns which will be
VARCHAR used to store characters and
integers, basically a string.
used for columns which will
CHAR store char values(single
character).
used for columns which will
DATE
store date values.
used for columns which will
store text which is generally
long in length. For example, if
you create a table for storing
TEXT
profile information of a social
networking website, then for
DBMS Relational Algebra
• What is Relational Algebra in DBMS?
• Relational algebra is a procedural query
language that works on relational model.
• The purpose of a query language is to retrieve
data from database or perform various
operations such as insert, update, delete on
the data.
• When I say that relational algebra is a
procedural query language, it means that it
tells what data to be retrieved and how to be
retrieved.
Types of operations in relational
algebra
• We have divided these operations in two
categories:
1. Basic Operations
2. Derived Operations
I. Basic/Fundamental Operations:
1. Select (σ)
2. Project (∏)
3. Union (∪)
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)
II. Derived Operations:
1. Natural Join (⋈)
2. Left, Right, Full outer join (⟕, ⟖, ⟗)
3. Intersection (∩)
4. Division (÷)
Lets discuss these operations one by one with
the help of examples.
Select Operator (σ)
• Select Operator is denoted by sigma (σ) and it
is used to find the tuples (or rows) in a
relation (or table) which satisfy the given
condition.
• If you understand little bit of SQL then you can
think of it as a where clause in SQL, which is
used for the same purpose.
Syntax of Select Operator (σ)
• σ Condition(Relation/Table name)
Select Operator (σ) Example
Table: CUSTOMER
Customer_Id Customer_Name Customer_City
C10100 Steve Agra
C10111 Raghu Agra
C10115 Chaitanya Noida
C10117 Ajeet Delhi
C10118 Carl Delhi

Query:
σ Customer_City="Agra" (CUSTOMER)
Output:
Customer_Id Customer_Name Customer_City
C10100 Steve Agra
C10111 Raghu Agra
Project Operator (∏)
• Project operator is denoted by ∏ symbol and
it is used to select desired columns (or
attributes) from a table (or relation).
• Project operator in relational algebra is similar
to the Select statement in SQL. But it will work
on columns
Syntax of Project Operator (∏)
• ∏ column_name1, column_name2, ....,
column_nameN(table_name)
Project Operator (∏) Example
• Table: CUSTOMER
Customer_Id Customer_Name Customer_City
C10100 Steve Agra
C10111 Raghu Agra
C10115 Chaitanya Noida
C10117 Ajeet Delhi
C10118 Carl Delhi

• In this example, we have a table CUSTOMER


with three columns, we want to fetch only two
columns of the table, which we can do with
the help of Project Operator ∏.
Query:
• ∏ Customer_Name, Customer_City (CUSTOMER)
• Output:
Customer_Name Customer_City
Steve Agra
Raghu Agra
Chaitanya Noida
Ajeet Delhi
Carl Delhi
Union Operator (∪)

• Union operator is denoted by ∪ symbol and it


is used to select all the rows (tuples) from two
tables (relations).
• Lets discuss union operator a bit more.
• Lets say we have two relations R1 and R2 both
have same columns and we want to select all
the tuples(rows) from these relations then we
can apply the union operator on these
relations.
• Note: The rows (tuples) that are present in
both the tables will only appear once in the
union set.
• In short you can say that there are no
duplicates present after the union operation.
Syntax of Union Operator (∪)
• table_name1 ∪ table_name2
Union Operator (∪) Example
Table 1: COURSE
Course_Id Student_Name Student_Id
C101 Aditya S901
C104 Aditya S901
C106 Steve S911
C109 Paul S921
C115 Lucky S931
• Table 2: STUDENT
Student_Id Student_Name Student_Age
S901 Aditya 19
S911 Steve 18
S921 Paul 19
S931 Lucky 17
S941 Carl 16
S951 Ricky 18
Query:
• ∏ Student_Name (COURSE) ∪ ∏ Student_Name (STUDENT)
• Output: Student_Name
Aditya

Carl

Paul

Lucy

Rick

Steve

• Note: As you can see there are no duplicate names present in


the output even though we had few common names in both
the tables, also in the COURSE table we had the duplicate
name itself.
Intersection Operator (∩)

• Intersection operator is denoted by ∩ symbol


and it is used to select common rows (tuples)
from two tables (relations).
• Lets say we have two relations R1 and R2 both
have same columns and we want to select all
those tuples(rows) that are present in both
the relations, then in that case we can apply
intersection operation on these two relations
R1 ∩ R2.
• Note: Only those rows that are present in
both the tables will appear in the result set.
Syntax of Intersection Operator
(∩)
• table_name1 ∩ table_name2
Intersection Operator (∩) Example

• Lets take the same example that we have


taken above.
Table 1: COURSE
Intersection Operator (∩) Example

• Lets take the same example that we have


taken above.
Table 1: COURSE
Course_Id Student_Name Student_Id
C101 Aditya S901
C104 Aditya S901
C106 Steve S911
C109 Paul S921
C115 Lucky S931
• Table 2: STUDENT
Student_Id Student_Name Student_Age
S901 Aditya 19
S911 Steve 18
S921 Paul 19
S931 Lucky 17
S941 Carl 16
S951 Ricky 18
Query:
• ∏ Student_Name (COURSE) ∩ ∏ Student_Name (STUDENT)
• Output:
Student_Name

Aditya

Steve

Paul

Lucy
Set Difference (-)

• Set Difference is denoted by – symbol.


• Lets say we have two relations R1 and R2 and
we want to select all those tuples(rows) that
are present in Relation R1 but not present in
Relation R2, this can be done using Set
difference R1 – R2.
Syntax of Set Difference (-)
• table_name1 - table_name2
Set Difference (-) Example

• Lets take the same tables COURSE and


STUDENT that we have seen above.
Set Difference (-) Example

• Lets take the same example that we have


taken above.
Table 1: COURSE
Course_Id Student_Name Student_Id
C101 Aditya S901
C104 Aditya S901
C106 Steve S911
C109 Paul S921
C115 Lucky S931
• Table 2: STUDENT
Student_Id Student_Name Student_Age
S901 Aditya 19
S911 Steve 18
S921 Paul 19
S931 Lucky 17
S941 Carl 16
S951 Ricky 18
Query:
• Lets write a query to select those student names that are
present in STUDENT table but not present in COURSE table.
• ∏ Student_Name (STUDENT) - ∏ Student_Name (COURSE)
• Output:
Student_Name

Carl

Rick
Cartesian product (X)
• Cartesian Product is denoted by X symbol.
• Lets say we have two relations R1 and R2 then
the cartesian product of these two relations
(R1 X R2) would combine each tuple of first
relation R1 with the each tuple of second
relation R2.
Syntax of Cartesian product (X)
• R1 X R2
Cartesian product (X) Example

• Table 1: R
Col_A Col_B
AA 100
BB 200
CC 300

• Table 2: S
Col_X Col_Y
XX 99
YY 11
ZZ 101
• Query:
• Lets find the cartesian product of table R and
S.
• RXS
• RXS Col_A Col_B Col_X Col_Y
AA 100 XX 99
AA 100 YY 11
AA 100 ZZ 101
BB 200 XX 99
BB 200 YY 11
BB 200 ZZ 101
CC 300 XX 99
CC 300 YY 11
CC 300 ZZ 101

• Note: The number of rows in the output will always


be the cross product of number of rows in each
table. In our example table 1 has 3 rows and table 2
has 3 rows so the output has 3×3 = 9 rows.
Rename (ρ)

• Rename (ρ) operation can be used to rename


a relation or an attribute of a relation.
• Rename (ρ) Syntax:
• ρ(new_relation_name, old_relation_name)
• Rename (ρ) Example
• Lets say we have a table customer, we are
fetching customer names and we are
renaming the resulted relation to
CUST_NAMES.
• Table: Customer
Customer_Id Customer_Name Customer_City
C10100 Aditya Agra
C10111 Steve Agra
C10115 Paul 19
C10117 Lucky Noida
C10119 Carl Delhi
C10120 Ricky Delhi
• Query:
• ρ(CUST_NAMES,
∏(Customer_Name)(CUSTOMER))
• Table: Customer
Customer_Name
Aditya
Steve
Paul
Lucky
Carl
Ricky
Examples
BRANCH_NAME LOAN_NO AMOUNT
Downtown L-17 1000
Redwood L-23 2000
Perryride L-15 1500
Downtown L-14 1500
Mianus L-13 500
Roundhill L-11 900
Perryride L-16 1300
• σ BRANCH_NAME="perryride" (LOAN)
Examples
NAME STREET CITY
Jones Main Harrison
Smith North Rye
Hays Main Harrison
Curry North Rye
Johnson Alma Brooklyn
Brooks Senator Brooklyn
NAME STREET CITY
• ∏ NAME, CITY (CUSTOMER)
"EmployeeDetails" table:
EmpId FullName ManagerId Address
121 John Snow 321 LPU
321 Walter White 986 Jalandhar
421 Kuldeep Rana 876 Delhi

“Employee Salary" table

EmpId Project Salary


121 P1 8000
321 P2 1000
421 P1 12000

Write a SQL query to fetch the count of employees working in project 'P1'.
• Ques.1. Write a SQL query to fetch the count
of employees working in project 'P1'.
• Ques.2. Write a SQL query to fetch employee
names having salary greater than or equal to
5000 and less than or equal 10000.
• Ques.3. Write a SQL query to fetch project-
wise count of employees sorted by project's
count in descending order.
• SELECT COUNT(*) FROM EmployeeSalary
WHERE Project = 'P1';

• SELECT FullName FROM EmployeeDetails


WHERE EmpId IN (SELECT EmpId FROM
EmpolyeeSalary WHERE Salary BETWEEN
5000 AND 10000);
• SELECT Project, count(EmpId)
EmpProjectCount FROM EmployeeSalary
GROUP BY Project ORDER BY
EmpProjectCount DESC;

Das könnte Ihnen auch gefallen