Вы находитесь на странице: 1из 64

SQL

Reshma Dayma
Types of SQL Statements
• DDL ( Data Definition Language): these commands to create, modify and
delete tables. CREATE, ALTER, DROP etc.

• DML (Data Manipulation Language): these commands are used to


manipulate data inside the table. INSERT, SELECT, DELETE, UPDATE etc.

• DCL (Data Control Language): used to control the access to the data.
GRANT, REVOKE etc.

• TCL (Transaction Control Language): used to manage transaction in


database. COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION
Create Table
• Create table student
(
id varchar2(11) primary key,
name varchar2(20),
address varchar2(20),
phone varchar2(10),
age number(2)
);
Insert
• Insert into student(id,name,address,phone,age) values
(’13CE150’,’xyz’,’amd’,112233’,19);

• Insert into student values (’13CE150’,’xyz’,’amd’,112233’,19);

• Insert into student(id,name,phone) values (’13CE150’,xyz’,’112233’);


update
• Update student set address=‘baroda’;

• Update student set address=‘baroda’ where id=’13ce150’;

• Update student set address=‘baroda’, age=19 where id=‘13ce150’;


Delete
• Delete from student;
will remove all the rows in table.
• Delete from student where id=‘13ce150’;
will remove specific row having id value 13ce150.
Primary key
• Primary key is one or more column that uniquely identifies each row.
• Primary key attributes can not contain null value.
• Table can have only one primary key.
Primary key defined at column level
• Create table student
(
id varchar2(11) primary key,
name varchar2(20),
address varchar2(20),
phone varchar2(10),
age number(2)
);
Primary key defined at table level
• Create table result
(
id varchar2(10),
semester number(2),
percentage number(5,2),
primary key(id,semester)
);
Foreign key
• Foreign key represents relationship between table.
• The table in which foreign key is defined is foreign table or detail
table.
• The table that defines primary key is primary or master table.
Foreign key
• Create table result
(
id varchar2(11) ,
semester number(2),
percentage number(5,2),
primary key(id,semester),
Foreign key(id) references student(id)

);
Foreign key
• Create table result
(
id varchar2(10) ,
semester number(2),
percentage number(5,2),
primary key(id,semester),
Foreign key(id) references student(id) on delete cascade

);
Foreign key
• Create table result
(
id varchar2(10) ,
semester number(2),
percentage number(5,2),
primary key(id,semester),
Foreign key(id) references student(id) set null on delete

);
Unique constraint
• If attribute has constraint to be unique, it will not allow duplicate
value.
• In primary key, attribute value must be unique and not null while in
unique constraint attribute can have null value but not a duplicate
value.
Unique
• Create table student
(
id varchar2(11) primary key,
name varchar2(20),
address varchar2(20),
phone varchar2(10) unique,
age number(2)
);
Unique
• Create table student
(
id varchar2(11) primary key,
name varchar2(20),
address varchar2(20),
phone varchar2(10),
age number(2),
unique(phone)
);
Not null
• If an attribute value is compulsory for record, if it cant be left blank, then
put the constraint not null.

Create table student


(
id varchar2(11) primary key,
name varchar2(20),
address varchar2(20) not null,
phone varchar2(10),
age number(2),
unique(phone)
);
Check
• In check constraint, logical expression is specified. If that expression is
true for given value of record then only it will be inserted into table.
• Otherwise it will give error and will not allow to insert.
Check
Create table student
(
id varchar2(11) check(id LIKE ‘_ _ce%’),
name varchar2(20),
address varchar2(20) not null,
phone varchar2(10),
age number(2),
primary key(id),
unique(phone)
);
Check
create table student
(
id varchar2(11) check(id LIKE '__ce%'),
name varchar2(20),
address varchar2(50) not null,
phone varchar2(15),
primary key(id),
unique(phone),
check(address IN ('amd','baroda','surat'))
);
AND, OR, IN operator
• AND and OR operator is used to combine the conditions in single sql
statement.
• The IN operator allows you to specify multiple values in a WHERE
clause.
• Select * from student where address=‘amd’ AND age<20;
• Select * from student where address=‘amd’ OR age<20;
• Select * from student where address IN(‘amd’,’baroda’,’surat’);
Aggregate functions
• Result Table
ID SEMESTER PERCENTAGE
13CE001 1 10
13CE001 2 90
13CE002 1 90
13CE002 2 80

