Intorduction SQL
description
Transcript of Intorduction SQL
![Page 1: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/1.jpg)
Prepared BY: Mitali Sonar
(Assistant Professor)
Intorduction SQL
04/20/231Prepared By: Mitali Sonar (Assistant Professor)
![Page 2: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/2.jpg)
What is database?Collection of information/ meaningful dataEx:- postal address
Values in this fields are dataAddress book is database
Building name
Flat name
Road name
Area
State
pin code
04/20/232 Prepared By: Mitali Sonar (Assistant Professor)
![Page 3: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/3.jpg)
What is DBMS?Software that designs, manages databaseDBMS allows insert, update, delete and
processing of data in databaseEx:-
OracleIngresDbaseMS. Access
04/20/233 Prepared By: Mitali Sonar (Assistant Professor)
![Page 4: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/4.jpg)
What is relational DBMSDBMS based on relational modelStores data in form of related data/tablesDbase can Be viewed in many different waysEx:-
OracleMicrosoft SQL serverSybase SQL ServerDB2MySQL
04/20/234 Prepared By: Mitali Sonar (Assistant Professor)
![Page 5: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/5.jpg)
DBMS Vs. RDBMSDBMS RDBMS
Relationship between two tables or files are maintained programmatically
Relationship between tables or files are maintained at the time of their creation
Does not support client/ server architecture
Support client/ server architecture
No security of the data Multiple levels of the security•At O/S level•Command Level•Object level
Field, records, files Columns (attribute)Rows (tuple)Table (relation)
04/20/235 Prepared By: Mitali Sonar (Assistant Professor)
![Page 6: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/6.jpg)
Introduction to SQLStructured Query Language
Provides interface to RDBMSLanguage for communication with oracle server
to access dataCategory/ component of SQL DDL commands (data definition language)
To create a database objects not dataDefine relation schema ,deleting relations and
modifying relational schemasEx:-
CREATE :- Used to create a db objectALTER :- alter structure of DBDROP:- Delete the object from DBTRUNCATE :- Remove all records from DB
04/20/236 Prepared By: Mitali Sonar (Assistant Professor)
![Page 7: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/7.jpg)
Introduction to SQL (conti…)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)7
DML commands (Data Manipulation Language)To manipulate data of a database objectsIncludes commands to insert tuples into , delete
tuples from and modify tuples in database. INSERT :- Insert data into tableUPDATE:-Updates existing data within tableDELETE :- deletes all records from table
DQL command (Data Query Language) To retrieve the data from a databaseGetting data from database and imposing ordering
upon itSELECT:- retrieve data from the DB
![Page 8: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/8.jpg)
Introduction to SQL (conti…)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)8
DCL commands (Data Control Language)Controlled access to data
GRANT - Used to give privilege to user on object REVOKE - Used to withdraw the privilege that has been
granted to the user. COMMIT:- save work doneROLLBACK :- restore the database to original state
since last commit
![Page 9: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/9.jpg)
Basic data type
04/20/23Prepared By: Mitali Sonar (Assistant Professor)9
char(size) A fixed length character string with only 255 user specified
charactersData held is right padded with spaces to whatever size is
specifiedvarchar2(size)
A variable character length string with alphanumeric valuesmaximum length 4000 charactersInserted values are not contains white spaces
Date a calendar date containing a year, month and day of the
month DD-MON-YYYY
Number (P,S)Used to store a number (fixed or floating point). Max precision can be 38 digitsP – max length of the dataS- number of places to the right of decimal
![Page 10: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/10.jpg)
TABLE fundamentals
04/20/23Prepared By: Mitali Sonar (Assistant Professor)10
Table holds user data & Similar to a spreadsheetConsist of rows (tuples) & columns (attribute)Each column have data type associated with it.Syntax :- CREATE TABLE table_name (col1 datatype(size), ….,
coln datatype(size) );
OUTPUT:-
![Page 11: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/11.jpg)
Inserting data into tables
04/20/23Prepared By: Mitali Sonar (Assistant Professor)11
Loads the value passed by SQL insert command into columns specified
INSERT INTO tablename VALUES(<val 1>,<val 2>…….<valn>);
![Page 12: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/12.jpg)
Viewing data in the tables
04/20/23Prepared By: Mitali Sonar (Assistant Professor)12
SELECT – is used to retrieve rows from one or more tables
All rows & all columnsSELECT * FROM tablename; Ex: - show all employee details
![Page 13: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/13.jpg)
Viewing data in the tables (cont..)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)13
Selected columns & all rowsSELECT Column1, Column2 FROM
tablename;
![Page 14: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/14.jpg)
Viewing data in the tables (cont..)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)14
Selected Rows and all ColumnsSELECT * FROM tablename WHERE conditionEx:- Display details of employee who lives in andheri
area
Ex:- Display details of employee who live in vile parle area
![Page 15: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/15.jpg)
Viewing data in the tables (cont..)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)15
Selected Rows and selected ColumnsSELECT Column1, Column2 FROM tablename
WHERE conditionEx:- list eno and ename who lives in vile parle area
![Page 16: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/16.jpg)
Eliminate duplicate values
04/20/23Prepared By: Mitali Sonar (Assistant Professor)16
DISTINCTIt scans through the values of columns specified
and display only unique values among themSELECT DISTINCT column1 FROM tablename;
![Page 17: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/17.jpg)
Sorting the data
04/20/23Prepared By: Mitali Sonar (Assistant Professor)17
ORDER BY :-retrieves rows from table either ascending or descending order
SELECT * FROM tablename ORDER BY colname (sortorder);
Ex:- show details of employee according to department name.
![Page 18: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/18.jpg)
DELETE operation
04/20/23Prepared By: Mitali Sonar (Assistant Professor)18
Deletes rows from table that satisfies the condition provided by where clause
Removal of all rows form the table DELETE FROM tablename;
Removal of specific rows DELETE FROM tablename where Condition;
![Page 19: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/19.jpg)
Update the content of table
04/20/23Prepared By: Mitali Sonar (Assistant Professor)19
Change or modify the data values in tableUpdating all rowsUPDATE tablename SET col1 = expression1;Ex:- update the department name to research for all
employees
![Page 20: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/20.jpg)
Update the content of table
04/20/23Prepared By: Mitali Sonar (Assistant Professor)20
Change or modify the data values in tableUpdating rows conditionallyUPDATE tablename SET col1 = expression1
WHERE condition;Ex:- update the address of employee sanket from
sion to navi mumbai
NEW TABLE
OLD TABLE
![Page 21: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/21.jpg)
Modifying the structure of the tables
04/20/23Prepared By: Mitali Sonar (Assistant Professor)21
ALTER TABLE :-Changes the structure of existing table
Add, delete columns / changes the datatype of columns /rename the columns or table itself
Adding a new columnALTER TABLE tablename ADD (new_column _name
datatype(size));Ex:- Enter a new field called contactno in table
![Page 22: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/22.jpg)
Modifying the structure of the tables(cont..)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)22
Dropping a column from a tableALTER TABLE tablename DROP COLUMN column
name;Ex- drop the column contactno from the employee
table
![Page 23: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/23.jpg)
Modifying the structure of the tables(cont..)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)23
Modifying Existing columnsALTER TABLE tablename MODIFY (colnname
newdatatype (newsize));
Ex:- Change the employee name field to hold Maximum 30 characters
![Page 24: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/24.jpg)
Restriction to ALTER TABLE
04/20/23Prepared By: Mitali Sonar (Assistant Professor)24
Following task can’t be performed using ALTER TABLE
Change the name of the table /columnsDecrease size of column
RENAME TABLESREANAME tablename to newtablename;Ex:- change the name of table to emp_data;RENAME employee_data TO emp_data;
![Page 25: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/25.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)25
TRUNCATING TABLESEmpties a table completelyDifferent from delete in following ways
Drop and recreates the table that is much faster than deleting
Truncate are not transaction-safe No. of deleted rows are not returned
TRUNCATE TABLE tablename;Ex:- clear all records from employee tableOutput-DESTROYING TABLESWhen table becomes obsolete and needs to be
discarded.Destroys a specific table DROP TABLE tablename;Ex:-DROP TABLE emp_data;O/P :- table dropped.
![Page 26: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/26.jpg)
Examining objects created by users
04/20/23Prepared By: Mitali Sonar (Assistant Professor)26
Finding out tables created by userSELECT table_name FROM user_tables;Displaying the table structure
To display information about columns defined in a tableDESCRIBE tablename;
![Page 27: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/27.jpg)
Data constraints
04/20/23Prepared By: Mitali Sonar (Assistant Professor)27
Set of rules that must be applied to data prior to being stored in DB
Ex:- no employee in sales department should have salary more than 10,000
If there is any violation between the constraint and the data action, the action is aborted by the constraint.
Once constraints is attached to table any SQL INSERT or UPDATE statement automatically causes these constraints to be applied to data before its being stored in table
2 typesI/O constraintBusiness rule constraints
![Page 28: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/28.jpg)
Data constraints
04/20/23Prepared By: Mitali Sonar (Assistant Professor)28
In SQL, we have the following constraints:
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
![Page 29: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/29.jpg)
I/O Constraint
04/20/23Prepared By: Mitali Sonar (Assistant Professor)29
PRIMARY KEY CONSTRAINTS
One or more column in table that uniquely identify each
tuple
No primary key column can contain NULL value
primary key column is a mandatory column
Data held across column must be unique.
Single column primary key is Simple key
A multi column primary key is a Composite primary key
Defined either in CREATE TABLE statement or in ALTER
TABLE statement
![Page 30: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/30.jpg)
PRIMARY KEY CONSTRAINTS
04/20/23Prepared By: Mitali Sonar (Assistant Professor)30
Syntax : Column-name datatype(size) primary key
Ex: CREATE TABLE Employee(
ENO number(4) primary key,
ENAME varchar2(20));PRIMARY KEY (column-name1, column-name2)Ex: CREATE TABLE Employee(
ENO number(4),
ENAME varchar2(20),
CONSTRAINT pk_ENO primary key (ENO));EX:- ALTER TABLE Employee
ADD CONSTRAINT pk_ENO primary key (ENO));
![Page 31: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/31.jpg)
Foreign key constraints
04/20/23Prepared By: Mitali Sonar (Assistant Professor)31
Represents relationship between two tablesIts value is derived from primary key of the other tableTable in which foreign key is defined is called
foreign tableTable in which primary key is defined is called
master tableSyntax :- REFERENCES tablename.columnnameFeaturesParent that is being referenced has to be unique Child may have duplicateParent record can be deleted provided no child existsMaster table cannot be updated if child record exists
![Page 32: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/32.jpg)
Foreign key constraints
04/20/23Prepared By: Mitali Sonar (Assistant Professor)32
create table branch(branch_name char(15),branch_city char(30),assetsnumber(12,2),primary key (branch_name ));
create table account(account_number char(10),branch_name char(15),balance integer,primary key (account_number), references branch (branch_name) );
![Page 33: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/33.jpg)
Foreign key constraint
04/20/23Prepared By: Mitali Sonar (Assistant Professor)33
Insert/update operations in foreign A value cannot be inserted in foreign table if
corresponding value is not presented in master table
![Page 34: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/34.jpg)
Foreign key constraints
04/20/23Prepared By: Mitali Sonar (Assistant Professor)34
Delete operation on primary key table(master table)Oracle display error message when deleting a record
form master table and corresponding record exists in foreign key table
This will prevent the delete operation form execution
![Page 35: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/35.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)35
ON DELETE CASCADEIf a record is deleted in master table , all
corresponding records in foreign key table is also deleted.
create table "branch" (`"branch_name" char(15), "branch_city" char(30), "assets" number(12,2), constraint "branch_con" foreign key ("branch_name") references "account" ("branch_name") ON DELETE CASCADE ENABLE )
![Page 36: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/36.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)36
![Page 37: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/37.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)37
ON DELETE SET NULLIf a record is deleted from Master table, the
value held by foreign key table is set to NullThe records in foreign key table will not
deletedcreate table "branch" (
"branch_name" char(15), "branch_city" char(30), "assets" number(12,2), constraint "branch_con" foreign key ("branch_name") references "account" ("branch_name") ON DELETE SET NULL)
![Page 38: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/38.jpg)
Unique key constraint
04/20/23Prepared By: Mitali Sonar (Assistant Professor)38
It permits multiple entries of NULL into columnIt will not allowed duplicate valueA table can have more than one unique key that
is not possible for primary key
ALTER TABLE customerADD CONSTRAINT Cust_con UNIQUE (cust_no);
![Page 39: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/39.jpg)
BUSINESS RULE CONSTRAINT
04/20/23Prepared By: Mitali Sonar (Assistant Professor)39
Rules are applied to data prior the data is being inserted
This will ensure that data in table have integrityEx;- Rule ” no employee in company shall get a
salary less than 10000”Inserted to column or table using create table or
alter tableConstraints can be defined at
Column levelTable level
![Page 40: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/40.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)40
NULL VALUE CONCEPTSSome fields do not have values because information is not
available at time of data entryWill place NULL value that is different from blank(if data
type is character) or zero(if data type is number)Null can be inserted in columns of any data type If a column has NULL value than oracle ignore UNIQUE,
FOREIGN KEY, CHECK constraintsNOT NULL conceptEnsures that column cannot left emptyOnly be applied at column level If column is defined as not null, that column becomes a
mandatory column
![Page 41: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/41.jpg)
CHECK CONSTRAINT
04/20/23Prepared By: Mitali Sonar (Assistant Professor)41
used to limit the value range that can be placed in a column.
Specified as logical expression that evaluates as TRUE or FALSE
CHECK constraint on a single column allows only certain values for this column.
CHECK constraint on a table can limit the values in certain columns based on values in
other columns in the row.CREATE TABLE Persons
(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT chk_Person CHECK (P_Id>0 and City=‘Ahmedabad'))
![Page 42: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/42.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)42
Create table customer_master( cust_no varchar2(5), Fname varchar2(10), Lname
varchar2(10),CHECK (cust_no like ‘C%’),CHECK (Fname =UPPER (FNAME)));
If condition has false value error message will be displayed and processing stops there
![Page 43: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/43.jpg)
Default Constraint
04/20/23Prepared By: Mitali Sonar (Assistant Professor)43
used to insert a default value into a column.The default value will be added to all new
records, if no other value is specified.
CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255) DEFAULT ‘ahmedabad');
![Page 44: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/44.jpg)
Create the tables described as follow
04/20/23Prepared By: Mitali Sonar (Assistant Professor)44
Table name: Product MasterColumn Name
Data Type
Size
Attribute
PRODUCT NO Varchar2 6 PRIMARY KEY/ first letter must start with ‘P’
DESCRIPTION Varchar2 15 Not Null
PROFITPERCENT
Number 4,2 Not Null
SELLPRICE Number 8,2 Not Null, cannot be 0
COSTPRICE Number 8,2 Not null, cannot be 0
![Page 45: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/45.jpg)
Computations done on table data
04/20/23Prepared By: Mitali Sonar (Assistant Professor)45
manipulates individual data items and returns a result.
Ex:- display all employee’s detail with their annual salary (salary *12)
Arithmetic operators/ Division (numbers and dates)
SELECT SAL / 10 FROM EMP;
* Multiplication SELECT SAL * 5 FROM EMP;+ Addition (numbers
and dates)SELECT SAL + 200 FROM EMP;
- Subtraction (numbers and dates)
SELECT SAL - 100 FROM EMP;
![Page 46: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/46.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)46
C_code
cname city areacountry
gradeopening_amt
receive_amt
payment_amt
outstanding_amt
C00013
Holmes
London
London
UK 26000.00
5000.00
7000.00
4000.00
C00001
Micheal
New York
New York
USA 23000.00
5000.00
2000.00
6000.00
Customer Table
SELECT cname, opening_amt, receive_amt,(opening_amt + receive_amt) FROM customer WHERE (opening_amt + receive_amt)>15000;
![Page 47: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/47.jpg)
Renaming the column used with expression
04/20/23Prepared By: Mitali Sonar (Assistant Professor)47
SQL aliases are used to give a column in a table, a temporary name.
SELECT column_name AS alias_name FROM table_name;C_ID C_Name Contact
NameAddress City PostalC
odeCountry
1 Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados
Ana Trujillo
Avda. de la Constitución 2222
México D.F.
05021 Mexico
3 Antonio Moreno Taquería
Antonio Moreno
Mataderos 2312
México D.F.
05023 Mexico
![Page 48: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/48.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)48
SELECT C_Name, Address+City+PostalCode+Country AS AddressFROM Customers;
![Page 49: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/49.jpg)
Logical operators
04/20/23Prepared By: Mitali Sonar (Assistant Professor)49
Logical operators in SQL will return either true or false value.Logical
OperatorsDescription
OR At least one of the conditions must be true.
AND All the specified conditions must be true.
NOT Reversed the result of logical expression
![Page 50: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/50.jpg)
"OR" Logical Operator:
04/20/23Prepared By: Mitali Sonar (Assistant Professor)50
find the details of students who are studying either Maths or Science, the query would be like,
SELECT * FROM studentdetails
WHERE sub1 = 'Maths' OR sub1= 'Science'
![Page 51: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/51.jpg)
AND logical operator
04/20/23Prepared By: Mitali Sonar (Assistant Professor)51
Joins two or more conditions, and returns results only when all of the conditions are true
find the details of students, who got marks more than 70 and less than 100Select * from studentdetails Where Marks >70 and Marks<100;
![Page 52: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/52.jpg)
NOT logical operator
04/20/23Prepared By: Mitali Sonar (Assistant Professor)52
Reversed the result of logical expressionFind rows that do not satisfy a conditionFind details of the students who are not
Studying MathsSELECT *
FROM studentdetails WHERE NOT sub1= ‘Maths' ;
![Page 53: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/53.jpg)
Combining OR and AND Operators
04/20/23Prepared By: Mitali Sonar (Assistant Professor)53
• When the AND operator is combined with OR• Oracle server will evaluate the condition connected
by the AND first before any conditions connected with OR.
• Parenthesis must be used to force an order of operation.
Find out details of the students Who studying Maths or Science And marks >=70 SELECT *
FROM studentdetails where Sub1=‘Maths’ or sub1 =‘Science’ AND Marks>=70 SELECT *
FROM studentdetails where ( Sub1=‘Maths’ or sub1 =‘Science’) AND Marks>=70
![Page 54: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/54.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)54
Employee
Sales-master
List all employee who stay in city ‘Banglore’ or ‘Manglore’
List details of employee who are not inhabit in the state of ‘Maharashtra’
List the products whose selling price is more than 500 and less than 750.
Calculate a new selling price as basic_cost plus profit rate and rename this column in output as new_price
First name Last Name Address1 City State
P_no P_name Basic_cost Profit_rate Selling _Price
![Page 55: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/55.jpg)
Range searching
04/20/23Prepared By: Mitali Sonar (Assistant Professor)55
IN and NOT IN operatortesting a condition by comparing it with a list of
fixed values.column value is equal to any one of a specified set
of valuesfind the names of students who are studying either
Maths or Science,SELECT * FROM studentdetails WHERE sub1 IN ('Maths', 'Science');
![Page 56: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/56.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)56
Find out details of students who got marks either 90 or 80 or 60
Select * from studentdetails where marks in (90,80,60);
Select * from studentdetails where marks not in (90,80,60);
![Page 57: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/57.jpg)
BETWEEN and NOT BETWEEN operator
04/20/23Prepared By: Mitali Sonar (Assistant Professor)57
Tests an expression against a rangeIn between two valuesThis eliminates the need to use a more complex
WHERE clause involving the use of the AND logical operator.
Find out details of students who got marks in the range 70 to 90Select * from studentdetails where marks BETWEEN 70 AND 90 Select * from studentdetails where marks NOT BETWEEN 70 AND 90
![Page 58: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/58.jpg)
LIKE AND NOT LIKE operator
04/20/23Prepared By: Mitali Sonar (Assistant Professor)58
used to search for data rows containing incomplete or partial character strings within a data column.
When one does not know the exact
value for the search conditionsFind the details of employee
Whose name start with ‘pa’Select * from employee
Where empname1 like ‘pa%’;
Select * from employee
Where empname1 not like ‘pa%’;
![Page 59: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/59.jpg)
LIKE AND NOT LIKE operator
04/20/23Prepared By: Mitali Sonar (Assistant Professor)59
Symbol Represents
% match any string of any length
_ match on a single character
[ ] (brackets) any single character within a specified range
such as 'a' to 'd', inclusive [a-d] or a set of characters such as [aeiouy]
[^] (not brackets)
any single character not in the specified range or set. (e.g., [^a-f] )
LIKE '%en%' will search for every word that has the letters 'en' in it (Green, Benten)LIKE '_heryl' will search for every six-letter name ending with 'heryl' (Cheryl).
![Page 60: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/60.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)60
LIKE '[CK]ars[eo]n ' will search for every six-letter name begins with a 'C' or 'K' (not both of them) and Second last letter should be 'e' or 'o' (e.g., 'Carsen,' 'Karsen,' 'Carson,' and 'Karson‘)
LIKE '[P-T]inger' will search for all the names ending with 'inger‘ begin with any single letter ‘P' thru ‘T' (Singer,
Ringer).LIKE 'M[^c]%' will search for all the names
begin with 'M' not having 'c' as the second letter.
![Page 61: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/61.jpg)
SQL GROUP Functions
04/20/23Prepared By: Mitali Sonar (Assistant Professor)61
built-in SQL functions that operate on groups of rows return one value for the entire group. COUNT, MAX, MIN, AVG, SUM, DISTINCTCOUNT ():Returns the number of rows in the table that satisfies the
condition specified in the WHERE condition. SELECT COUNT(marks) from
Studnetdetails Where marks>70SELECT COUNT(*) from
studentdetails.
![Page 62: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/62.jpg)
SQL GROUP Functions
04/20/23Prepared By: Mitali Sonar (Assistant Professor)62
MAX(): used to get the maximum value from a column.
To get the maximum marks SELECT MAX(MARKS) from studentdetails
MIN(): is used to get the minimum value from a column.
To get the minimum marks SELECT MIN(MARKS) from studentdetails
![Page 63: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/63.jpg)
SQL GROUP Functions
04/20/23Prepared By: Mitali Sonar (Assistant Professor)63
AVG(): The average value of a numeric column.To get the average marks, SELECT AVG (marks) FROM
studentdetail;
SUM(): sum of a numeric columnTo get the total marks given out to the students,SELECT SUM (marks) FROM studentdetail;
DISTINCT(): to select the distinct rows.SELECT distinct(marks) from studentdetail;
![Page 64: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/64.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)64
List out the names of students having ‘a’ as the second letter in their name
Count the total number of students.Determine max and min marks of the students.Count the number of students who got more than
50 marks in science subject
![Page 65: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/65.jpg)
Mathematical functionsCEIL (or CEILING) and FLOOR round the numbersCEIL roundup to the nearest integer value FLOOR round down to the next least integer
value.SELECT CEIL(10.19) AS ceil_value,FLOOR(10.19) AS floor_valueOUTPUT ceil_value floor_value---------- ----------- 11 10
04/20/23Prepared By: Mitali Sonar (Assistant Professor)65
![Page 66: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/66.jpg)
RAND Functionused to generate some random numbers at run
timeSELECT RAND() AS random_value
OUTPUTrandom_value ---------------0.4179369289595
04/20/23Prepared By: Mitali Sonar (Assistant Professor)66
![Page 67: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/67.jpg)
ABS functionfunction returns the absolute value of an numeric
input argument.EXSELECT ABS(-10) as arg1, ABS(10) AS arg2OUTPUT arg1 arg2 ------ ------ 10 10
04/20/23Prepared By: Mitali Sonar (Assistant Professor)67
![Page 68: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/68.jpg)
SQRT functionextracts the square root from the positive
numeric input argument. SELECT SQRT(100) AS sqrt_of_100Output
Sqrt of 10010
POWER functionSELECT POWER(10,2) AS power_valueOUTPUTPower_value100
04/20/23Prepared By: Mitali Sonar (Assistant Professor)68
![Page 69: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/69.jpg)
ROUND Function rounds a number to a specific length or precisionSELECT ROUND(10.09 ,1)
positive_rounded_value, ROUND(10.09 ,-1)
negative_rounded_value
OUTPUTpositive_rounded_value
negative_rounded_value---------------------- ---------------------- 10.1 10
04/20/23Prepared By: Mitali Sonar (Assistant Professor)69
![Page 70: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/70.jpg)
Character Functions
CharacterCharacterfunctionsfunctions
LOWERLOWER
UPPERUPPER
INITCAPINITCAP
CONCATCONCAT
SUBSTRSUBSTR
LENGTHLENGTH
INSTRINSTR
LPADLPAD
Case conversion Case conversion functionsfunctions
Character manipulationCharacter manipulationfunctionsfunctions
![Page 71: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/71.jpg)
String function
04/20/23Prepared By: Mitali Sonar (Assistant Professor)71
LOWER()
Converts string into lowercase
Select LOWER(‘ABCD’) from dual
UPPER() Converts string into uppercase
Select UPPER(‘abc’) from dual
INITCAP()
Converts first letter of each word in uppercase
Select INITCAP(‘abcd’) from dual
![Page 72: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/72.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)72
LTRIM(string,trimlist) & RTRIM(string,trimlist) Returns string with the leftmost or rightmost characters
that match the characters in trimlist
SUBSTR(string,pos,len)Returns the substring of string which begins at pos and is
len characters long
ASCII()Return numeric value of left-most character
![Page 73: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/73.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)73
INSTR() Return the index of the first occurrence of substring
LENGTH(string)Return the length of a string in characters
LPAD(string, length, pad) & RPAD(string, length, pad)
Return the string argument, left-padded or right padded with the specified string
![Page 74: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/74.jpg)
04/20/23Prepared By: Mitali Sonar (Assistant Professor)74
REPLACE(string,target,replacement)Returns string with all occurrences of target replaced
with replacement
REVERSE(str)Returns the string str with the order of the characters
reversed.
CONCAT(str1,str2)Returns the string that results from concatenating the
arguments.
![Page 75: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/75.jpg)
Working with Dates
Oracle stores dates in an internal numeric format: century, year, month, day, hours, minutes, seconds.
The default date format is DD-MON-YY.SYSDATE is a function returning date and
time.DUAL is a dummy table used to view
SYSDATE.
![Page 76: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/76.jpg)
Date Functions
Number of monthsbetween two dates
MONTHS_BETWEEN
ADD_MONTHS
NEXT_DAY
LAST_DAY
Add calendar months to date
Next day of the date specified
Last day of the month
Function Description
![Page 77: Intorduction SQL](https://reader035.fdocuments.net/reader035/viewer/2022062304/568139e7550346895da19f6f/html5/thumbnails/77.jpg)
• MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')
Using Date FunctionsUsing Date Functions
• ADD_MONTHS ('11-JAN-94',6)ADD_MONTHS ('11-JAN-94',6)
• NEXT_DAY ('01-SEP-95','FRIDAY') NEXT_DAY ('01-SEP-95','FRIDAY')
• LAST_DAY('01-SEP-95')LAST_DAY('01-SEP-95')
19.677419419.6774194
'11-JUL-94''11-JUL-94'
'08-SEP-95''08-SEP-95'
'30-SEP-95''30-SEP-95'