SlideShare ist ein Scribd-Unternehmen logo
1 von 80
SQL Fundamentals
MR. ADITYA KUMAR TRIPATHY
SQL
What is Data?
 Any Useful information is a data.
 In simple words data can be facts related to any object in
consideration
 For example your name, age, height, weight, etc are some data related
to you. A picture , image , file , pdf etc can also be considered data
What is Database ?
A database is a systematic collection of data. Databases support storage
and manipulation of data. Databases make data management easy
Ex: An online telephone directory
electricity service provider
facebook.
What is a Database Management System (DBMS)?
Database Management System (DBMS) is a collection of programs which
enables its users to access database, manipulate data, reporting /
representation of data . It also helps to control access to the database
Database Management Systems are not a new concept and as such had been
first implemented in 1960s. Charles Bachmen's Integrated Data Store(IDS) is
said to be the first DBMS in history
Types of DBMS
 Hierarchical - this type of DBMS employs the "parent-child" relationship of
storing data.
The windows registry used in Windows OS is an example of a hierarchical
database.
 Network DBMS - this type of DBMS supports many-to many relations.
Ex: RDM Server
 Relational DBMS - this type of DBMS defines database relationships in
form of tables, also known as relations
Ex: MySQL, Oracle and Microsoft SQL Server
A cell is an intersection of a row and a column
A column is also called as a field / attribute
A record is also called as a row / tuple.
A table is also called as an entity / relation.
Object Oriented Relation DBMS - this type supports storage of new data types.
The data to be stored is in form of objects. The objects to be stored in the
database have attributes (i.e. gender, age) and methods that define what to do
with the data.
EX: PostgreSQL.
Note :-
If we install any of the database related software(s) – we can create our own
database, we can create our own tables and we can store the data inside it.
When we install any database s/w(s) – a part of hard disk will be designated /
reserved to perform database related activities
A database can also contain other database objects like views, indexes, stored
procedures, functions, triggers etc, apart from tables.
Some of the database software(s) we have are,
Oracle, SQL Server, DB2, Sybase, Informix, MySQL, MS – Access, Foxbase,
FoxPro
The s/w which is widely used today is Oracle. The different versions of Oracle
starting from the earliest to the latest are – Oracle 2, Oracle 3, Oracle 4,
Oracle 5, Oracle 6, Oracle 7, Oracle 8i, Oracle 9i, Oracle 10g,11g and the latest
to hit the market is Oracle 12c. here ‘i’ stands for Internet, ‘g’ stands for Grid /
Grid computing and C for Cloud Computing .
Client Server Architecture:
What is Relational Database?
 It is the collection of relations or two dimensional tables
 Dr E.F Codd proposed the relational model for database
system in 1969
Relational Model Consists of following
• Collections of Objects or Relations
• Set of Operators to act on the relations
• Data integrity for accuracy and consistency.
( Data integrity is the one which contains correct data in the
database)
• To restrict storing wrong data in database we use data integrity.
 To Preserve data integrity we have two types
1.DataType:
2.Constraints:
Data Type is a type of data which you store in each column
CONSTRAINTS
A constraint is a condition which restricts the invalid data in the table.
A constraint can be provided for a column of a table.
Types of Constraints
NOT NULL
UNIQUE
Primary Key
Foreign Key
Check
NULL
NULL is nothing, it is neither zero nor blank space
It will not occupy any space in the memory
Two NULLS are never same in Oracle.
NULL represents unknown value
Any arithmetic operation we perform on NULL will result in NULL itself. For ex,
100000 + NULL = NULL ; 100000 * NULL = NULL
NOT NULL
- NOT NULL will ensure atleast some value should be present in a
column
UNIQUE
It will not allow any duplicates in a column
UNIQUE column can take multiple NULL (s)
Primary Key
It is the combination of NOT NULL and UNIQUE
Only one PK is allowed in a table
PK identifies a record uniquely in a table
Creation of PK is not mandatory, but it is highly recommended to
create
Foreign Key
FK creates relationship between any two tables
FK is also called as referential integrity constraints
FK is created on the child table
FK can take both NULL and duplicate values
To create FK, the master table should have PK defined on the
common column of the master table
We can have more than 1 FK in a given table
CHECK
It is used to provide additional validations as per the customer
requirements.
Troubleshooting Oracle
Error 1
The account is locked
Steps to rectify the error
Login as username – ‘system’ & password – ‘manager’ or ‘password
– ‘tiger’
SQL > show user ;
User is “SYSTEM”
SQL > alter user scott account unlock ;
User altered
SQL > exit ;
Error 2
TNS : protocol adapter error
How to troubleshoot this
Cause is “oracle service has not started”
Sql is developed by IBM
SQL – Structured Query Language. The first name of sql is
SEQUEL(Simple or Structured english query language)
SQL – it is a language to talk to the database / to access the
database
To work on SQL , a DB software (RDBMS) is required.
SQL is not case sensitive
What is SQL?
Structured Query language (SQL) pronounced as "S-Q-L" or
sometimes as "See-Quel"is actually the standard language for
dealing with Relational Databases. SQL can be effectively used to
insert, search, update, delete database records.
1 Select Data retrieval language
2 Insert Data manipulation Language
Update
Delete
3 Create Data definition language
Alter
Drop
Rename
Truncate
4 Commit Transaction Control Language
Rollback
Save Point Data transaction Language
5 Grant, Revoke Data Control language
SELECT:
It is the statement used to read data from the table.
Capabilities of Select Statement
1. Projection:
2. Selection:
3. Join
Projection:
Syntax:
Select * | {[Distinct] Column| Expression [Aliase],…}
From table
Column Alias
Defining a Columns Alias
A Column Alias:
Rename a column heading
Is useful with calculation
Immediately follows the column name – there can also be the optional as keyword
between the column name and alias
Requires double quotation marks if it contains spaces or special characters or is case
sensitive.
Literal characters.
SQL> Select 'hello',ename from emp;
Literal Character String
A literal is a character, a number, or a date included in the select list
Date and character literals values must be enclosed within single quotation mark
Each character string is output once for each row returned.
|| is a concatenation operation used concatenate columns
SQL> Select ename||job||sal from emp;
Eliminating Duplicate Rows:
Eliminating duplicate rows by using the DISTINCT keyword in the select clause.
Q. Display department which has atleast 1 employee
Select DISTINCT deptno from emp;
Example Problems:
1. Select Salary increase of 300 for all the employees and display both old and new
salary.
2. Display ename, his monthly salary and his annual salary
3. Display employee name, monthly sal, and his annual salary with monthly bonus of
Rs 300
Assignments:
1. Display all rows and all columns of employee table
2. Display any 2 columns of employee table
4. Display the distinct salary of all the employee
5. Display the output of the following employee
“Hello smith your salary is 800”
6 is the following statement is correct.
Select ename,deptno from emp;
Select *,ename from emp;
Select ename deptno from emp;
1. Select *
From emp
/
2. List command is used to know the last execution command.
SQL> List Or SQL>l Or SQL>;
3.To set page size and line size in a single line.
SQL>Set lines 200 pages 100;
4. To execute the previously executed statement we use / (forward
slash)
SQL>/
5.To edit the previously executed statement we use edit
Sql>edit C:xyz.txt
6. To save the previously executed statement
SQL> Save C:xyz.txt
7. To save multiple statement in same file or to add statement to the
already saved file we use append.
SQL>Save C:xyz.txt append
9. To execute all the statement from file we use @
SQL>@ c:xyz.txt
10. To set the time we use
SQL> Set time on
11. Timing is used to display the execution time of the statement
SQL>Set timing on
12. To record the output that is taking place in sql plus we use ‘SPOOL’
SQL> Spool
13. To see all the parameters
SQL>Show all
14. To know about any command go to help
SQL>Help
SQL>? @
SL No. SQL Statement SQL*Plus
1 A Language An Environment
2 ANSI Standard Oracle Proprietary
3 Keywords Cannot be abbreviated Keywords can be
abbreviated
4 Statement manipulate data and table
definitions in the database
Commands do not allow
manipulation of values in
database
5 Runs on client and needs
to be install in each
machine
SQL* Plus/SQL Plus
Client tool to access the database
Installed along with database
Has specific set of commands
Interface user and data base
Difference between SQL Statement and SQL* Plus command
Operators are classified into,
Arithmetic Operators ( +, - , * , / )
Relational Operators ( > , < , >= , <= , = , < > or != - not equals to )
Logical Operators ( NOT, AND, OR )
Special Operators ( IN , LIKE , BETWEEN , IS )
Order Evaluated Operator
1 Arithmetic Operator
2 Concatenation
3 Comparison
4 Is, Like, In
5 Between
6 Not
7 AND
8 OR
Rules of Precedence:
SELECTION:
Limiting the Rows Selected
Select *|{[Distinct ] column|expression [aliase]…}
From table
Where condition(s)]
SQL> Select *
2 from emp
3 where ename='ALLEN';
where’ clause is used to restrict the number of records displayed. It gives only
the records of the specified condition.
Ex: Select *
From emp
Where job=‘MANAGER’
1. List all the employees in dept 20.
2. List the employee earning more than Rs 2500;
3. Display all the salesmen
IN: it is used for evaluating multiple values.
1. List the employees in department 10 and 20.
2. List all the clerks and analyst.
LIKE – used for pattern matching
% (percentage) - matches 0 or ‘n’ characters
_ (underscore) - matches exactly one character
1. List all the employee whose name starts with ‘S’
2. List all the employee whose name is having letter ‘L’ as Second character
3. List all the employees whose name is having at least 2 L’s in it
4) List the employees whose name is having letter ‘E’ as the last but one character
5) List all the employees whose name is having letter ‘R’ in the 3rd position
6) List all the employees who are having exactly 5 characters in their jobs
BETWEEN operator – used for searching based on range of values.
Ex – 1) List the employees whose salary is between 200 and 300
IS operator – it is used to compare nulls
Ex – 1) List all the employees whose commission is null
1) List all the employees who don’t have a reporting manager
2) List all the salesmen in dept 30
2) List all the salesmen in dept number 30 and having salary greater than 1500
3)List all the employees whose name starts with ‘s’ or ‘a’
4) List all the employees except those who are working in dept 10 & 20.
5) List the employees whose name does not start with ‘S’
6) List all the employees who are having reporting managers in dept 10
Assignments.
1) List the employees who are not working as managers and clerks in dept
10 and 20 with a salary in the range of 1000 to 3000
2) List the employees whose salary not in the range of 1000 to 2000 in dept
10,20,30 except all salesmen
3) List the department names which are having letter ‘O’ in their locations
as well as their department names
4) Display all the employees whose job has string ‘MAN’ in it.
SORTING
It arranges the data either in ascending / descending order
Ascending – ASC / Descending – DESC
We can sort the data using ORDER BY
By default, the data is always arranged in ASC order
NOTE :-
1.ORDER BY should be used always as the last statement in the SQL query.
2. You can sort by a column that is not in the select case.
3. Entire row will be ordered not only selected columns will be displayed in
order.
1)Arrange all the employees by their salary
2) Arrange all the employees by their salary in the descending order
3) Arrange ename, sal, job, empno and sort by descending order of salary
Function is a Reusable program that returns a value
There are 2 types of functions
1. Pre-defined or Built in functions.
2. User defined functions.
 These are used both in SQL and PL/SQL. PL – Procedural Language (it’s a extension to
SQL, can contain IF statements, loops, exceptions, OOPs, etc .. )
 Functions are very powerful features of sql and can be used to do the following