• AVG([<DISTINCT>|<ALL>] <N>)
select avg(DISTINCT percentage) "average" from result;
select avg(percentage) "average" from result;
Aggregate functions
• MIN
Select min(percentage) "min result" from result;
• MAX
Select MAX(percentage) "MAX result" from result;
• COUNT
select count(distinct id) "number of student" from result;
select count(id) "number of student" from result;
• SUM
select sum(percentage) “sum of result” from result;
Numeric Functions
• ABS(n)
select abs(-15) from dual;
select abs(percentage) “absolute” from student;
• power(m,n)
select power(3,2) “raised” from dual;
select power(semester,2) from result_res;
• round(n,[m])
select round(15.18,1) “round” from dual;
Numeric Functions
• SQRT(n)
select sqrt(2) from dual;
select sqrt(semester) from result;
• EXP(n)
select exp(2) from dual;
select exp(semester) from result;
• EXTRACT
select extract (month from sysdate) "month" from dual;
select extract(month from bday) from student_res;
Numeric Functions
• Other functions
mod(m,n) mod(12,5) ans=2
trunk(123.456,1) ans=123.4
floor(24.8) ans=24
ceil(24.8) ans=25
String Functions
• Lower(char)
select lower('HELLO') “lower case” from dual;
select lower(id) "ID" from result;
• upper(char)
select upper(id) "ID" from result;
• Initcap(char)
converts first letter in capital and rest of letters in small.
select initcap('hELLO') from dual;
String Functions
• SUBSTR(<string> <start pos> <length>)
select substr(‘secure’,3,4 ) “substring” from dual;
select substr(id,3,2) from result;
• length(word)
select length(‘hello’) from dual;
• trim([leading|trailing|both[<trim_character> from]] <string>)
select trim(leading ‘1’ from ‘123abc321’) from dual;
select trim(trailing ‘1’ from ‘123abc321’) from dual;
select trim(both ‘1’ from ‘123abc321’) from dual;
String Functions
• Vsize(<expression>)
returns number of bytes in expression
select vsize(‘database’) from dual;
• ltrim(char[,set])
• Rtrim(char[,set])
• Instr((<string1>,<string 2>,[<start position>],[<nth appearance>])
• Ascii(<single character>)
Set Operations
• UNION & UNION ALL
UNION operator combines the result of two or more SELECT
statements.

select id from result union select id from result1;


select id from result union all select id from result1;

 all the tables in query must have same structure.


 union operator removes duplicate values.
 if duplicates are required in result, UNION ALL operator should be
used.
Union
• Following example shows that union has removed duplicates values.
Union all
• Following example shows that union all has retains duplicates values.
INTERSECT
• This operator gives common values out of two or more select
statements.

Given query will select common value of semester that appears in


both tables.

 select semester from result intersect select semester from result1;


Intersect
MINUS
• The SQL MINUS operator is used to return all rows in the first SELECT
statement that are not returned in the second SELECT statement.

select semester from result minus select semester from result1;


minus
Sub Queries
• Sub query if form of SQL statement that appear inside another sql
statement.
• The statement containing the another query is called parent
statement.
• Parent statement uses result return by sub query.

 select name, address from student where id in (select distinct id


from result);
Correlated sub queries
• A sub query becomes correlated sub query when sub query reference
column from a table in parent query.
• A correlated sub queries are evaluated for each row processed by
parent statement.
• A correlated sub query is one way of reading every row in table and
compare value in each row against related data.
Diff. between subquery & correlated subquery
Example of subquery:
• Select id, semester, percentage from result r where percentage>(select
avg(percentage) from result);
• This is sub query because in case of sub query it executes first and once
and gives result to outer query.
Diff. between subquery & correlated subquery
• While in case of correlated sub query for every row in outer query,
sub query executes.
• Select id, semester, percentage from result r where percentage>(select
avg(percentage) from result where id=r.id);
• Above one is correlated sub query because for every row in table, it
will calculate average.
Exists
• The EXISTS checks the existence of a result of a sub query.
• If sub query return at least one then outer query will gives result for
that particular row.
• Select * from supplier where exist (select * from order where
suppliers.supplier_id = order. supplier_id);
• This SQL EXISTS condition example will return all records from the
suppliers table where there is at least one record in the orders table
with the same supplier_id.
Any
All
join
• An SQL JOIN clause is used to combine rows from two or more tables,
based on a common field between them.
• Four types of join
1. inner join
2. left join
3. right join
4. full join
Inner join
• The INNER JOIN keyword selects all rows from both tables where
there is a match between the columns in both tables.

SELECT column_name(s) FROM table1 INNER JOIN table2


ON table1.column_name=table2.column_name;

select * from student inner join result ON student.id=result.id;


Inner join
Left join
• The LEFT JOIN keyword returns all rows from the left table (table1),
with the matching rows in the right table (table2).
• The result is NULL in the right side when there is no match.

SELECT column_name(s) FROM table1 LEFT JOIN table2


ON table1.column_name=table2.column_name;

select * from student left join result ON student.id=result.id;


Left join
Right join
• The RIGHT JOIN keyword returns all rows from the right table (table2),
with the matching rows in the left table (table1).
• The result is NULL in the left side when there is no match.

SELECT column_name(s) FROM table1 RIGHT JOIN table2


ON table1.column_name=table2.column_name;

select * from student right join result ON student.id=result.id;


Right join
Full join
• full join or full outer join.
• An outer join extends the result of a simple join. An outer join returns
all rows that satisfy the join condition and also returns some or all of
those rows from one table for which no rows from the other satisfy
the join condition.

SELECT column_name(s) FROM table1 FULL OUTER JOIN table2


ON table1.column_name=table2.column_name;

select * from student full outer join result ON student.id=result.id;


Full join
View
• A view is virtual table.
• In SQL, a view is a virtual table based on the result-set of an SQL statement.
• A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
• Views do not contain any data - it is just a stored query in the database that can
be executed when called. View query is stored in data dictionary.
View
Syntax:
• CREATE VIEW view_name AS SELECT column_name(s)
FROM table_name WHERE condition;
• Create view data as select id,name, address from student where
add=‘amd’;
• Select * from data;
View
• Data of the underlying table can also be updated using view.
• If user insert, update or delete data on view, data is updated in the table from
where view is created.
• Insert into data values(’13ce004’,’amar’,’amd’);
View
• Update data set address=‘rajkot’ where id=’13CE004’;
• Delete from data where id=‘13CE004’;
• Select * from student;
Types of View
• There are two types of user defined view.
1. simple view
2. Complex View

• Simple View: when a view is based on single table, it is called


simple view.

Create view data as select id,name, address from student


where add=‘amd’;
Types of View
• Complex View: when a view is based on more than one table, it is
called complex view.
create view data1 as select student.id, name, add, semester,
percentage from student inner join result on student.id=result.id;
Transaction Control Commands
• Transaction control statements manage changes made by DML statements. The
transaction control statements are:
commit
rollback
savepoint
set transaction
• Commit: Use the COMMIT statement to end your current transaction and make
permanent all changes performed in the transaction.
Transaction Control Commands
• Savepoint: Use the SAVEPOINT statement to identify a point in a
transaction to which you can later roll back.

UPDATE employees SET salary = 7000 WHERE last_name = 'Banda';

SAVEPOINT banda_sal;

UPDATE employees SET salary = 12000 WHERE last_name = 'Greene';

SAVEPOINT greene_sal;

ROLLBACK TO SAVEPOINT banda_sal;

COMMIT;
Transaction Control Commands
• Rollback: Use the ROLLBACK statement to undo work done in the current
transaction.
• The ROLLBACK command can be used to undo transactions since the last
COMMIT

ROLLBACK;

• The following statement rolls back your current transaction to savepoint


banda_sal:

ROLLBACK TO SAVEPOINT banda_sal;


Transaction Control Commands
• Set Transaction: Use the SET TRANSACTION statement to establish the
current transaction as read only or read write.

This command is used to specify characteristics for the transaction that follows.

The syntax for SET TRANSACTION is as follows:

SET TRANSACTION [READ WRITE|READ ONLY];


Database Scheme
• People(ssn,fname,lname,city,state)
• Agents(ssn,fname,salary);
• Vehicle(vno, company, year, agent_no);
• Owns(ssn,vno);
• Accidents(acc_date,vin,driver_ssn);
query
• Display all ssn who has purchased vehicle in of maruti company in
2012.
• Display all the vehicles whose agent is having ssn 11245.
• Display detail of all person who met with an accident on 12-dec-2012.
• Display number of agents who have sold at least one vehicles.
• Display name of people from city delhi.

Вам также может понравиться