Database Basics for Beginners
Database Basics for Beginners
me/campusdrive
CHAPTER 1
RDBMS Concepts
Database
A database is the place of storage of the data in the form of tables
Data means information which is very useful. A database is also collection of 1 or more tables.
CELL
CELL
Columns
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.
Among the above database software – some of them are DBMS and some of them are RDBMS
                                                                                                  1|Page
                      Telegram - https://t.me/campusdrive
                       Telegram - https://t.me/campusdrive
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,
and the latest to hit the market is Oracle 11g. here ‘i’ stands for Internet and ‘g’ stands for Grid / Grid
computing.
RELATIONSHIPS
A relationship is the association between any two tables which preserves data integrity.
Relationships
                                                                 Emp
               Dept No.      Dept Name             Emp No.                   Dept No.     Salary
                                                                 Name
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.
                                                                                                      2|Page
                       Telegram - https://t.me/campusdrive
                       Telegram - https://t.me/campusdrive
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.
Ex -     1) sal > 0
         2) empnum should start with 1
         3) commission should be between 1000 & 5000
                                                                                          3|Page
                       Telegram - https://t.me/campusdrive
                    Telegram - https://t.me/campusdrive
                                                                    Check
                                                                    (sal >
                                                                      0)
PK NN PK NN FK NN Unique Unique
RELATIONSHIP NULL
                                                                                 4|Page
                    Telegram - https://t.me/campusdrive
                        Telegram - https://t.me/campusdrive
CHAPTER 2
Username - Scott
Password – Tiger
Troubleshooting Oracle
Error 1
The account is locked
Error 2
TNS : protocol adapter error
How to go here,
Settings – Control Panel – Administrative Tools – Services
Sort the list
There is an “Oracle Service ORCL” & “start the service”
                                                                                  5|Page
                        Telegram - https://t.me/campusdrive
                       Telegram - https://t.me/campusdrive
                                                                        6|Page
                       Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
The above query gives the description of the “employee” table. But we see that all the data is in different
lines which makes it very difficult to analyse.
So we use the following command to see the data in a more orderly fashion,
The “set linesize” command helps in increasing the line size , thus the data is arranged in a orderly
fashion.
                                                                                                 7|Page
                      Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
The above command “set pagesize 20” increases the page size, thus accommodating more number of
rows in a single page.
The above query gives the value of only these 3 columns from the table “employee”.
                                                                                        8|Page
                     Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
‘where’ clause is used to restrict the number of records displayed. It gives only the records of the
specified condition.
Any string data should be enclosed within single quotes ( ‘ ‘ ) and the same becomes case sensitive.
Assignment
1) List the employees in dept 20
                                                                                                  9|Page
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
CHAPTER 3
OPERATORS
SPECIAL OPERATORS
                                                                                10 | P a g e
                      Telegram - https://t.me/campusdrive
                       Telegram - https://t.me/campusdrive
2) List the employees whose name is having letter ‘L’ as 2nd character
                                                                                11 | P a g e
                       Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
ASSIGNMENT
1) List the employees whose name is having atleast 2 L’s
2) List the employees whose name is having letter ‘E’ as the last but one character
3) List all the employees whose name is having letter ‘R’ in the 3rd position
4) List all the employees who are having exactly 5 characters in their jobs
                                                                                      12 | P a g e
                     Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
ASSIGNMENT
1) List all the employees who don’t have a reporting manager
LOGICAL OPERATORS
2) List all the salesmen in dept number 30 and having salary greater than 1500
                                                                                 14 | P a g e
                      Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
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’
                                                                          15 | P a g e
                     Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
6) List all the employees who are having reporting managers in dept 10
ASSIGNMENT
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
                                                                                             16 | P a g e
                     Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
3) List the department names which are having letter ‘O’ in their locations as well as their department
names
SORTING
It arranges the data either in ascending / descending order
Ascending – ASC / Descending – DESC
We can sort the data using ORDER BY
                                                                                            17 | P a g e
                     Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
3) Arrange ename, sal, job, empno and sort by descending order of salary
                                                                           18 | P a g e
                     Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
In the above query we have – order by 2 – thus it arranges only the 2nd column ‘salary’ in the descending
order.
Thus to arrange the specific columns in order – we must have to specify the column number.
NOTE :- ORDER BY should be used always as the last statement in the SQL query.
The above query arranges all the distinct values of department number.
                                                                                             19 | P a g e
                     Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
CHAPTER 4
Ex – 1) display the maximum salary, minimum salary and total salary from employee
                                                                                    20 | P a g e
                      Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