• Perform Calculation on data
• Modify individual data items
• Manipulate output for group of rows
In SQL functions are classified into
1. Single row function: Which returns one results per row.
2. Multiple row function: Returns one result per group
Single row functions
1. Character Functions:
Character functions are classified into case manipulation function
And character manipulation function
Case manipulation Functions:
1) Lower
2) Upper
3) INITCAP
Character Manipulation Functions:
1)CONCAT
2)SUBSTR
3)LENGTH
4)INSTR
5)REPLACE
Case manipulation Functions:
SQL> select upper('Qspiders'),lower('QSPiders'),initcap('qspiders') from dual;
UPPER('Q LOWER('Q INITCAP(
-------- -------- --------
QSPIDERS qspiders Qspiders
Dual – is a dummy table which is used for performing some independent operations
which will not depend on any of the existing tables.
SQL> select upper(ename),lower(ename),initcap(ename) from emp;
UPPER(ENAM LOWER(ENAM INITCAP(EN
---------- ---------- ----------
SMITH smith Smith
ALLEN allen Allen
Character Manipulation Functions:
Concat: It concatenates any two values or columns.
It is represented by ||
Ex:
SQL> select ename,job, concat(ename,job) from emp;
ENAME JOB CONCAT(ENAME,JOB)
---------- --------- -------------------
SMITH CLERK SMITHCLERK
ALLEN SALESMAN ALLENSALESMAN
1. Write a sql statement to display ‘SMITH is a clerk’
Note: Exactly 2 arguments can be given to concat function.
The Substring function in SQL is used to return a portion of string
Syntax:
SUBSTR (str, position, [length])
where position and length are both integers. This syntax means the following: Start with
the position-th character in string str, select the next length characters.
1. Display 1st and last character of all the employees.
Length: Length is used to find the length of the given string.
Syntax: Length(Str)
EX: Select Length(‘Qspiders’) from dual;
1. Display all the employees whose name has exactly 6 character.
INSTR: Find the staring location of the nth occurrence of pattern
beginning in the starting position-th position in string str.
INSTR (str, pattern, [starting position, [nth location]])
Ex: Instr(‘Qspiders’, ‘s’ , ‘1’ , ‘1’) from dual;
1. Display all the employees whose name start with ‘S’
Replace:
The Replace function in SQL is used to update the content of a
string. The syntax of the Replace function is:
Replace (str1, str2, str3)
In str1, find where str2 occurs, and replace it with str3.
Ex:
SQL> Select Replace('qspiders','s','*') from dual;
Trim: Is used to remove the spaces present in the given string.
Ltrim(Str): LTRIM Removes all white spaces from the beginning
of the string.
Rtrim(Str):RTRIM Removes all white spaces at the end of the
string.
1. Write a sql statement to display the number of spaces
present in the given string
2. NUMBER FUNCTIONS:
Round: Round the Value to specified decimal
Ex: Round(23.34) 23
Trunc: Truncate the values to specified decimal.
Ex: Trunc(34.6554) --- 34
Mod: Returns Reminder of division.
Ex: Mod(10,3) 1
Ex:
SQL> SELECT * FROM EMP WHERE MOD(SAL,2)=1;
1. Display all the employees whose job has string ‘MAN’
2. Display all the employees whose name has ‘L’ as third
character.
3. Display the result in the following format, first
character in lower case rest in uppercase.
4. Display all the employees which has at lest 2L’s in it.
5. Display the number of occurrence of substring in a
string.
Display the number of L’s in each name
6. Display all the employees whose name is palindrome
Working with Dates:
 Oracle database stores dates in an internal numeric format:
Century, Year, Month, day, hours, minutes, Seconds.
 The default date display format is DD-MM-YY
Ex: Select ename, hiredate from emp
• Sysdate: It is a function that returns date
• Systimestamp: It is a function that returns date, time including milliseconds and time
zone
Arithmetic With dates:
• Add or subtract a number to or from a date for a resultant date value
• Subtract two dates to find the number of days between those date.
Ex : To get future or past date
Select sysdate+100 , sysdate-70 from dual;
Ex: Experience with years;
Select ename,hiredate, round((sysdate-hiredate)/360) from emp;
Group Functions operate on sets of rows to give one row result
per group.
We have 5 GROUP functions,
Sum
Max
Min
Avg
Count
Sum – returns total value
Max – returns maximum value
Min – returns minimum value
Avg – returns average value
Count – returns number of records
Ex – 1) display the maximum salary, minimum salary and
total salary from employee
2)Write a query to display total number of employees
3. Display the number of employee who has commission
4) List the number of employees in department 30
5) Display the total salary in department 30
6) List the number of clerks in department 20
7) List the highest and lowest salary earned by salesmen
GROUPING
It is the process of computing the aggregates by segregating based on one or more
columns.
Grouping is done by using ‘group by’ clause.
Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
For ex – 1) Display the total salary of all departments
2) Display the maximum of each job
HAVING
‘Having’ is used to filter the grouped data.
‘Where’ is used to filter the non grouped data.
‘Having’ should be used after group by clause
‘Where’ should be used before group by clause
1) Display job-wise highest salary only if the highest salary is more than Rs1500
2) Display job-wise highest salary only if the highest salary is more than 1500 excluding
department 30. Sort the data based on highest salary in the ascending order.
RESTRICTIONS ON GROUPING
Note 1- we can select only the columns that are part of ‘group by’ statement
If we try selecting other columns, we will get an error
Note 2:Whatever is there in the select statement must be there in the group by
statement. But, whatever is there in the group by statement need not be present in the
select statement. This is shown in the above two corrected queries.
1) Display the department numbers along with the number of employees in it
2) Display the department numbers which are having more than 4 employees in them
3) Display the maximum salary for each of the job excluding all the employees whose
name ends with ‘S’
4) Display the department numbers which are having more than 9000 as their
departmental total salary
SUB - QUERIES
A sub-query is also called as a nested query.
Syntax of a sub-query
OUTER QUERY
Select …
From …
Where … ( select …
From …
Where …
)
INNER QUERY
Here, the inner query will be executed first.
The output of inner query is passed as input to the outer query.
To write a sub-query, atleast 1 common column should be existing between the tables.
1) List the employees who has salary greater than Allen
2) List the employees working in ‘Research’ department.
3) List the department names that are having analysts
4) List the employees in Research and Sales department
5) List the department names which are having salesmen in it.
6) Display the employees whose location is having at least one ‘O’ in it.
7) List the department names that are having at least 1 employee in it.
8) List the department names that are having at least 4 employees in it
9) Display the department names which are having at least 2clerks in it
10) List the department names that are having no employees at all
11) Display all the employees whose job is same as scott
12) Display scott manager’s manager’s department name
13) List employees whose job is same as scott and their salary greater than smith’s
salary
14) Display all the employees whose job is same as scott and allen
15) Display all the employees who are actual managers
16) Display who are all the employees reporting to scott
17) Display all the employees who are not manager
1. Display the 2nd maximum salary
2. Display the 3rd maximum salary
3. Display all the employees who are earning more than all the managers.
4. Display all the employees who are earning more than any of the manager
5. Select empno, job and salary of all the analyst who are earning MORE THAN any
of the manager
6. Select the department name and location of all the employees working for clerk.
7. Select all the employees working for dallas
8. Display all the employees whose salary is greater than avg sal of department 20
Joins are used when we need to fetch the data from multiple tables
Types of JOIN(s)
Cartesian Join (product)
Inner (Equi) Join
Outer Join - Left Outer Join, Right Outer Join, Full Outer Join
Self Join
CARTESIAN JOIN
- It is based on Cartesian product theory.
Display employee name along with the department name
INNER JOIN
Inner join are also called as equijoins.
They return the matching records between the tables.
In the real time scenarios, this is the most frequently used Join.
Display employee name along with the department name
Note:JOIN condition is mandatory for removing the Cartesian output.
ANSI style JOINS
This was introduced from Oracle 9i.
It is another way of writing inner joins with a few modifications.
,(comma) has been replaced by the word ‘join’
where’ has been replaced with ‘on’
OUTER JOIN
It returns both matching and non-matching records
Outer join = inner join + non-matching records
Non-matching records means data present in one table, but absent in another table
w.r.to common columns.
For ex, 40 is there in deptno of dept table, but not there in deptno of emp table.
1) Display employee name and his department name for the employees whose name
starts with ‘S’
2) Display employee name and his department name who is earning 1st maximum
salary
3) Display ename and grade in 1 and 2
4) Write a query to display number of employees in each department.
SELF JOIN
Joining a table to itself is called self join
1) Display employee name along with their manager name
2) Display the employees who are getting the same salary
Equijoin:
1. Display all the managers and clerks who work in accounts and
marketing departments.
2. Display all the salesman who are not located at DALLAS
3. Select all the employees who work in DALLAS
OUTER JOIN
1. Get matching as well as non matching records from both the
table
SELF JOIN:
1. Get all the employees who work in the same department as of scott
SELECT A.ENAME,B.ENAME
FROM EMP A, EMP B
WHERE A.DEPTNO=B.DEPTNO
AND A.ENAME='SCOTT‘
1. List all the employees earning more than there manager
SELECT A.ENAME,A.SAL,B.ENAME,B.SAL
FROM EMP A,EMP B
WHERE A.MGR=B.EMPNO
AND A.SAL>B.SAL
1. Fetch all the employees who are earning same salary
1. Select all the employees who are earning same as ‘SMITH’
SELECT A.ENAME,A.SAL,B.ENAME,B.SAL
FROM EMP A, EMP B
WHERE A.SAL=B.SAL
AND A.EMPNO<>B.EMPNO
AND A.ENAME='SMITH'
Co – related Queries :
They are special type of sub – queries
Here, both outer & inner queries are inter-dependent
For each & every record of outer query, the entire inner query will be executed
They work on the principles of both sub – queries & JOIN(s).
For ex, Display the employee who is earning the highest salary
SQL> select * from emp A
2 where 0=(Select count(distinct(sal)) from emp B where A.Sal<B.Sal);
1) Display the least salary from the employee table.
2) Display top 3 person’s salaries from the employee table.
3) Write a query to display bottom 3 salaries
4) Display 1st and 4th maximum salary
5) Display 1st, 4th & 6th highest salaries in a single query
DDL – Data Definition Language
the various commands in DDL are :- Create, Drop, Truncate, Alter, Rename
CREATE – It creates the table.
Before we study the Create command, let us first study the some of the basic
datatypes we use in SQL.
1) CHAR :-
It stores the fixed length character data.
It can store the alphanumeric data (i.e, numbers and characters).
2) VARCHAR
It stores the variable length character data
It can store alphanumeric data.
Another difference is : -
In char, maximum value we can store is 2000 characters
In varchar, maximum value we can store is 4000 characters.
3) NUMBER
- it stores numeric data.
For ex – 1) sal number(4) ;
Here the maximum possible value is 9999.
2) sal number (6, 2) ;
Here, 2 – scale (total number of decimal places)
6 – precision (total number of digits including decimal places)
Maximum value is 9999.99
sal number (4, 3) ;
maximum value is 9.999
sal number (2, 2)
maximum value is .99
4) DATE
- it stores date and time
- no need to specify any length for this type.
Date is always displayed in the default format :- dd – month – yy
5) BLOB
Stands for – Binary Large Object
It stores binary data (images, movies, music files) within the database. It stores upto
4GB.
6) CLOB
Stands for – Character Large Object
It stores plain character data like varchar field upto 4GB.
NOTE :-
varchar2 – from 10g, varchar & varchar2 are the same.
Earlier, varchar was supporting upto 2000 characters and varchar2 was supporting
upto 4000 characters.
Create the following tables
PRODUCTS
ProdID ( PK )
ProdName ( Not Null )
Qty ( Chk > 0 )
Description
ORDERS
ProdID ( FK from products )
OrderID ( PK )
Qty_sold ( chk > 0 )
Price
Order_Date
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
create table Products
(
prodid number(4) Primary key,
prodname varchar(10) Not null,
qty number(3) check (qty>0),
description Varchar(20)
)
Create table Orders
(
prodid number(4) references Products(prodid),
orderid number(4) Primary key,
qty_sold number(3) check (qty_sold>0),
price Number(8,2),
Order_dt date
)
The new table orders has been created. We can see from the above query how to
reference a child table to the parent table using the references keyword.
Creating a table from another table :-
Now, we will see how to create a table from another table – i.e, it duplicates all the
records and the characterstics of another table.
The SQL query for it is as follows,
SQL> create table test3 as
2 select * from dept;
Thus we can see that we have created another table temp from the table dept.
Thus, we can see that the table temp has copied the structure of the table dept. Here,
we must observe that temp copies all the columns, rows and NOT NULL constraints only
from the table dept. It never copies PK, FK, Check constraints.
Thus, when in the interview somebody asks you “I have a table which has about
1million records. How do I duplicate it into another table without using Insert keyword
and without inserting it individually all the records into the duplicated table ?
Answer is - Use the above query of creating a table from another table and explain it.
TRUNCATE
It removes all the data permanently, but the structure of the table remains as it is.
Ex – SQL > TRUNCATE TABLE test ;
DROP
It removes both data and the structure of the table permanently from the database.
Ex – SQL > DROP TABLE test ;
The functionality of Recycle Bin was introduced in Oracle 10G version only. Thus even
though the table has been dropped, we can still restore it using flashback command
or we can permanently remove it using the purge command.
This concept of Recycle bin was not there in the earlier versions of Oracle.
Recovering Drop Tables (Undo Drop Table)
To recover this dropped table a user can type the command
SQL> Flashback table tablename to before drop;
You can also restore the dropped table by giving it a different name like this
SQL> Flashback table emp to before drop rename to emp2;
Permanently deleting table after drop
Purge table tableName
Permanently Dropping Tables
If you want to permanently drop tables without putting it into Recycle Bin drop tables with
purge command like this
SQL> drop table tablename purge;
This will drop the table permanently and it cannot be restored.
Rename Table:
It renames a table.
Syntax:
Rename table_name to new_table_name
ALTER
- this query alters / changes the structure of the table (i.e, - adding columns,
removing columns, renaming columns etc ).
1. Rename table name
alter table
table_name
rename to
new_table_name;
2. ) Let us add a new column ‘model_no’ to the table.
Alter table table_Name
add Column_Name [Constraints]
3.Now let us drop the column model_no from products.
Alter table table_Name
Drop column Column_Name
3) Let us rename the column qty to qty_available.
Alter table table_Name
rename column Column_Name to New_Column_Name
Assignments
1) Create the following tables
a) Table name :- STUDENTS
regno (PK)
name (NN)
semester
DOB
Phone
b) Table name :- BOOKS
bookno (PK)
bname
author
c) Table name :- LIBRARY
regno (FK from students)
bookno (FK from books)
DOI –date of issue
DOR – date of return
INSERT - insert data into a table
 UPDATE - updates existing data within a table
