SQL Notes
SQL Notes
Data
Database
DBMS
user DBMS DB
Objectives
1. Mass storage:
DBMS allows to store thousands of data in the database. We can fetch the
data whenever required.
2. Data Redundancy:
If we are storing the same data multiple times in the database then the data
duplication will occur. Here DBMS guaranties, it won’t accept any
duplication data in the database.
3. Data Protection:
Bank details should always kept secure. Here DBMS provide a master level
security for the data in the database.
4. Platform Independent:
We can run DBMS on any Platforms.
5. Improved Data sharing:
The data stored in the database can be retrieved very quickly, sufficiently,
and securely across any organisation with the help of DBMS.
Types of DBMS
1. HDBMS ( Hierarchial DBMS):
IN NDBMS, the data will be stored in the form of structure but all the data will
be interconnected.
In RDBMS, the data will be stored in the form of tables, in this case both
inserting and retrieving is easy.
In object oriented DBMS, the data will be store in the form of objectives
Data Models
Data models are used to define how the data is processed and stored into the
database.
Data Types
Data types are used to define what kind of data that can be entered or stored
into the column of the table
Types
Number
Integer
2. string data type
The string data type classified into three types
char(size)
varchar(size)
varchar2
among these three types, we will prefer to use varchar data type because, left
out memory will be wasted. Both Varchar and varchar2 are same but varchar
allows 2000 bytes of memory where as varchar2 allows 4000 bytes of memory
For date data type, no need to give the size and default date format in SQL
’DD-mm-YY’
The sub languages of SQL are fetching the data, creating our own tables in the
database, performing some alterations to the created table and so on.
DQL
DML
DDL
TCL
DCL
DQL is mainly used to fetch the data from the data base. In DQL we have only
one command that is
Select
Syntax
Select * from table _ name;
From- from clause is used to specify from which table we are going to fetch
the data
*- is an operator which will display all the records from the table
Questions
1. Write a query to fetch all the data from the Emp table
2. Display name and salary of the emp table
3. Display name, designation and their joining date from the employee
table
4. Display the department information of the employee table
5. Display the department name of the employee
Operators
Types of operators
Arithmetic
Logical
Relational
String
Set
Special Operator
1. Arithmetic Operator
Where clause – where clause is used to fetch the particular record from
the table
Literals
A literals is nothing but a fixed data which might be available inside
the table or outside the table and literal are some constant
Logical operator
All the logical operators will display the output based on multiple
condition checking
Types of logical operators
1. Logical AND
2. Logical OR
3. Logical NOT
1. Logical AND
If both the conditions are true the AND operator gets executed and
display the output
2. OR
If one conditions are true, then OR operator gets executed and
displays the output
3. NOT
It displays the output when none of the conditions are true
Questions
Relational Operator
The relational operator are used to compare two values or two
expressions it is also known as comparison operator
questions
Special Operator
Like
Between
Is null
In
AS
Like Operator
Like operator is used to search query specified pattern. Incase like operator we
have to use, two wildcard characters ‘%” & “_”.
Syntax
Questions
Between operator
Syntax
QUESTIONS
SYNTAX
Questions
1. List all the employees details who are all not getting
commission
2. Display the employees who all are earning commission
3. Display the details of employees who don’t have repoting
manager
4. Display the details of employees who all are having reporting
manager
IN operator
Syntax
Questions
1. Write a query to fetch the details of smith, allen and scott
2. Display the name and salary of employees who are working
department 10 & 20
3. Display the department information of employees who are
working in research and sales department
4. Write a query to fetch employee id, name and commission of
all the salesman and the manager
AS or Aliasing Operator
Syntax
Set operator
Set operator are used to fetch the information of same data
type and same values from two or more tables
conditions
Number of columns in each result set should be same
Column data types should be compatible
Types
Union
Union all
Intersect
Except
Union
Syntax
Union all
Syntax
Intersect
Syntax
Except
Syntax
DML buffer(commit) DB
DML commands
Insert
Update
Delete
Insert
Syntax
Or
Note
If we try to insert low number of columns data also will get error
Update
Syntax
Questions
Delete
Syntax
Questions
constraints
Types of constraints
Unique
Not null
Default
Check
Primary key
Foreign key
Unique
Not null
It ensures there will be no null values present in the column of the table
for one table, we can have multiple not null constraint
Default
It set a default value, if no values is specified by a user. For one table ,
we can have multiple default constraints
Check
It will allows the values to enter into the columns if it satisfies a specific
condition. For one table, we can have multiple check constraints
Primary key
Foreign key
It is used to connect or join two or more table. The foreign key column
of child table will take the reference of primary key column present in
the parent table and connect both table by using relationship for one
table, we can have multiple foreign key. The foreign key contains both
duplication and not null
DDL commands are used to create our own table in the database, to
perform some alterations to the created table and to delete the
unwanted table from the database
Create
Alter
Drop
Truncate
Rename
Create
Syntax
Create table table_name (coulmn1 data type constraint,
column2 data type constraint,….);
Alter
The alter command are used to add, rename,drop and modify the
column of a table
Alter – ADD
Syntax
Alter –Rename
Syntax
Alter –Drop
Syntax
Alter –modify
Syntax
Drop
Syntax
Truncate
It is used to delete all the records from the table but it won’t
affect the table. The structure of the table will remain same in the
database
Syntax
Rename
Syntax
Functions
Types of functions
Number
Number again contains few functions
1 .Mod ()
It will return the remainder of given input
Syntax
Mod (source/input)
Ex:
Select mod (12,10) from dual;
2.abs() (absolute function)
It will convert negative to positive values
Syntax
abs (source/input)
Ex:
Select abs(-15) from dual;
3.Power()
4. Sqrt()
It will display the root values of the given input
Syntax
Sqrt(source/input)
Ex:
Select sqrt(16) from dual;
5. Floor()
It used to convert the decimal into integer i.e., from 0.1 to
0.9,it will display the least value as output
Syntax
Floor(source/input)
Ex:
Select floor(13.5) from dual;
6. Ceil()
It is used to convert decimal into integer but from 0.1 to 0.9 it
will display the highest value as the output.
Syntax:
Ceil(source/input)
Ex:
Select Ceil (13.5) from dual;
7. round()
Combination of both floor () and ceil() from 0.1 to o.4 it will
display the least value as output
From 0.5 to 0.9, it will display the highest value as output
Syntax:
Round(source/input)
Ex:
Select round(13.5) from dual;
Select round(13.2) from dual;
Char function:
1.Length()
Syntax:
Ex:
Select length (‘hiiiii’) from dual;
Question
3. upper()
It converts lower case to upper case
Syntax:
Upper (col _ name/ source)
Ex:
Select upper ( ‘hiiii’) from dual;
4. Lower ()
It converts upper case to lower case
Syntax:
Lower ( col _ name /source)
Ex:
Select Lower ( ‘SMITH’) from dual;
5. Substr()
It is used to fetch the part of the given string.
Syntax:
Substr (input, starting point)
Substr(input, starting point, length)
Ex:
Select substr( ‘Rahul’, 3) from dual;
Select Substr ( ‘Rahul’, 3,5) from dual;
6. Replace()
It is used to replace the given string with another new string
or we can replace a particular character with another new
character.
Syntax:
Replace (input, old char/ str, new char/ str)
Ex:
Select Replace ( ‘ java’, ‘j’, ‘m’) from dual;
7. Reverse ()
It display reversed string as output.
Syntax:
Reverse (source / input)
Ex:
Select reverse (‘java’) from dual;
8. Initcap()
It is used to display a string character of each word into upper
Syntax:
Initcap (source/input)
Ex:
Select initcap ( ‘developer’) from dual;
9. Instr ()
It display the occurrence position of a specified character in
the given string.
Syntax:
Instr ( input, char)
Ex:
Select instr( ‘developer’, ‘v’) from dual;
10.Ascii ()
It return the Ascii value of a specified character or string.
Syntax:
Ascii( source/input)
Ex:
Select ascii(“developer”) from dual;
Questions
1. Write a query to display the details of odd salaried from
the employee table
2. To display the details of even salaries
3. Display the details of employees whose name is consist of
exactly four characters
4. Display the details of employees whose name is consist of
exactly seven characters
5. Display first three character of employee name
6. Display last three character of employee designation
7. Write a query to fetch the details of employee whose job is
having “man” as first three character
8. Display the output of “development” from the input
“developer”
9. Display the last 5 character of department name in lower
case
Date function
1. Current_date
It displays the today date
Ex
Select current_date() from dual;
2. Sysdate()
It displays current system date with time
Ex
Select sysdate() from dual;
3. Month()
It displays today month
Ex:
Select month(“2023-08-08”) from dual;
Max()
Question
Min()
Questions
Sum()
It displays the sum of the given value
Questions
Average()
It will return the average value of the given input
Questions
1. Display the average salary of employee working in 10
Count()
Questions
Trim()
It is used to remove the starting and ending spaces of the
given input
EX:
Select trim(“ name “) from emp;
Sub Queries
Execution process
Order by
Syntax
Group by clause
Syntax
Select col1, col2, from employee group by col_name;
Questions
1. Display the highest salary in each designation
2. Write a query to fetch the highest salary in each department
3. Display the total salary given to each designation
4. Display the no. of employee working in each department
5. Display the no. of employee working in each department except
department 20
Having clause
Syntax
Select cn1,cn2……
from table_name
Where condition
Group by column_name
Having condition;
Question
1. Display the highest salary in each designation only if highest salary is >
2000
2. A query to fetch the salaries that are repeated
3. Display the count of employee in each department except department
20 and count should be less than 6
4. Display the average salary of each department only if the average salary
is > 3000
Commit
it is used to save the data permanently in the database
syntax
commit;
save point
it is used to store the data temporarily under a particular save
point
syntax
save point save point_name;
example
save point A;
insert into writer values (1, “raj”,22);
save point B
insert into writer values (3, “ram”, 22);
Rollback
It is used to restore the data upto last committed state . we can do
rollback only when the data is store permanently
Syntax
Rollback to save point save point_name;
Ex
Roll back to save point A;
Normalization
It is used to organize the data in the database
It is help to reduce the data redundancy
It is also used to eliminate insetion,updation and deletion
anomalous
Distinct
It is keyword which is used to display the unique value by
removing the duplicate from the column of the table
Syntax
Ex
Limit
Limit 1 offset 4;
Joins
Types of joins
1. Cross join
2. Inner join
3. Equi join
4. Self join
5. outer join
In cross join each value of the first column all the values of the second column
Cross join can display the output from multiple table without connections
Syntax
Where condition
Questions
Equi join
Equi join remove the ivalid combination of output which is
produced by cross join
It is same as cross join but the joining condition is specified
In case of equii we need to use (=) operator the main use
of equi join is to remove the invalid combination of data
Syntax
Select TN1.CN,TN2.CN,……
From TN1,TN2
Where condition and
Joining condition;
Questions
1. Display the employee name and department name of all
the employee
2. Display the employee name and department and annual
salary of employee smith who is working in department 20
3. A query to fetch employee name, half of their salary along
with their department information of all employees
4. A query to fetch employee details and location as who is
working as a manager
Inner join
It will fetch the matching rows from each table
Syntax
Select TN1.CN,TN2.CN,….
From TN1 inner join TN2
On condition and
Joining condition;
Questions
1. Display the details of employee along with their
department information
2. Display all the details employee along with their
department name, location who has hired in 18-feb-81
with salary range between 1500-3000
Self join
A table joining itself is known as self join
Syntax
Select aliasing TN1.CN,aliasing TN2.CN
From T1 aliasing name, t2 aliasing name
Where condition and
Joining condition
Question
1. Write a query to fetch name and salary of employee
whose salary is same as martin salary
2. Display the employee name, joining date along with
salary with 30% hike whose department is scott
department
3. Display the employee name, salary along with their
manger name along with their salary
4. Display the employee name, department name , salary
along with their manger name, department number,
salary
Outer join
It will fetch all the data of one table and only the matching
record of another table
It will fetch all the data from right side table and matching records from
left side table
Syntax
Select TN1.CN, TN2.CN
From TN1 right join TN2
On condition and
Joining condition
INDEX
Index is used to display the output in a faster way
Syntax:
Create index Index _name on table _ name (column1, column2);
Show index from table _ name;
Drop index index _ name on table _ name;
Ex:
Create index test on writer (name);
Select name from writer;
Drop index test on writer;
View
View is the virtual table, it is called as resultant set of store query.
View are mainly used to display only the necessary data to the user by
hiding unnecessary data to the user.
Syntax:
Create view view _name as
Select column1, column2,
From table _ name
Where condition;
Ex:
Create view dummy as
Select name from writer;
Drop view dummy;
Note:
After created view, if we update anything in the existing table, it will
reflect into view table
Advantages:
It provides security for the data
It increases the databases performance.
The DCL commands are used to deal with rights and permissions of the
DCL Commands
Grant
Revoke
1. Grant
It is used to give permission to the user
2. Revoke
It is used to get back the given permission from the user.
Syntax:
User list
Select user from my sql. user;
Current users
Select users;
Create new users
Create user ‘new-username’@ ‘local host’ identified by ‘password’;
Grant
Grant select , insert, …. ON database-name . table-name to ‘username’
@ ‘hostname’;
Grant all privileges on database-name * to ‘username’ @ ‘hostname’;
Revoke syntax:
Revoke select, insert, …. ON database -name. table -name to
‘username’ @ ‘hostname’;
Revoke all privileges on database-name * to ‘username’ @ ‘hostname’;
Ex:
Use scott _schema;
Select * from writer;
Select user from my sql . user;
Select user ();
Create user ‘raj’ @ ‘local host’ identified by ‘raj’;
Create user ‘raja’ @ ‘local host’ identified by ‘raja’;
Select user from my sql . user;
Grant select , insert on scott _ schema . wrier to ‘raj’@ ‘ local host’;
Select current _ user ();
Update writer set name = “ram” where id=1;
Select sql-safe-updates -0;
Show grants for ‘raj’ @ ‘local host’;
Revoke select , insert on scott _ schema . writer from ‘raj’ @ ‘local host’;
Drop user ‘raj’ @ ‘local host’ ;
Grant