4) The below query gives the number of employees who have commission
ASSIGMENT
1) Display the total salary in department 30
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.
                                                                                             22 | P a g e
                     Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
HAVING
‘Having’ is used to filter the grouped data.
‘Where’ is used to filter the non grouped data.
For ex – 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
- we can select only the columns that are part of ‘group by’ statement
If we try selecting other columns, we will get an error as shown below,
The above query is an error because ‘job’ is there in the select query but not in the group by query.
                                                                                               23 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
If it is enclosed in any of the group functions like sum(sal) etc – then it is not an error. But whatever
table is included in the select query must also be included in the group by query.
The above problem can be overcome with the following query as shown below,
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.
ASSIGNMENT
1) Display the department numbers along with the number of employees in it
                                                                                             24 | P a g e
                      Telegram - https://t.me/campusdrive
                    Telegram - https://t.me/campusdrive
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
                                                                                       25 | P a g e
                    Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
  NOTE :
  To clear the screen, the command used is,
  cl scr ;
  if it is a large query and we cannot type it repeatedly, then type in – SQL > ed ;
  when we type ed ; - we get the notepad – after making the necessary changes – then click on the ‘x’
  i.e, the close button at the top right corner – then click on yes when a dialog box asking whether to
  overwrite the file comes – after this it comes to the oracle screen – in the next line , enter ‘/ ‘ and hit
  on enter button – another way of ending the query is by typing ‘ / ‘ in the next line of the query – this
  indicates the end of the query.
CHAPTER 5
STATEMENTS
Statements – they help us to create the table and insert the data.
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).
                                                                                                   26 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
2) VARCHAR
It stores the variable length character data
It can store alphanumeric data.
Blank Space
T O M - - -
When we declare anything of type char, the memory is allocated as of the size given and its fixed length
– hence it cannot be altered.
Now, when we give tom, it allocates 6 bytes for name char – only the 1st 3bytes are used to store Tom –
the rest becomes waste as it is a blank space and it is reserved memory.
The length(name) = 6.
Null
T O M . . .
                                                                                             27 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
                                            Re-usable memory
When we declare anything of type varchar, the memory is allocated as shown above and it is variable
length
When we give tom, it allocates 6bytes for name varchar – only the 1st 3bytes are used to store tom – the
remaining 3 fields becomes null. As we know the property of null – null does not occupy any memory
space – thus the memory is not wasted here.
The length(name) = 3.
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.
    NOTE :-
    varchar2 – from 10g, varchar & varchar2 are the same.
    Earlier, varchar was supporting upto 2000 characters and varchar2 was supporting upto
    4000 characters.
5) BLOB
Stands for – Binary Large Object
It stores binary data (images, movies, music files) within the database. It stores upto 4GB.
6) CLOB
                                                                                               28 | P a g e
                      Telegram - https://t.me/campusdrive
                       Telegram - https://t.me/campusdrive
Stands for – Character Large Object
It stores plain character data like varchar field upto 4GB.
               PRODUCTS
             ProdID ( PK )
         ProdName ( Not Null )
             Qty ( Chk > 0 )
              Description
                ORDERS
      ProdID ( FK from products )
             OrderID ( PK )
          Qty_sold ( chk > 0 )
                  Price
              Order_Date
                                                                                                 29 | P a g e
                       Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
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.
Thus we can verify that orders table has ben created and added to the database.
                                                                                          30 | P a g e
                     Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
Thus, we get the description of the orders table.
Thus we can see that we have created another table temp from the table dept.
We can verify it as shown below,
Thus, we can see that the table temp has been created.
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.
                                                                                           31 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
Thus, from the above query – we can see that all the records of the table dept has been copied into the
table temp.
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 ;
Let us understand the difference between drop & truncate using the below shown example,
                                                                                           32 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
The above shows the description of the table test1.
Now, let us use the Truncate query on Test1 and Drop query on Test2 and see the difference.
The above 3 queries show that – 1st query has the table test1 truncated.
2nd query – it shows no rows selected – thus only the records from the table has been removed. 3rd query
– it shows that the structure of the table is still present. Only the records will be removed.
Thus, this explains the truncate query.
                                                                                            33 | P a g e
                      Telegram - https://t.me/campusdrive
                    Telegram - https://t.me/campusdrive
Thus from the above queries we can explain how drop works. 1st query – it drops the table. Thus – the
entire structure and records of the table are dropped.
2nd and 3rd query – since, there is no table – select & desc query for test2 will throw an error.
Thus, this explains the drop query.
Hence, we have seen the difference between drop & truncate query.
TABLE
DROP
PURGE
PERMANENTLY REMOVE
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.
RENAME
                                                                                           34 | P a g e
                    Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