DELETE - deletes all records from a table.
INSERT:
Insert into table_Name
Values(v1,v2,v2…)
Or
Insert into table_Name (column1,column2,…)
Values (v1,v1,….)
Note:
This is how we insert values into a table. All characters and alpha-numeric
characters(ex – 10023sdf78) must be enclosed in single quotes (‘ ‘ ) and each value
must be separated by comma. Also we must be careful in entering the data without
violating the primary key, foreign key , unique constraints.
During an abnormal exit – i.e, shutdown or if the SQL window is closed by
mouse click – then all the DML’s will be rolled back automatically.
During a normal exit – exit ; - all the DML’s will be auto-committed – and there
will be no rollback.
Delete and Truncate
a) Delete – deletes whichever records we want to delete from the table
Truncate – deletes all the records whether we want it or not
b) Delete – can be undone
Truncate – cannot be undone.
UPDATE :-
It updates one or more records.
Update Table_Name Set Expression…..
For ex – 1) Let us update salary by increasing it by Rs200 and also give commission of
Rs100 where empno = 7369.
2) Increase all salary by 10%
DELETE
It deletes one / some / all the records.
Ex: Delete from table
TCL (Transaction Control Language)
Any DML change on a table is not a permanent one.
We need to save the DML changes in order to make it permanent
We can also undo (ignore) the same DML changes on a table.
The DDL changes cannot be undone as they are implicitly saved.
ROLLBACK
It undoes the DML changes performed on a table.
Let us see in the below example how rollback works,
COMMIT
It saves the DML changes permanently to the database.
Committing after rollback & vice versa will not have any effect
Data transaction Language(DTL)
SavePoint
Rollback to savepoint
Data Control language(DCL)
Grant:
grant select on emp to hr;
Login as HR
Execute the Bellow query
select * from scott.emp;
Revoke:
Login as Scott
revoke select on emp from hr;
Login as HR
Difference Between Oracle and SQL Server
SL No Oracle SQL Server
1 Oracle Server is developed by oracle SQL Server is developed by
Microsoft
2 It is available in multiple OS’s It is available under only
windows
3 Null != Null Null=Null
NORMALIZATION:
Normalization is a database design technique which organizes tables in a manner
that reduces redundancy and dependency of data.
It divides larger tables to smaller tables and link them using relationships.
The inventor of the relational model Edgar Codd proposed the theory of
normalization with the introduction of FirstNormal Form and he continued to
extend theory with Second and Third Normal Form. Later he joined with
Raymond F. Boyce to develop the theory of Boyce-Codd Normal Form
Let's learn Normalization with practical example –
Assume a video library maintains a database of movies rented out. Without any
normalization all information is stored in one table as shown below.
1NF Rules
Each table cell should contain single value.
Each record needs to be unique.
2NF Rules
Rule 1- Be in 1NF
Rule 2- Single Column Primary Key
It is clear that we can't move forward to make our simple database in 2nd Normalization form
unless we partition the table above
We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains
member information. Table 2 contains information on movies rented.
3NF Rules
Rule 1- Be in 2NF
Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF we again need to need divide our table.
Conversion Functions:
Conversion function s are used to convert one data type into another data type
There are two type of conversion Functions
1. Implicit conversion Function
Ex: Select 10+’20’ from dual;
2. Explicit conversion function
Ex: Select 10+Ascii(‘A’) from dual;
TO_DATE: Is used to convert into date data type
TO_CHAR: Is used to convert into character data type
TO_NUMBER: is used to convert into number data type
Using TO_CHAR function with dates
TO_CHAR(date, ‘Format model’)
The format model:
• It must enclosed with single quotation mark and is case sensitive
• Is separated from the date value of a comma
Element of date format:
YYYY Full year in number
YEAR year spelled out
MM Two digit value for month
MONTH Full name of month
MON Three letter abbreviation of month
DY Three letter abbreviation of day
DAY Full name of day
DD Numeric day of month
Ex: select sysdate,to_char(sysdate,'yyyy year mm month mon dy day dd') from dual
/
NVL Functions:
1> NVL(arg1,arg2)
• If agr1 is null it returns arg2
• If arg1 is not null then it returns itself
Converts a null to actual values:
Data types that can be used are date, character and numbers
Ex:
1.select ename,sal,comm,nvl(comm,0) from emp
2. SQL> select ename,sal,comm,sal+comm, sal+nvl(comm,0) totalsalary from emp;
Accessing tables of other users
Provided that a user has the privilege to access tables of other users
also she/he can refer to these tables in her/his queries. Let <user> be
a user in the Oracle system and <table> a table of this user. This table
can be accessed by other (privileged) users using the
command
select from <user>.<table>;
In case that one often refers to tables of other users, it is useful to
use a synonym instead of <user>.<table>.
In Oracle-SQL a synonym can be created using the command
create synonym <name> for <user>.<table> ;
It is then possible to use simply <name> in a from clause.
Synonyms can also be created for one's own tables.
Modifying Table- and Column Definitions
It is possible to modify the structure of a table (the relation schema) even if rows have
already
been inserted into this table. A column can be added using the alter table command
alter table <table> add(<column> <data type> [default <value>] [<column
constraint>]);
If more than only one column should be added at one time, respective add clauses need to
be
separated by colons. A table constraint can be added to a table using
alter table <table> add (<table constraint>);
The syntax of the command for modifying a column is
alter table <table> modify(<column>
[<data type>] [default <value>] [<column constraint>]);
Views
In Oracle the SQL command to create a view (virtual table) has the form
create [or replace] view <view-name> [(<column(s)>)] as
<select-statement> [with check option [constraint <name>]];
The optional clause or replace re-creates the view if it already exists. <column(s)>
names
the columns of the view. If <column(s)> is not specified in the view definition, the
columns of
the view get the same names as the attributes listed in the select statement (if
possible).
Example: The following view contains the name, job title and the annual salary of
employees working in the department 20:
create view DEPT20 as
select ENAME, JOB, SAL12 ANNUAL SALARY from EMP
where DEPTNO = 20;
(or)
create view DEPT20 (ENAME, JOB, ANNUAL SALARY)
as
select ENAME, JOB, SAL 12 from EMP
where DEPTNO = 20;
RESUME:
 Good understanding of RDBMS concepts like constraints, Normalization, Tables
