samson dbms (R23) FULL NOTES-1_removed
samson dbms (R23) FULL NOTES-1_removed
Example: C hange the name of teacher to ‘ARJUN RAO’ whose name is ‘A.RAO’
SQL> UPDATE teacher SET name=’ARJUN RAO’ where name=’A.RAO’;
DELETE COMMAND:
DELETE command is used to delete a specific single record or group of records or all records
based on the given condition in WHERE clause. It is DML command.
It delete the records temporarily from the table. We can rollback the deleted records before
COMMIT command.
Syntax:
DELETE from tablename where condition;
Example: Delete a teacher record whose id=3;
SQL> DELETE from teacher where id=3;
Example: Delete a teacher record whose name is ‘B.RAO’
SQL>DELETE from teacher where name=’B.RAO’;
If you want to access all rows from all fields of the table, use the following SELECT syntax with
* asterisk sign:
UNIT 3
SQL:Basic SQL querying (select and project) using where clause, arithmetic & logical
operations, SQL functions(Date and Time, Numeric, String conversion).Creating tables with
relationship, implementation of key and integrity constraints, nested queries, sub queries,
grouping, aggregation, ordering, implementation of different types of joins, view(updatable and
non-updatable), relational set operations.
a. Selection:
Selection is used to filter rows based on specific conditions.
Selection of rows by using SELECT and WHERE clauses.
Syntax:
SELECT * FROM table_name WHERE condition;
The * operator indicates all columns in a row.
Consider the following table “TEACHER”
Table: TEACHER
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20
Example1: Query to display teachers whose age is greaterthan or equal to 40 years
SQL>SELECT * from teacher where age>=40;
Output:
Id Name Age
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
b. Projection:
Projection is used to select specific columns for display.
Projection of particular columns by using SELECT and WHERE clauses.
Syntax:
SELECT c1,c2,c3.. FROM table_name WHERE condition;
The c1,c2,c3.. are the columns names to display.
Consider the following table “TEACHER”
Table: TEACHER
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20
Example1: Query to display names of the teachers whose age is greater than or equal to 40 years
SQL> SELECT name from teacher where age>=40;
Output:
Name
RAMA RAO
CHANDRA RAO
DURGA RAO
Example2: Query to display Name and ages of teachers whose age is below 40 years
SQL> SELECT name, age from teacher where age<40;
Output:
Name Age
ANAND RAO 30
ANAND KRISHNA 20
Examples:
SQL>Select sal+1000 from emp;
Ans: all salaries with addition of 1000
Examples:
Select * from EMP where sal>=5000;
Ans: all salaries greater than or equal to 5000
Operator can be any relational operator (< , > , !=, = , >=, <=,<>)
Example2: Query to display teachers whose age is greater than 40 and less than 60 years
SQL>SELECT * from teacher where age>40 AND age<60;
Output:
Id Name Age
3 CHANDRA RAO 50
LIKE:
Where Clause with LIKE Operator
It is used to fetch filtered data by searching for a particular pattern in the where clause.
Syntax:
SELECT column1,column2 FROM table_name WHERE column_name LIKE pattern;
Pattern is exact value extracted from the pattern to get related data in the result set.
Note: The character(s) in the pattern is case-insensitive.
To fetch records of Teachers where Name starts with the letter S. Query:
Example1: Query to display Teachers where Name starts with the letter A.
SQL>SELECT * from teacher where Name LIKE 'A%';
The ‘%'(wildcard) signifies the later characters here which can be of any length.
Output:
Id Name Age
1 ANAND RAO 30
5 ANAND KRISHNA 20
Example2: Query to display Teachers where Name contains the pattern ‘N’.
SQL> SELECT * from teacher where Name LIKE '%N%';
Output:
Id Name Age
1 ANAND RAO 30
3 CHANDRA RAO 50
5 ANAND KRISHNA 20
IN:
Where Clause with IN Operator, it is used to fetch the filtered data same as fetched by ‘=’
operator just the difference is that here we can specify multiple values for which we can get the
result set.
Syntax:
SELECT column1, column2 FROM table_name WHERE column_name IN (value1, value2,..);
value1, value2,..: exact value matching the values given and get related data in the result set.
1. Scalar Functions:
The Scalar Functions in SQL are used to return a single value from the given input value. Each
record is operated independently by the function.
Types of Functions:
a. Numeric Functions
b. String Functions
c. Date & Time Functions
d. Conversion Functions
Numeric Functions:
These functions take number type values or columns parameters
Function Value Returned
ABS ( m ) Absolute value of m
MOD ( m, n ) Remainder of m divided by n
POWER ( m, n ) m raised to the nth power
ROUND ( m , n ) m rounded to the nth decimal place
TRUNC ( m, n ) m truncated to the nth decimal place
SQRT ( n ) positive square root of n
EXP ( n ) e raised to the power n
LN ( n ) natural logarithm of n
LOG ( n2, n1 ) logarithm of n1, base n2
CEIL ( n ) smallest integer greater than or equal to n
FLOOR ( n ) greatest integer smaller than or equal to n
Examples:
SQL> select ABS(-65) from dual;
Ans:65
SQL>select CEIL(18.2) from dual;
Ans: 19
SQL>select FLOOR(18.2) from dual;
Ans:18
SQL>select POWER(10,2) from dual;
Ans:100
SQL>select SQRT(16) from dual;
Ans:4
STRING Functions
These functions take string type values or columns parameters
Examples:
SQL> select CONCAT('Tamota','soup') "Dinner" from dual;
Ans: Tamotasoup
Example3: Query to display all names and length of the names of Teachers
SQL> select name, length(name) from teacher;
Ouput:
Id Name Length(name)
1 ANAND RAO 9
2 RAMA RAO 8
3 CHANDRA RAO 11
4 DURGA RAO 9
5 ANAND KRISHNA 13
Conversion Functions
Function Input Argument Value Returned
TO_CHAR ( m [, fmt ] ) m = numeric value, fmt = Number m converted to
format character string as specified by
the format
TO_NUMBER ( s [, fmt ] ) s = character string, fmt = Character string s converted to
format a number as specified by the
format
TO_DATE ( s [, fmt ] ) s = character string, fmt = String s converted to a date
format for date value
Examples:
SQL> select SYSDATE, TO_CHAR(SYSDATE,'DAY') from dual;
Ans: Monday (if the sysdate is 09-05-2022)
SQL> Select TO_CHAR(sysdate, 'yyyy/mm/dd') from dual;
Ans: ‘2022/05/09’ if the sysdate is 09/05/2022
SQL> Select TO_CHAR(sysdate, 'Month DD, YYYY') from dual;
Ans: ‘May 05,2022 if the sysdate is 09/05/2022
SQL> SELECT TO_DATE('09-05-2022', 'DD-MM-YYYY') FROM DUAL;
Converts ‘09-05-2022’ i.e string into Date type
2. Aggregate Functions
Performing calculations on multiple rows of a single column of a table and returning a single
value.The commonly used aggregated functions are
HAVING Clause
We can use HAVING clause to place conditions to decide which group will be the part of final
result-set. Also we can not use the aggregate functions like SUM(), COUNT() etc. with
WHERE clause. So we have to use HAVING clause if we want to use any of these functions in
the conditions
Syntax:
SELECT column1, function_name(column2)
FROM table_name WHERE condition
GROUP BY column1, column2 HAVING condition ORDER BY column1, column2;
Example5: Write a query to display department wise total salary of employees in the table
‘EMP’
SQL> SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO;
Output:
DEPTNO SUM(SAL)
10 8750
20 10875
30 17900
Example6: Write a query to display department wise total salary of employees which department
wise sum is >10000 in the table ‘EMP’
SQL> SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO HAVING
SUM(SAL)>10000;
Output:
DEPTNO SUM(SAL)
20 10875
30 17900
ORDER BY:
The ORDER BY statement in SQL is used to sort the fetched data in either ascending or
descending according to one or more columns.
• By default ORDER BY sorts the data in ascending order.
• We can use the keyword DESC to sort the data in descending order and the keyword
ASC to sort in ascending order.
Syntax of all ways of using ORDER BY is shown below:
• Sort according to one column: To sort in ascending or descending order we can use the
keywords ASC or DESC respectively.
Syntax:
SELECT * FROM table_name ORDER BY column_name ASC|DESC
Sort according to multiple columns: To sort in ascending or descending order we can use the
keywords ASC or DESC respectively. To sort according to multiple columns, separate the names
of columns by (,) operator.
Syntax:
SELECT * FROM table_name ORDER BY column1 ASC|DESC , column2 ASC|DESC
Child Table: Child table is the table, the data of this table should references to the column in
parent table..
It should have same column name of the parent table.
The child table maintains a foreign key on the same column of the parent table.
Example: Create emp table as child table, in this deptno is the foreign key attribute.
create table emp
( empno number(5) primary key,
ename varchar2(10) not null,
sal number(7,2),
deptno number(2),
foreign key(deptno) references dept);
Constraints: You can place constraints to limit the type of data that can go into a table.
Common types of constraints include the following:
UNIQUE Constraint : Ensures that all values in a column are distinct.
NOT NULL Constraint : Ensures that a column cannot have NULL value.
CHECK Constraint : Makes sure that all values in a column satisfy certain criteria.
PRIMARY KEY Constraint : Ensures that all values in a column are distinct and a
Column can’t have NULL value.
FOREIGN KEY Constraint : Used to ensure referential integrity of the data.
UNIQUE Constraint:-
SQL> CREATE TABLE Customer
(SID integer Unique,
First_Name varchar2(30),
Last_Name varchar2(30));
SID FIRST_NAME LAST_NAME
1212 RAJENDRA PRASAD
1201 PURNA CHANDRARAO
1215 LITHEN KUMAR
1242 DIVYA SREE
1243 BHAVYA SREE
1238 SUDHEER BABU
It will result in an error because '1242' already exists in the SID column, thus trying to insert
another row with that value violates the UNIQUE constraint.
Check Constraint:-
SQL> create table emp (empno number(5) ,ename varchar2(10) sal number(7,2) check(sal>=500
and sal<=10000));
Executing the following SQL statement,
SQL> INSERT INTO emp values (100, ‘Rama’ , 20000);
It will result in an error
A subquery is a query within another query. The outer query is called as main query and
inner query is called as subquery.
The subquery generally executes first, and its output is used to complete the query
condition for the main or outer query.
Subquery must be enclosed in parentheses.
A sub query is typically appears within the where clause of a query.
Syntax:
SELECT column_name FROM table_name WHERE column_name
expression_operator ( SELECT COLUMN_NAME from TABLE_NAME
WHERE ……... );
Example: Find the names of sailors who have reserved at least one boat.
Example: Find the names of sailors who have reserved a red or green boat.
CORRELATED QUERY –
In Correlated Query, Outer query executes first and for every Outer query row Inner query is
executed. Hence, Inner query uses values from Outer query.
Example –
Orders (OrderID, CustomerID, OrderDate);
Customers (CustomerID, CustomerName, ContactName, Country);
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records
from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table
Examples:
Consider the following two student tables:
OFFICE EXAM-SECTION
ROLLNO TUTIONFEE_DUE ROLLNO EXAMFEE_DUE
501 50000 501 500
502 80000 502 800
503 30000 504 300
505 20000 506 200
Inner join
Example: The query displays all students who have both Tution and Exam Fees due
employees with their working department name:
SELECT O.ROLLNO, O.TUTIONFEE_DUE, E.EXMFEE_DUE FROM OFFICE O
INNER JOIN EXAM-SECTION E ON O.ROLLNO=E,ROLLNO;
Rollnos 503 & 505 only have TutionFee_due but not ExamFee_due.
Self join
A table can join with the same table. One table can be assumed as two tables by using the
alias names and then perform the join operations on rows.
Example: The following query displays the students details whose DUE is lessthan other
Views in SQL are a type of virtual table that simplifies how users interact with data across one
or more tables. Unlike traditional tables, a view in SQL does not store data on disk; instead, it
dynamically retrieves data based on a pre-defined query each time it’s accessed.
We can create a view using CREATE VIEW statement. A View can be created from a single
table or multiple tables.
Syntax:
CREATE VIEW view_name AS SELECT column1, column2….. FROM table_name WHERE
condition;
Updatable views
Updatable views can be modified using INSERT, UPDATE, or DELETE statements, while
non-updatable views cannot.
Updatable views
Can contain both updatable and non-updatable columns
Have a one-to-one relationship between the rows in the view and the rows in the underlying
table
Can be used in statements such as UPDATE, DELETE, or INSERT to update the contents of
the underlying table
Non-updatable views
Cannot be modified using INSERT, UPDATE, or DELETE statements
Contain constructs such as aggregate functions, window functions, DISTINCT, GROUP BY,
HAVING, UNION or UNION ALL, or a subquery in the select list
Consider the following table “TEACHER”
Table: TEACHER
Id Name Age
1 ANAND RAO 30
2 RAMA RAO 40
3 CHANDRA RAO 50
4 DURGA RAO 60
5 ANAND KRISHNA 20
OUTPUT:
Id Name Age
3 CHANDRA RAO 50
4 DURGA RAO 60
UNION Operator
The Union operator returns rows from both tables. If used by itself, UNION returns a distinct
list of rows.
Using UNION ALL, returns all rows from both tables.
A UNION is useful when you want to sort results from two separate queries as one combined
result.
For instance if you have two tables, Teacher1 & Teacher2
Example: query to display name of teachers from both tables
SQL> select name from Teacher1 UNION select name from Teacher2;
Name
ANAND RAO
RAMA RAO
CHANDRA RAO
DURGA RAO
ANAND KRISHNA
DURGA RAO
ANAND KRISHNA
INTERSECT Operator
Use an intersect operator to returns rows that are in common between two tables; it returns
unique rows from both the left and right query.
This query is useful when you want to find results that are in common between two queries.
Continuing with Vendors, and Customers, suppose you want to find vendors that are also
customers. You can do so easily using:
SQL> select name from Teacher1 INTERSECT select name from Teacher2;
Name
RAMA RAO
EXCEPT Operator
Use the EXCEPT Operator to return only rows found in the left query.
It returns unique rows from the left query that aren’t in the right query’s results.
This is similar to MINUS command in other sql softwares. This query is useful when you’re
looking to find rows that are in one set but not another.
For example, to create a list of all Teachers that are in Teacher1 table but not in Teachers table:
SQL> select name from Teacher1 EXCEPT select name from Teacher2;
Table: TEACHER1
Id Name Age
1 ANAND RAO 30
3 CHANDRA RAO 50
EXISTS Operator
The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns TRUE if the subquery returns one or more records.
Example: The following query display the Sailors who reserves at least one boat.