It renames a table.
For ex, let us see the query of how we do this renaming a table.
In the above 3queries – we have created a table temp which copies table dept – we see the records of the
table temp – and also check if the table has really been created.
                                                                                            35 | P a g e
                      Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
Thus the table has been renamed and its contents are verified.
ALTER
- this query alters / changes the structure of the table (i.e, - adding columns, removing columns,
renaming columns etc ).
Now let us alter the table products (which we have created earlier).
1) Let us add a new column ‘model_no’ to the table.
Thus, a new column has been added. Lets verify it with the query shown below,
                                                                                       36 | P a g e
                     Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
2) Now let us drop the column model_no from products.
Thus, we can see from the description of the table – the column model_no has been dropped.
NOTE : SELECT is neither DML nor DDL. It does not belong to any group because it does not alter
anything, it just displays the data as required by the user.
                                                                                             37 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
DML
INSERT
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.
Now let us see the table in which the data in has been inserted,
Now, let us insert data into the table orders in which a foreign key is referencing primary key,
Here, we see that 1001 is the same prodid as of the earlier table. Sysdate – it displays the current date set
in the system .
                                                                                                 38 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
UPDATE :-
For ex – 1) Let us update salary by increasing it by Rs200 and also give commission of Rs100 where
empno = 7369.
                                                                                       39 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
                                                            40 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
DELETE
                                                                                            41 | P a g e
                      Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
TCL
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.
ROLLBACK
Let us delete the employee table. When we perform select operation on emp, we can see that all the rows
have been deleted.
We now perform the rollback operation,
                                                                                           42 | P a g e
                     Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
Thus performing the rollback operation, we can retrieve all the records which had been deleted.
COMMIT
Committing after rollback & vice versa will not have any effect
Let us explain the above statement with an example,
                                                                                            43 | P a g e
                     Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
Thus, from above – we can see that rollback has no effect after commit operation.
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.
                                                                                         44 | P a g e
                     Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
During a normal exit – exit ; - all the DML’s will be auto-committed – and there will be no rollback.
Ex – 1) INSERT
        UPDATE
        ALTER
        DELETE
        ROLLBACK
When we perform the following operations in the same order for a table – then INSERT, UPDATE will
be committed – because ALTER is a DDL – and thus all the DML’s above it will also be committed –
because DDL operations cannot be undone.
Here – only DELETE will be rolled back because it’s a DML.
       2) INSERT
           UPDATE
           DELETE
           ROLLBACK
Here, all are rolled back.
SAVEPOINT :
Save point x ;
Update …
Delete ..
Rollback to x ;
…
…
Assignments
1) Create the following tables
                                                                                               45 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
regno (PK)
name (NN)
semester
DOB
Phone
3) Differentiate between,
a) Delete and Truncate
b) Truncate and Drop
c) Char and Varchar
d) Drop and Delete
NOTE – The Primary Key created using more than 1 column is called as composite primary key.
Ex – alter table lib
     Add primary key (regno, bookno, DOI) ;
CHAPTER 6
SUB - QUERIES
                                                                                        46 | P a g e
                      Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
Syntax of a sub-query
                      Select …
                      From …
                      Where …        ( select …
                                      From …
                                      Where …
                                     )
To write a sub-query, atleast 1 common column should be existing between the tables.
For ex :-
1) List the employees working in ‘Research’ department.
                                                                                       47 | P a g e
                     Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
Assignment
1) List the department names which are having salesmen in it.
2) Display the employees whose location is having atleast one ‘O’ in it.
                                                                           48 | P a g e
                     Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
3) List the department names that are having atleast 1 employee in it.
                                                                         49 | P a g e
                     Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
8) Display the 4th least salary
This method is not efficient to find the maximum and minimum salary. The limit is 32. This is not
efficient if you want to find the 100th maximum salary.
We can have upto 32 levels of sub-queries only.
                                                                                      50 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
                                                  CHAPTER 7
JOIN
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.
Here, each and every record of the 1st table will combine with each and every record of the 2nd table.
If a table A is having 10 records & B is having 4 records – the Cartesian join will return 10*4 = 40 records.
                                                                                                 51 | P a g e
                      Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
From above – we can see that the above query returns 56 records – but we are expecting 14 records. This
is because each and every record of employee table will be combined with each & every record of
department table.
Thus, Cartesian join should not be used in real time scenarios.
The Cartesian join contains both correct and incorrect sets of data. We have to retain the correct ones &
eliminate the incorrect ones by using the inner join.
INNER JOIN
Inner join are also called as equijoins.
They return the matching records between the tables.
                                                                                             52 | P a g e
                     Telegram - https://t.me/campusdrive
                       Telegram - https://t.me/campusdrive