etc.
 Excellent knowledge of writing SQL queries.
 Good understanding of SQL concepts like Grouping, Sub queries, Functions etc.
 Solid understand of SQL Joins (Inner joins, Left join and Right joins and full Joins).
 Good knowledge of DDL, DML and TCL.

Weitere ähnliche Inhalte

Was ist angesagt? (20)

SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
SQL commands
SQL commandsSQL commands
SQL commands
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
SQL
SQLSQL
SQL
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Sql Basics | Edureka
Sql Basics | EdurekaSql Basics | Edureka
Sql Basics | Edureka
 
Mysql
MysqlMysql
Mysql
 
Sql operators & functions 3
Sql operators & functions 3Sql operators & functions 3
Sql operators & functions 3
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
All data models in dbms
All data models in dbmsAll data models in dbms
All data models in dbms
 

Ähnlich wie SQL Fundamentals for Database Beginners

Ähnlich wie SQL Fundamentals for Database Beginners (20)

Module02
Module02Module02
Module02
 
Lecture on DBMS & MySQL.pdf v. C. .
Lecture on DBMS & MySQL.pdf v.  C.     .Lecture on DBMS & MySQL.pdf v.  C.     .
Lecture on DBMS & MySQL.pdf v. C. .
 
Introduction to sql server
Introduction to sql serverIntroduction to sql server
Introduction to sql server
 
lovely
lovelylovely
lovely
 
ORACLE PL SQL
ORACLE PL SQLORACLE PL SQL
ORACLE PL SQL
 
Oracle notes
Oracle notesOracle notes
Oracle notes
 
Bank mangement system
Bank mangement systemBank mangement system
Bank mangement system
 
Dbms important questions and answers
Dbms important questions and answersDbms important questions and answers
Dbms important questions and answers
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developer
 
Introduction to dbms
Introduction to dbmsIntroduction to dbms
Introduction to dbms
 
12 SQL
12 SQL12 SQL
12 SQL
 
12 SQL
12 SQL12 SQL
12 SQL
 
DBMS Part-3.pptx
DBMS Part-3.pptxDBMS Part-3.pptx
DBMS Part-3.pptx
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
 
Database Management Lab -SQL Queries
Database Management Lab -SQL Queries Database Management Lab -SQL Queries
Database Management Lab -SQL Queries
 
Sql introduction
Sql introductionSql introduction
Sql introduction
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
T-SQL Overview
T-SQL OverviewT-SQL Overview
T-SQL Overview
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
SQL_NOTES.pdf
SQL_NOTES.pdfSQL_NOTES.pdf
SQL_NOTES.pdf
 