In the real time scenarios, this is the most frequently used Join.
Scenario 1
              A
   P         Q              R
              B
   P          S             T
              C
   P          X             Y
                  We want
                                                                     53 | P a g e
                       Telegram - https://t.me/campusdrive
                          Telegram - https://t.me/campusdrive
   P           Q           S       X
Scenario 2
               A
   P           Q           R
                     B
   P           Q           S       T
               C
   P           X           Y
                         We want
   P           Q           R       S         X
If there are no common columns, then reject it saying that the two tables can be joined.
But there are some cases – where the 2 columns will be same but having different column names.
For ex – customerid & cid
                                                                                           54 | P a g e
                          Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
Display employee name, his job, his dname and his location for all the managers living in New York
or Chicago
Assignment
1) Display employee name and his department name for the employees whose name starts with ‘S’
                                                                                       55 | P a g e
                      Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
OUTER JOIN
It returns both matching and 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.
Display all the department names irrespective of any employee working in it or not. If an employee is
working – display his name.
                                                                                          56 | P a g e
                     Telegram - https://t.me/campusdrive
                       Telegram - https://t.me/campusdrive
A B
10 6
3 3
                                                                                      57 | P a g e
                       Telegram - https://t.me/campusdrive
                        Telegram - https://t.me/campusdrive
2) Display employee name and his department name who is earning 1st maximum salary
SELF JOIN
Joining a table to itself is called self join
Or
For ex, - Display employee name along with their manager name
Now, let us see how this i.e the logic (the above query) works,
                                                                                     58 | P a g e
                        Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
          Emp (A)
                                                                 Emp (B)
  EmpNo      Ename       Mgr
                                                         EmpNo      Ename      Mgr
   101        Scott      102
                                                          101        Scott     102
   102        Blake      103
                                                          102        Blake     103
   103        King        -
                                                          103        King       -
   104       Smith       103
                                                          104       Smith      103
   105        Jones      104
                                                          105        Jones     104
Now, when we give the above query – in Oracle – it starts matching the ‘mgr’ column of emp A with the
‘empno’ of emp b – we get two tables because in self join – a duplicate of the table required is created.
Now let us consider the first employee Scott – it starts the mgrid of Scott with the empno of all the
records in emp B – when two ids match, then the empno in emp B becomes the mgr of the empno in
emp A. Thus, we can see that – mgr id 102 is matching with empno 102 Blake in emp B. Therefore, Blake
is the manager of Scott.
Similarly we do the same for all the other records of emp A and thus find the employees and their
respective managers.
Co – related Queries :
For ex, Display the employee who is earning the highest salary
                                                                                             59 | P a g e
                      Telegram - https://t.me/campusdrive
                       Telegram - https://t.me/campusdrive
Thus, if an outer query column is being accessed inside the inner query, then that query is said to be co-
related.
Let us see the logic i.e, how we get the 1st max salary :-
In interview – this is a definite question. They will ask you what is co-related queries. And then
they’ll ask you find, 1st or max or 3rd maximum salary – after you write the query – they will ask you
to explain the logic as to how it gets the same – draw the table and explain it to them just as shown
above.
                                                                                                  60 | P a g e
                       Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
Assignment
                                                              61 | P a g e
                     Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
                                                               62 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
CHAPTER 8
FUNCTIONS
Pre – defined
     GROUP functions
     CHARACTER functions
     NUMERIC functions
     DATE functions
     SPECIAL 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 .. )
User – defined
Used only in PL/SQL and we will not study it here.
                                                                                          63 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
For ex :-
Dual – is a dummy table which is used for performing some independent operations which will not
depend on any of the existing tables.
                                                                                    64 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
For ex,
1)
2)
3)
We use dual – when the data is not present in any of the existing tables. Then we use dual.
                                                                                              65 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
For ex,
1)
2)
3) Display all the employees whose name & job is having exactly 5 characters
REPLACE
It replaces the old value with a new value in the given string.
For ex,
                                                                               66 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
Here, a – is the old value to be replaced with p – which is the new value.
This query replaces all the names which has ‘A’ in it with ‘B’.
                                                                             67 | P a g e
                      Telegram - https://t.me/campusdrive
                       Telegram - https://t.me/campusdrive
SUBSTR
This is called substring.
It extracts ‘n’ characters from x(th) position of a given string.
For ex,
                                                                    68 | P a g e
                       Telegram - https://t.me/campusdrive
                       Telegram - https://t.me/campusdrive
Here , (job, ‘1’ , ‘3’) – means from job – extract from 1st position , 3 characters.
                                                                                       69 | P a g e
                       Telegram - https://t.me/campusdrive
                         Telegram - https://t.me/campusdrive
INSTR
This is also called as instring.
It returns position of a given character in a given string.
For ex,
Given string
Character to be searched
Number of occurences
                                                                                   70 | P a g e
                         Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
List the employees whose job is having atleast 2 A’s in it
CONCAT
It concatenates any two values or columns.
It is represented by - ||
For ex,
NUMERIC FUNCTIONS
                                                                            71 | P a g e
                     Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
Round
It rounds off a given number to the nearest decimal place.
Trunc
It truncates the given number to the given decimal place. Truncate does not do any rounding.
For ex,
DATE FUNCTIONS
1) Sysdate
Stands for System date.
It returns both date & time, but by default – only date is displayed.
The default format is,
                      dd – mon – yy
2) Systimestamp
Introduced from Oracle 9i
Returns date, time and timezone.
                                                                                               72 | P a g e
                      Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
Here, .914000 – gives the fraction of millisecond which keeps changing as shown below,
In interview – if they ask you – “ which function contains fractions of a second “ OR “how to see the
system time “ – then answer is “SYSTIMESTAMP”.
SPECIAL FUNCTIONS
1) TO – CHAR
Used for displaying the date in different formats.
For ex,
                                                                                          73 | P a g e
                      Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
We can see that 5 hrs has been added to the current time.
                                                            74 | P a g e
                     Telegram - https://t.me/campusdrive
                       Telegram - https://t.me/campusdrive
NVL
It substitutes a value for a null.
For ex,
The above query means – if the employee has commission, then add sal + comm. To get total salary –
else add 0 to the sal and display total salary.
DECODE
It works like ‘if – then – else’ statement.
For ex,
                                                                                       75 | P a g e
                       Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
The above query states that – in job, if clerk is there, replace with C – else if salesman is there, replace it
with S – else replace with ‘O’.
Display employee name, job, salary and commission. If the commission is NULL, then display -100
                                                                                                   76 | P a g e
                      Telegram - https://t.me/campusdrive
                     Telegram - https://t.me/campusdrive
CHAPTER 9
NORMALIZATION
Normalization is the process of splitting the bigger table into many small tables without changing its
functionality.
It is generally carried out during the design phase of SDLC.
Advantages
1) it reduces the redundancy (unnecessary repeatation of data)
2) avoids problem due to delete anamoly (inconsistency)
Normalization is a step-by-step process and in each step, we have to perform some activities.
STEPS IN NORMALIZATION
1) 1NF – 1st Normal form
2) 2NF – 2nd Normal form
3) 3NF – 3rd Normal form
1NF
- We should collect all the required attributes into 1 or more bigger entities.
- We have to assume no 2 records are same (i.e, records should not be duplicated)
                                                                                                77 | P a g e
                     Telegram - https://t.me/campusdrive
                      Telegram - https://t.me/campusdrive
- Identify the probable primary key
    RegNo - PK
      Sname
     Semester
       DOB
      MailID
      Phone
    BookNo - PK
      Bname
      Author
       DOI
       DOR
       Fine
2NF
To perform 2NF,
- The tables have to be in 1NF
- Here, we identify all the complete dependencies and move them separately into different tables.
    RegNo - PK                    BookNo - PK
      Sname                       RegNo - FK
     Semester                       Bname
       DOB                          Author
      MailID                         DOI
      Phone                          DOR
                                     Fine
3NF
The table will have to be in 2NF
Here, we identify all the partial dependencies and move such columns to a separate table.
Disadvantage of Normalization
The only minor disadvantage is we may have to write complex queries as we have more number of
tables to be accessed.
Denormalization is the process of combining more than 1 smaller table to form 1 bigger table is called as
denormalization.
STUDENTS
           RegNo - PK
             Sname
            Semester
               DOB
             MailID
              Phone
                                                                               STUDENTS _
                                                                               INTERNALS
                                                                               RegNo - FK
                                                                                   Sid
                                                                                  Marks
BOOKS
                                                                                             79 | P a g e
                       Telegram - https://t.me/campusdrive
              Telegram - https://t.me/campusdrive
BookNo - PK
   BName
   Author
LIBRARY
                          BookNo - FK
                           RegNo - FK
                              DOI
                              DOR
                              Fine
                                                    80 | P a g e
              Telegram - https://t.me/campusdrive