Mehr von Aditya Kumar Tripathy

Remote control using 4 channel Relay
Remote control using 4 channel RelayRemote control using 4 channel Relay
Remote control using 4 channel RelayAditya Kumar Tripathy
 
Protection of Converter Dense Power Systems
Protection of Converter Dense Power Systems Protection of Converter Dense Power Systems
Protection of Converter Dense Power Systems Aditya Kumar Tripathy
 
SUPERCONDUCTING MAGNETIC ENERGY STORAGE SYSTEM (SMES)
SUPERCONDUCTING  MAGNETIC ENERGY  STORAGE  SYSTEM  (SMES)SUPERCONDUCTING  MAGNETIC ENERGY  STORAGE  SYSTEM  (SMES)
SUPERCONDUCTING MAGNETIC ENERGY STORAGE SYSTEM (SMES)Aditya Kumar Tripathy
 
Design and Implementation of a Robotic Vehicle With Real-Time Video Feedback ...
Design and Implementation of a Robotic Vehicle With Real-Time Video Feedback ...Design and Implementation of a Robotic Vehicle With Real-Time Video Feedback ...
Design and Implementation of a Robotic Vehicle With Real-Time Video Feedback ...Aditya Kumar Tripathy
 

Mehr von Aditya Kumar Tripathy (7)

Remote control using 4 channel Relay
Remote control using 4 channel RelayRemote control using 4 channel Relay
Remote control using 4 channel Relay
 
Voice controlled Robot
Voice controlled RobotVoice controlled Robot
Voice controlled Robot
 
Protection of Converter Dense Power Systems
Protection of Converter Dense Power Systems Protection of Converter Dense Power Systems
Protection of Converter Dense Power Systems
 
SUPERCONDUCTING MAGNETIC ENERGY STORAGE SYSTEM (SMES)
SUPERCONDUCTING  MAGNETIC ENERGY  STORAGE  SYSTEM  (SMES)SUPERCONDUCTING  MAGNETIC ENERGY  STORAGE  SYSTEM  (SMES)
SUPERCONDUCTING MAGNETIC ENERGY STORAGE SYSTEM (SMES)
 
Design and Implementation of a Robotic Vehicle With Real-Time Video Feedback ...
Design and Implementation of a Robotic Vehicle With Real-Time Video Feedback ...Design and Implementation of a Robotic Vehicle With Real-Time Video Feedback ...
Design and Implementation of a Robotic Vehicle With Real-Time Video Feedback ...
 
Cell phone jammer
Cell phone jammerCell phone jammer
Cell phone jammer
 
Plasma antenna
Plasma antennaPlasma antenna
Plasma antenna
 

Kürzlich hochgeladen

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Kürzlich hochgeladen (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

SQL Fundamentals for Database Beginners

  • 2. SQL What is Data?  Any Useful information is a data.  In simple words data can be facts related to any object in consideration  For example your name, age, height, weight, etc are some data related to you. A picture , image , file , pdf etc can also be considered data What is Database ? A database is a systematic collection of data. Databases support storage and manipulation of data. Databases make data management easy Ex: An online telephone directory electricity service provider facebook. What is a Database Management System (DBMS)? Database Management System (DBMS) is a collection of programs which enables its users to access database, manipulate data, reporting / representation of data . It also helps to control access to the database
  • 3. Database Management Systems are not a new concept and as such had been first implemented in 1960s. Charles Bachmen's Integrated Data Store(IDS) is said to be the first DBMS in history Types of DBMS  Hierarchical - this type of DBMS employs the "parent-child" relationship of storing data. The windows registry used in Windows OS is an example of a hierarchical database.  Network DBMS - this type of DBMS supports many-to many relations. Ex: RDM Server  Relational DBMS - this type of DBMS defines database relationships in form of tables, also known as relations Ex: MySQL, Oracle and Microsoft SQL Server A cell is an intersection of a row and a column A column is also called as a field / attribute A record is also called as a row / tuple. A table is also called as an entity / relation.
  • 4. Object Oriented Relation DBMS - this type supports storage of new data types. The data to be stored is in form of objects. The objects to be stored in the database have attributes (i.e. gender, age) and methods that define what to do with the data. EX: PostgreSQL. Note :- If we install any of the database related software(s) – we can create our own database, we can create our own tables and we can store the data inside it. When we install any database s/w(s) – a part of hard disk will be designated / reserved to perform database related activities A database can also contain other database objects like views, indexes, stored procedures, functions, triggers etc, apart from tables. Some of the database software(s) we have are, Oracle, SQL Server, DB2, Sybase, Informix, MySQL, MS – Access, Foxbase, FoxPro
  • 5. The s/w which is widely used today is Oracle. The different versions of Oracle starting from the earliest to the latest are – Oracle 2, Oracle 3, Oracle 4, Oracle 5, Oracle 6, Oracle 7, Oracle 8i, Oracle 9i, Oracle 10g,11g and the latest to hit the market is Oracle 12c. here ‘i’ stands for Internet, ‘g’ stands for Grid / Grid computing and C for Cloud Computing . Client Server Architecture:
  • 6. What is Relational Database?  It is the collection of relations or two dimensional tables  Dr E.F Codd proposed the relational model for database system in 1969 Relational Model Consists of following • Collections of Objects or Relations • Set of Operators to act on the relations • Data integrity for accuracy and consistency. ( Data integrity is the one which contains correct data in the database) • To restrict storing wrong data in database we use data integrity.  To Preserve data integrity we have two types 1.DataType: 2.Constraints: Data Type is a type of data which you store in each column
  • 7. CONSTRAINTS A constraint is a condition which restricts the invalid data in the table. A constraint can be provided for a column of a table. Types of Constraints NOT NULL UNIQUE Primary Key Foreign Key Check NULL NULL is nothing, it is neither zero nor blank space It will not occupy any space in the memory Two NULLS are never same in Oracle. NULL represents unknown value Any arithmetic operation we perform on NULL will result in NULL itself. For ex, 100000 + NULL = NULL ; 100000 * NULL = NULL
  • 8. NOT NULL - NOT NULL will ensure atleast some value should be present in a column UNIQUE It will not allow any duplicates in a column UNIQUE column can take multiple NULL (s) Primary Key It is the combination of NOT NULL and UNIQUE Only one PK is allowed in a table PK identifies a record uniquely in a table Creation of PK is not mandatory, but it is highly recommended to create
  • 9. Foreign Key FK creates relationship between any two tables FK is also called as referential integrity constraints FK is created on the child table FK can take both NULL and duplicate values To create FK, the master table should have PK defined on the common column of the master table We can have more than 1 FK in a given table CHECK It is used to provide additional validations as per the customer requirements.
  • 10. Troubleshooting Oracle Error 1 The account is locked Steps to rectify the error Login as username – ‘system’ & password – ‘manager’ or ‘password – ‘tiger’ SQL > show user ; User is “SYSTEM” SQL > alter user scott account unlock ; User altered SQL > exit ; Error 2 TNS : protocol adapter error How to troubleshoot this Cause is “oracle service has not started”
  • 11. Sql is developed by IBM SQL – Structured Query Language. The first name of sql is SEQUEL(Simple or Structured english query language) SQL – it is a language to talk to the database / to access the database To work on SQL , a DB software (RDBMS) is required. SQL is not case sensitive What is SQL? Structured Query language (SQL) pronounced as "S-Q-L" or sometimes as "See-Quel"is actually the standard language for dealing with Relational Databases. SQL can be effectively used to insert, search, update, delete database records.
  • 12. 1 Select Data retrieval language 2 Insert Data manipulation Language Update Delete 3 Create Data definition language Alter Drop Rename Truncate 4 Commit Transaction Control Language Rollback Save Point Data transaction Language 5 Grant, Revoke Data Control language
  • 13. SELECT: It is the statement used to read data from the table. Capabilities of Select Statement 1. Projection: 2. Selection: 3. Join Projection: Syntax: Select * | {[Distinct] Column| Expression [Aliase],…} From table
  • 14. Column Alias Defining a Columns Alias A Column Alias: Rename a column heading Is useful with calculation Immediately follows the column name – there can also be the optional as keyword between the column name and alias Requires double quotation marks if it contains spaces or special characters or is case sensitive. Literal characters. SQL> Select 'hello',ename from emp; Literal Character String A literal is a character, a number, or a date included in the select list Date and character literals values must be enclosed within single quotation mark Each character string is output once for each row returned.
  • 15. || is a concatenation operation used concatenate columns SQL> Select ename||job||sal from emp; Eliminating Duplicate Rows: Eliminating duplicate rows by using the DISTINCT keyword in the select clause. Q. Display department which has atleast 1 employee Select DISTINCT deptno from emp; Example Problems: 1. Select Salary increase of 300 for all the employees and display both old and new salary. 2. Display ename, his monthly salary and his annual salary 3. Display employee name, monthly sal, and his annual salary with monthly bonus of Rs 300
  • 16. Assignments: 1. Display all rows and all columns of employee table 2. Display any 2 columns of employee table 4. Display the distinct salary of all the employee 5. Display the output of the following employee “Hello smith your salary is 800” 6 is the following statement is correct. Select ename,deptno from emp; Select *,ename from emp; Select ename deptno from emp;
  • 17. 1. Select * From emp / 2. List command is used to know the last execution command. SQL> List Or SQL>l Or SQL>; 3.To set page size and line size in a single line. SQL>Set lines 200 pages 100; 4. To execute the previously executed statement we use / (forward slash) SQL>/ 5.To edit the previously executed statement we use edit Sql>edit C:xyz.txt 6. To save the previously executed statement SQL> Save C:xyz.txt 7. To save multiple statement in same file or to add statement to the already saved file we use append. SQL>Save C:xyz.txt append
  • 18. 9. To execute all the statement from file we use @ SQL>@ c:xyz.txt 10. To set the time we use SQL> Set time on 11. Timing is used to display the execution time of the statement SQL>Set timing on 12. To record the output that is taking place in sql plus we use ‘SPOOL’ SQL> Spool 13. To see all the parameters SQL>Show all 14. To know about any command go to help SQL>Help SQL>? @
  • 19. SL No. SQL Statement SQL*Plus 1 A Language An Environment 2 ANSI Standard Oracle Proprietary 3 Keywords Cannot be abbreviated Keywords can be abbreviated 4 Statement manipulate data and table definitions in the database Commands do not allow manipulation of values in database 5 Runs on client and needs to be install in each machine SQL* Plus/SQL Plus Client tool to access the database Installed along with database Has specific set of commands Interface user and data base Difference between SQL Statement and SQL* Plus command
  • 20. Operators are classified into, Arithmetic Operators ( +, - , * , / ) Relational Operators ( > , < , >= , <= , = , < > or != - not equals to ) Logical Operators ( NOT, AND, OR ) Special Operators ( IN , LIKE , BETWEEN , IS ) Order Evaluated Operator 1 Arithmetic Operator 2 Concatenation 3 Comparison 4 Is, Like, In 5 Between 6 Not 7 AND 8 OR Rules of Precedence:
  • 21. SELECTION: Limiting the Rows Selected Select *|{[Distinct ] column|expression [aliase]…} From table Where condition(s)] SQL> Select * 2 from emp 3 where ename='ALLEN'; where’ clause is used to restrict the number of records displayed. It gives only the records of the specified condition. Ex: Select * From emp Where job=‘MANAGER’
  • 22. 1. List all the employees in dept 20. 2. List the employee earning more than Rs 2500; 3. Display all the salesmen IN: it is used for evaluating multiple values. 1. List the employees in department 10 and 20. 2. List all the clerks and analyst. LIKE – used for pattern matching % (percentage) - matches 0 or ‘n’ characters _ (underscore) - matches exactly one character 1. List all the employee whose name starts with ‘S’ 2. List all the employee whose name is having letter ‘L’ as Second character 3. List all the employees whose name is having at least 2 L’s in it 4) List the employees whose name is having letter ‘E’ as the last but one character 5) List all the employees whose name is having letter ‘R’ in the 3rd position 6) List all the employees who are having exactly 5 characters in their jobs
  • 23. BETWEEN operator – used for searching based on range of values. Ex – 1) List the employees whose salary is between 200 and 300 IS operator – it is used to compare nulls Ex – 1) List all the employees whose commission is null 1) List all the employees who don’t have a reporting manager 2) List all the salesmen in dept 30 2) List all the salesmen in dept number 30 and having salary greater than 1500 3)List all the employees whose name starts with ‘s’ or ‘a’ 4) List all the employees except those who are working in dept 10 & 20. 5) List the employees whose name does not start with ‘S’ 6) List all the employees who are having reporting managers in dept 10
  • 24. Assignments. 1) List the employees who are not working as managers and clerks in dept 10 and 20 with a salary in the range of 1000 to 3000 2) List the employees whose salary not in the range of 1000 to 2000 in dept 10,20,30 except all salesmen 3) List the department names which are having letter ‘O’ in their locations as well as their department names 4) Display all the employees whose job has string ‘MAN’ in it.
  • 25. SORTING It arranges the data either in ascending / descending order Ascending – ASC / Descending – DESC We can sort the data using ORDER BY By default, the data is always arranged in ASC order NOTE :- 1.ORDER BY should be used always as the last statement in the SQL query. 2. You can sort by a column that is not in the select case. 3. Entire row will be ordered not only selected columns will be displayed in order. 1)Arrange all the employees by their salary 2) Arrange all the employees by their salary in the descending order 3) Arrange ename, sal, job, empno and sort by descending order of salary
  • 26. Function is a Reusable program that returns a value There are 2 types of functions 1. Pre-defined or Built in functions. 2. User defined functions.  These are used both in SQL and PL/SQL. PL – Procedural Language (it’s a extension to SQL, can contain IF statements, loops, exceptions, OOPs, etc .. )  Functions are very powerful features of sql and can be used to do the following • Perform Calculation on data • Modify individual data items • Manipulate output for group of rows
  • 27. In SQL functions are classified into 1. Single row function: Which returns one results per row. 2. Multiple row function: Returns one result per group Single row functions 1. Character Functions: Character functions are classified into case manipulation function And character manipulation function Case manipulation Functions: 1) Lower 2) Upper 3) INITCAP Character Manipulation Functions: 1)CONCAT 2)SUBSTR 3)LENGTH 4)INSTR 5)REPLACE
  • 28. Case manipulation Functions: SQL> select upper('Qspiders'),lower('QSPiders'),initcap('qspiders') from dual; UPPER('Q LOWER('Q INITCAP( -------- -------- -------- QSPIDERS qspiders Qspiders Dual – is a dummy table which is used for performing some independent operations which will not depend on any of the existing tables. SQL> select upper(ename),lower(ename),initcap(ename) from emp; UPPER(ENAM LOWER(ENAM INITCAP(EN ---------- ---------- ---------- SMITH smith Smith ALLEN allen Allen
  • 29. Character Manipulation Functions: Concat: It concatenates any two values or columns. It is represented by || Ex: SQL> select ename,job, concat(ename,job) from emp; ENAME JOB CONCAT(ENAME,JOB) ---------- --------- ------------------- SMITH CLERK SMITHCLERK ALLEN SALESMAN ALLENSALESMAN 1. Write a sql statement to display ‘SMITH is a clerk’ Note: Exactly 2 arguments can be given to concat function.
  • 30. The Substring function in SQL is used to return a portion of string Syntax: SUBSTR (str, position, [length]) where position and length are both integers. This syntax means the following: Start with the position-th character in string str, select the next length characters. 1. Display 1st and last character of all the employees.
  • 31. Length: Length is used to find the length of the given string. Syntax: Length(Str) EX: Select Length(‘Qspiders’) from dual; 1. Display all the employees whose name has exactly 6 character. INSTR: Find the staring location of the nth occurrence of pattern beginning in the starting position-th position in string str. INSTR (str, pattern, [starting position, [nth location]]) Ex: Instr(‘Qspiders’, ‘s’ , ‘1’ , ‘1’) from dual; 1. Display all the employees whose name start with ‘S’
  • 32. Replace: The Replace function in SQL is used to update the content of a string. The syntax of the Replace function is: Replace (str1, str2, str3) In str1, find where str2 occurs, and replace it with str3. Ex: SQL> Select Replace('qspiders','s','*') from dual; Trim: Is used to remove the spaces present in the given string. Ltrim(Str): LTRIM Removes all white spaces from the beginning of the string. Rtrim(Str):RTRIM Removes all white spaces at the end of the string. 1. Write a sql statement to display the number of spaces present in the given string
  • 33. 2. NUMBER FUNCTIONS: Round: Round the Value to specified decimal Ex: Round(23.34) 23 Trunc: Truncate the values to specified decimal. Ex: Trunc(34.6554) --- 34 Mod: Returns Reminder of division. Ex: Mod(10,3) 1 Ex: SQL> SELECT * FROM EMP WHERE MOD(SAL,2)=1;
  • 34. 1. Display all the employees whose job has string ‘MAN’ 2. Display all the employees whose name has ‘L’ as third character. 3. Display the result in the following format, first character in lower case rest in uppercase. 4. Display all the employees which has at lest 2L’s in it. 5. Display the number of occurrence of substring in a string. Display the number of L’s in each name 6. Display all the employees whose name is palindrome
  • 35. Working with Dates:  Oracle database stores dates in an internal numeric format: Century, Year, Month, day, hours, minutes, Seconds.  The default date display format is DD-MM-YY Ex: Select ename, hiredate from emp • Sysdate: It is a function that returns date • Systimestamp: It is a function that returns date, time including milliseconds and time zone Arithmetic With dates: • Add or subtract a number to or from a date for a resultant date value • Subtract two dates to find the number of days between those date. Ex : To get future or past date Select sysdate+100 , sysdate-70 from dual; Ex: Experience with years; Select ename,hiredate, round((sysdate-hiredate)/360) from emp;
  • 36. Group Functions operate on sets of rows to give one row result per group. We have 5 GROUP functions, Sum Max Min Avg Count Sum – returns total value Max – returns maximum value Min – returns minimum value Avg – returns average value Count – returns number of records
  • 37. Ex – 1) display the maximum salary, minimum salary and total salary from employee 2)Write a query to display total number of employees 3. Display the number of employee who has commission 4) List the number of employees in department 30 5) Display the total salary in department 30 6) List the number of clerks in department 20 7) List the highest and lowest salary earned by salesmen
  • 38. GROUPING It is the process of computing the aggregates by segregating based on one or more columns. Grouping is done by using ‘group by’ clause. Syntax: SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name; For ex – 1) Display the total salary of all departments 2) Display the maximum of each job HAVING ‘Having’ is used to filter the grouped data. ‘Where’ is used to filter the non grouped data. ‘Having’ should be used after group by clause ‘Where’ should be used before group by clause 1) Display job-wise highest salary only if the highest salary is more than Rs1500
  • 39. 2) Display job-wise highest salary only if the highest salary is more than 1500 excluding department 30. Sort the data based on highest salary in the ascending order. RESTRICTIONS ON GROUPING Note 1- we can select only the columns that are part of ‘group by’ statement If we try selecting other columns, we will get an error Note 2:Whatever is there in the select statement must be there in the group by statement. But, whatever is there in the group by statement need not be present in the select statement. This is shown in the above two corrected queries. 1) Display the department numbers along with the number of employees in it 2) Display the department numbers which are having more than 4 employees in them 3) Display the maximum salary for each of the job excluding all the employees whose name ends with ‘S’ 4) Display the department numbers which are having more than 9000 as their departmental total salary
  • 40. SUB - QUERIES A sub-query is also called as a nested query. Syntax of a sub-query OUTER QUERY Select … From … Where … ( select … From … Where … ) INNER QUERY Here, the inner query will be executed first. The output of inner query is passed as input to the outer query. To write a sub-query, atleast 1 common column should be existing between the tables.
  • 41. 1) List the employees who has salary greater than Allen 2) List the employees working in ‘Research’ department. 3) List the department names that are having analysts 4) List the employees in Research and Sales department 5) List the department names which are having salesmen in it. 6) Display the employees whose location is having at least one ‘O’ in it. 7) List the department names that are having at least 1 employee in it. 8) List the department names that are having at least 4 employees in it 9) Display the department names which are having at least 2clerks in it 10) List the department names that are having no employees at all 11) Display all the employees whose job is same as scott 12) Display scott manager’s manager’s department name 13) List employees whose job is same as scott and their salary greater than smith’s salary 14) Display all the employees whose job is same as scott and allen 15) Display all the employees who are actual managers 16) Display who are all the employees reporting to scott 17) Display all the employees who are not manager
  • 42. 1. Display the 2nd maximum salary 2. Display the 3rd maximum salary 3. Display all the employees who are earning more than all the managers. 4. Display all the employees who are earning more than any of the manager 5. Select empno, job and salary of all the analyst who are earning MORE THAN any of the manager 6. Select the department name and location of all the employees working for clerk. 7. Select all the employees working for dallas 8. Display all the employees whose salary is greater than avg sal of department 20
  • 43. Joins are used when we need to fetch the data from multiple tables Types of JOIN(s) Cartesian Join (product) Inner (Equi) Join Outer Join - Left Outer Join, Right Outer Join, Full Outer Join Self Join CARTESIAN JOIN - It is based on Cartesian product theory. Display employee name along with the department name INNER JOIN Inner join are also called as equijoins. They return the matching records between the tables. In the real time scenarios, this is the most frequently used Join. Display employee name along with the department name Note:JOIN condition is mandatory for removing the Cartesian output.
  • 44. ANSI style JOINS This was introduced from Oracle 9i. It is another way of writing inner joins with a few modifications. ,(comma) has been replaced by the word ‘join’ where’ has been replaced with ‘on’ OUTER JOIN It returns both matching and non-matching records Outer join = inner join + non-matching records Non-matching records means data present in one table, but absent in another table w.r.to common columns. For ex, 40 is there in deptno of dept table, but not there in deptno of emp table.
  • 45. 1) Display employee name and his department name for the employees whose name starts with ‘S’ 2) Display employee name and his department name who is earning 1st maximum salary 3) Display ename and grade in 1 and 2 4) Write a query to display number of employees in each department. SELF JOIN Joining a table to itself is called self join 1) Display employee name along with their manager name 2) Display the employees who are getting the same salary
  • 46. Equijoin: 1. Display all the managers and clerks who work in accounts and marketing departments. 2. Display all the salesman who are not located at DALLAS 3. Select all the employees who work in DALLAS OUTER JOIN 1. Get matching as well as non matching records from both the table
  • 47. SELF JOIN: 1. Get all the employees who work in the same department as of scott SELECT A.ENAME,B.ENAME FROM EMP A, EMP B WHERE A.DEPTNO=B.DEPTNO AND A.ENAME='SCOTT‘ 1. List all the employees earning more than there manager SELECT A.ENAME,A.SAL,B.ENAME,B.SAL FROM EMP A,EMP B WHERE A.MGR=B.EMPNO AND A.SAL>B.SAL 1. Fetch all the employees who are earning same salary 1. Select all the employees who are earning same as ‘SMITH’ SELECT A.ENAME,A.SAL,B.ENAME,B.SAL FROM EMP A, EMP B WHERE A.SAL=B.SAL AND A.EMPNO<>B.EMPNO AND A.ENAME='SMITH'
  • 48. Co – related Queries : They are special type of sub – queries Here, both outer & inner queries are inter-dependent For each & every record of outer query, the entire inner query will be executed They work on the principles of both sub – queries & JOIN(s). For ex, Display the employee who is earning the highest salary SQL> select * from emp A 2 where 0=(Select count(distinct(sal)) from emp B where A.Sal<B.Sal);
  • 49. 1) Display the least salary from the employee table. 2) Display top 3 person’s salaries from the employee table. 3) Write a query to display bottom 3 salaries 4) Display 1st and 4th maximum salary 5) Display 1st, 4th & 6th highest salaries in a single query
  • 50. DDL – Data Definition Language the various commands in DDL are :- Create, Drop, Truncate, Alter, Rename CREATE – It creates the table. Before we study the Create command, let us first study the some of the basic datatypes we use in SQL. 1) CHAR :- It stores the fixed length character data. It can store the alphanumeric data (i.e, numbers and characters). 2) VARCHAR It stores the variable length character data It can store alphanumeric data. Another difference is : - In char, maximum value we can store is 2000 characters In varchar, maximum value we can store is 4000 characters.
  • 51. 3) NUMBER - it stores numeric data. For ex – 1) sal number(4) ; Here the maximum possible value is 9999. 2) sal number (6, 2) ; Here, 2 – scale (total number of decimal places) 6 – precision (total number of digits including decimal places) Maximum value is 9999.99 sal number (4, 3) ; maximum value is 9.999 sal number (2, 2) maximum value is .99 4) DATE - it stores date and time - no need to specify any length for this type. Date is always displayed in the default format :- dd – month – yy
  • 52. 5) BLOB Stands for – Binary Large Object It stores binary data (images, movies, music files) within the database. It stores upto 4GB. 6) CLOB Stands for – Character Large Object It stores plain character data like varchar field upto 4GB. NOTE :- varchar2 – from 10g, varchar & varchar2 are the same. Earlier, varchar was supporting upto 2000 characters and varchar2 was supporting upto 4000 characters.
  • 53. Create the following tables PRODUCTS ProdID ( PK ) ProdName ( Not Null ) Qty ( Chk > 0 ) Description ORDERS ProdID ( FK from products ) OrderID ( PK ) Qty_sold ( chk > 0 ) Price Order_Date
  • 54. CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, PRIMARY KEY( one or more columns ) );
  • 55. create table Products ( prodid number(4) Primary key, prodname varchar(10) Not null, qty number(3) check (qty>0), description Varchar(20) ) Create table Orders ( prodid number(4) references Products(prodid), orderid number(4) Primary key, qty_sold number(3) check (qty_sold>0), price Number(8,2), Order_dt date ) The new table orders has been created. We can see from the above query how to reference a child table to the parent table using the references keyword.
  • 56. Creating a table from another table :- Now, we will see how to create a table from another table – i.e, it duplicates all the records and the characterstics of another table. The SQL query for it is as follows, SQL> create table test3 as 2 select * from dept; Thus we can see that we have created another table temp from the table dept. Thus, we can see that the table temp has copied the structure of the table dept. Here, we must observe that temp copies all the columns, rows and NOT NULL constraints only from the table dept. It never copies PK, FK, Check constraints. Thus, when in the interview somebody asks you “I have a table which has about 1million records. How do I duplicate it into another table without using Insert keyword and without inserting it individually all the records into the duplicated table ? Answer is - Use the above query of creating a table from another table and explain it.
  • 57. TRUNCATE It removes all the data permanently, but the structure of the table remains as it is. Ex – SQL > TRUNCATE TABLE test ; DROP It removes both data and the structure of the table permanently from the database. Ex – SQL > DROP TABLE test ; The functionality of Recycle Bin was introduced in Oracle 10G version only. Thus even though the table has been dropped, we can still restore it using flashback command or we can permanently remove it using the purge command. This concept of Recycle bin was not there in the earlier versions of Oracle. Recovering Drop Tables (Undo Drop Table) To recover this dropped table a user can type the command SQL> Flashback table tablename to before drop; You can also restore the dropped table by giving it a different name like this SQL> Flashback table emp to before drop rename to emp2;
  • 58. Permanently deleting table after drop Purge table tableName Permanently Dropping Tables If you want to permanently drop tables without putting it into Recycle Bin drop tables with purge command like this SQL> drop table tablename purge; This will drop the table permanently and it cannot be restored. Rename Table: It renames a table. Syntax: Rename table_name to new_table_name
  • 59. ALTER - this query alters / changes the structure of the table (i.e, - adding columns, removing columns, renaming columns etc ). 1. Rename table name alter table table_name rename to new_table_name; 2. ) Let us add a new column ‘model_no’ to the table. Alter table table_Name add Column_Name [Constraints] 3.Now let us drop the column model_no from products. Alter table table_Name Drop column Column_Name 3) Let us rename the column qty to qty_available. Alter table table_Name rename column Column_Name to New_Column_Name
  • 60. Assignments 1) Create the following tables a) Table name :- STUDENTS regno (PK) name (NN) semester DOB Phone b) Table name :- BOOKS bookno (PK) bname author c) Table name :- LIBRARY regno (FK from students) bookno (FK from books) DOI –date of issue DOR – date of return
  • 61. INSERT - insert data into a table  UPDATE - updates existing data within a table DELETE - deletes all records from a table. INSERT: Insert into table_Name Values(v1,v2,v2…) Or Insert into table_Name (column1,column2,…) Values (v1,v1,….) Note: This is how we insert values into a table. All characters and alpha-numeric characters(ex – 10023sdf78) must be enclosed in single quotes (‘ ‘ ) and each value must be separated by comma. Also we must be careful in entering the data without violating the primary key, foreign key , unique constraints.
  • 62. During an abnormal exit – i.e, shutdown or if the SQL window is closed by mouse click – then all the DML’s will be rolled back automatically. During a normal exit – exit ; - all the DML’s will be auto-committed – and there will be no rollback. Delete and Truncate a) Delete – deletes whichever records we want to delete from the table Truncate – deletes all the records whether we want it or not b) Delete – can be undone Truncate – cannot be undone.
  • 63. UPDATE :- It updates one or more records. Update Table_Name Set Expression….. For ex – 1) Let us update salary by increasing it by Rs200 and also give commission of Rs100 where empno = 7369. 2) Increase all salary by 10% DELETE It deletes one / some / all the records. Ex: Delete from table
  • 64. TCL (Transaction Control Language) Any DML change on a table is not a permanent one. We need to save the DML changes in order to make it permanent We can also undo (ignore) the same DML changes on a table. The DDL changes cannot be undone as they are implicitly saved. ROLLBACK It undoes the DML changes performed on a table. Let us see in the below example how rollback works, COMMIT It saves the DML changes permanently to the database. Committing after rollback & vice versa will not have any effect
  • 65. Data transaction Language(DTL) SavePoint Rollback to savepoint Data Control language(DCL) Grant: grant select on emp to hr; Login as HR Execute the Bellow query select * from scott.emp; Revoke: Login as Scott revoke select on emp from hr; Login as HR
  • 66. Difference Between Oracle and SQL Server SL No Oracle SQL Server 1 Oracle Server is developed by oracle SQL Server is developed by Microsoft 2 It is available in multiple OS’s It is available under only windows 3 Null != Null Null=Null
  • 67. NORMALIZATION: Normalization is a database design technique which organizes tables in a manner that reduces redundancy and dependency of data. It divides larger tables to smaller tables and link them using relationships. The inventor of the relational model Edgar Codd proposed the theory of normalization with the introduction of FirstNormal Form and he continued to extend theory with Second and Third Normal Form. Later he joined with Raymond F. Boyce to develop the theory of Boyce-Codd Normal Form Let's learn Normalization with practical example – Assume a video library maintains a database of movies rented out. Without any normalization all information is stored in one table as shown below.
  • 68. 1NF Rules Each table cell should contain single value. Each record needs to be unique.
  • 69. 2NF Rules Rule 1- Be in 1NF Rule 2- Single Column Primary Key It is clear that we can't move forward to make our simple database in 2nd Normalization form unless we partition the table above We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains member information. Table 2 contains information on movies rented.
  • 70. 3NF Rules Rule 1- Be in 2NF Rule 2- Has no transitive functional dependencies To move our 2NF table into 3NF we again need to need divide our table.
  • 71.
  • 72. Conversion Functions: Conversion function s are used to convert one data type into another data type There are two type of conversion Functions 1. Implicit conversion Function Ex: Select 10+’20’ from dual; 2. Explicit conversion function Ex: Select 10+Ascii(‘A’) from dual; TO_DATE: Is used to convert into date data type TO_CHAR: Is used to convert into character data type TO_NUMBER: is used to convert into number data type
  • 73. Using TO_CHAR function with dates TO_CHAR(date, ‘Format model’) The format model: • It must enclosed with single quotation mark and is case sensitive • Is separated from the date value of a comma Element of date format: YYYY Full year in number YEAR year spelled out MM Two digit value for month MONTH Full name of month MON Three letter abbreviation of month DY Three letter abbreviation of day DAY Full name of day DD Numeric day of month
  • 74. Ex: select sysdate,to_char(sysdate,'yyyy year mm month mon dy day dd') from dual / NVL Functions: 1> NVL(arg1,arg2) • If agr1 is null it returns arg2 • If arg1 is not null then it returns itself Converts a null to actual values: Data types that can be used are date, character and numbers Ex: 1.select ename,sal,comm,nvl(comm,0) from emp 2. SQL> select ename,sal,comm,sal+comm, sal+nvl(comm,0) totalsalary from emp;
  • 75. Accessing tables of other users Provided that a user has the privilege to access tables of other users also she/he can refer to these tables in her/his queries. Let <user> be a user in the Oracle system and <table> a table of this user. This table can be accessed by other (privileged) users using the command select from <user>.<table>; In case that one often refers to tables of other users, it is useful to use a synonym instead of <user>.<table>. In Oracle-SQL a synonym can be created using the command create synonym <name> for <user>.<table> ; It is then possible to use simply <name> in a from clause. Synonyms can also be created for one's own tables.
  • 76. Modifying Table- and Column Definitions It is possible to modify the structure of a table (the relation schema) even if rows have already been inserted into this table. A column can be added using the alter table command alter table <table> add(<column> <data type> [default <value>] [<column constraint>]); If more than only one column should be added at one time, respective add clauses need to be separated by colons. A table constraint can be added to a table using alter table <table> add (<table constraint>);
  • 77. The syntax of the command for modifying a column is alter table <table> modify(<column> [<data type>] [default <value>] [<column constraint>]);
  • 78. Views In Oracle the SQL command to create a view (virtual table) has the form create [or replace] view <view-name> [(<column(s)>)] as <select-statement> [with check option [constraint <name>]]; The optional clause or replace re-creates the view if it already exists. <column(s)> names the columns of the view. If <column(s)> is not specified in the view definition, the columns of the view get the same names as the attributes listed in the select statement (if possible).
  • 79. Example: The following view contains the name, job title and the annual salary of employees working in the department 20: create view DEPT20 as select ENAME, JOB, SAL12 ANNUAL SALARY from EMP where DEPTNO = 20; (or) create view DEPT20 (ENAME, JOB, ANNUAL SALARY) as select ENAME, JOB, SAL 12 from EMP where DEPTNO = 20;
  • 80. RESUME:  Good understanding of RDBMS concepts like constraints, Normalization, Tables etc.  Excellent knowledge of writing SQL queries.  Good understanding of SQL concepts like Grouping, Sub queries, Functions etc.  Solid understand of SQL Joins (Inner joins, Left join and Right joins and full Joins).  Good knowledge of DDL, DML and TCL.