SQL Notes Campus Monk

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

What is SQL?

To store multiple information, the most convenient way is to store the information on
the internet. To do this we can make use of databases.

For example: - To store information about a college.

The name of the tables are: -

• Student

• Course

• Department

• Instructor

The fields are: -

• Student name

• Student Id

• Course Name

• Description

• Department

• Name

• Instructor ID, etc.

SQL is the structured query language which will be used to communicate with
the database that we have created.
We use certain queries to communicate with our database, for eg:-

• Select Query - To read the data

• Insert Query - To insert the data

• Update Query - To modify data

• Delete Query - To delete the data, etc.


Basic Terminologies In SQL
• Data - Any useful information
• Table - When we organize data in the form of rows and columns, it is known as
a table.

For e.g: -

S.NO Name Age

1 Riya 25

2 Divya 23

• Record - All the single entry or row in a table is known as a record. So, in the
above example we have 2 records.
• Fields :- The name of the columns in a table are fields. In the above example,
S.No, Name, Age are fields
• Column - It is a set of the same datatype value. Eg, Name(String), Age(Integer).

Types Of Commands
Commands In SQL: SQL commands are used for database communication.
Additionally, they are utilised to carry out duties, activities, and data enquiries. Table
creation, data addition, table deletion, table modification, and user permission setting
are just a few of the many activities that we can do with the help of SQL commands.

There are basically five types of SQL commands: -


1. DDL: - Data Definition Language.
2. DML: - Data Manipulation Language.
3. DCL: - Data Control Language.
4. TCL: - Transaction Control Language
5. DQL: - Data Query Language

1. DDL: - Whenever there’s the need to change the structure of any table for example
creating the table, deleting the table or altering the table DDL come into the role. If any
change is made in DDL than it can’t be rolled back. Hence, they are permanent.

Example of DDL commands are: - CREATE, ALTER, DROP, TRUNCATE etc.

2. DML: - Whenever there’s the need to modify the database than DML come into the
role than DML is responsible for all possible changes in the database. If any change is
made in DML than it can be rolled back. Hence, they are not permanent.

Example of DML commands are: - INSERT, UPDATE, DELETE etc.

3. DCL: - Whenever there’s the need to grant or take back authority from any user
in the database than DCL come into the role.

Example of DCL commands are: - GRANT, REVOKE etc.

4. TCL: - TCL commands are the commands which are automatically committed and
can only used with DML commands like INSERT, DELETE etc. These commands cannot
be used while creating or Dropping tables.

Example of TCL commands are: - COMMIT, ROLLBACK etc.

5. DQL: - Whenever there’s the need to fetch the data from the database than DQL
come into the role. Whenever we need to print something or show something as
output than this command is needed.

Example of DQL commands are: - SELECT statements.

Keys in DBMS and Insert into keyword

Key: - key is used to identify each record or row of data in the table in a unique way.
Additionally, it is employed to define and pinpoint links between tables.

Keys are basically divided into 5 types: -

1. Primary Key: - It is the initial key used to uniquely identify each instance of an
object. An entity can have many keys. From those lists, the key that is most
appropriate becomes the primary key.
Example: -
Let say student details is a table that contains roll number, name, and class as
columns.
Here Primary key = Roll number
2. Candidate Key: - A minimum group of attributes that may independently identify
any other attribute is known as a candidate key.
The remaining attributes except primary key are regarded as candidate key. The
candidate keys are just as secure as the primary key.
Example: -
Let say student details is a table that contains roll number, name, and class as
columns.
Here Primary key = Roll number
So remaining name and class are considered as a candidate key.

3. Super Key: - Any numbers of attributes that may independently identify any other
attribute is known as a Super key.
Example: -
Let say student details is a table that contains roll number, name, and class as
columns.
Group of all 3 attributes will be considered as Super key.

4. Foreign Key: - A table's foreign key is a column that is used to refer to another
table's primary key.
Example: -
Let say student details is a table that contains roll number, name, and class as
columns.
And if there is another table where class and class teachers are attributes.
Here Foreign key = Class

5. Alternate Key: - The number of candidate keys minus the primary key equals the
total number of alternate keys. There could or might not be an alternative key. If
we have just one candidate key than does not have any alternate key.

Inserting Data

To insert the data into the table we use the INSERT INTO query.

INSERT INTO: -To insert new records inside the table, we use insert into key word.
We can use insert into syntax in two major ways: -

1. INSERT INTO table_name (column A, column B, column C, ...)


VALUES (value A, value B, value C, ...);

2. INSERT INTO table_name


VALUES (value A, value B, value C, ...);

Example of using INSERT INTO keyword: -

Let say we have the table Students with attributes as Roll number, Student name, and
class.
To insert details of new Student syntax that will be used will be: -
1. INSERT INTO Students
VALUES (17, Rohit, 12);

Roll_number Student_name Class


17 Rohit 12

or another syntax may be: -

2. INSERT INTO Students (Roll number, Student name, Class)


VALUES (16, Nisha, 12);

Roll_number Student_name Class


17 Rohit 12
16 Nisha 12

SELECT statement
Select: - To select any data from the database we generally use SELECT statements.
We may also obtain a specific record from a certain table column by using this
command. A result-set table is the one that contains the record that the SELECT query
returned.

General syntax of SELECT statement: -


1. To select fixed number of columns in a table.
SELECT column A, column B…. Column Z FROM table name;

2. To select every column of table.


SELECT * FROM table name;

Example: - We have a Table CUSTOMERS given here along with attributes as ID,
NAME, AGE, ADDRESS, and SALARY.

+-----+----------+-----+-----------+----------+--------+
| ID | NAME | AGE | ADDRESS | SALARY |

+-----+----------+-----+-----------+----------+---------+

| 1 | Rohit | 23 | Fatehabad | 20000.00 |

| 2 | Deepak | 21 | Rajgarh | 12500.00 |

| 3 | Nisha | 22 | Pilani | 21000.00 |

| 4 | Parveen | 26 | Palwal | 65000.00 |


| 5 | Samay | 25 | Pune | 85000.00 |

| 6 | Virat | 28 | Delhi | 5100.00 |

| 7 | Nikhil | 29 | Kanpur | 70000.00 |

+----+----------+-----+-----------+----------+----------+

1. SELECT ID, NAME, SALARY FROM CUSTOMERS;


+--+---------+-----------+

| ID | NAME | SALARY |

+--+---------+-----------+

| 1 | Rohit | 20000.00 |

| 2 | Deepak | 12500.00 |

| 3 | Nisha | 21000.00 |

| 4 | Parveen | 65000.00 |

| 5 | Samay | 85000.00 |

| 6 | Virat | 5100.00 |

| 7 | Nikhil | 70000.00 |

+----+----------+--------------+

2. SELECT * from CUSTOMERS;

+-----+----------+-----+-----------+----------+--------+
| ID | NAME | AGE | ADDRESS | SALARY |

+-----+----------+-----+-----------+----------+---------+

| 1 | Rohit | 23 | Fatehabad | 20000.00 |

| 2 | Deepak | 21 | Rajgarh | 12500.00 |

| 3 | Nisha | 22 | Pilani | 21000.00 |

| 4 | Parveen | 26 | Palwal | 65000.00 |


| 5 | Samay | 25 | Pune | 85000.00 |

| 6 | Virat | 28 | Delhi | 5100.00 |

| 7 | Nikhil | 29 | Kanpur | 70000.00 |

+----+----------+-----+-----------+----------+----------+

Data Types in SQL


Data type can be of many types according to the usage but more importantly we divide
the data types like Numbers, characters and Date Time data storage.

Numbers:

Numbers are of three types either Integer value which can be created as int.

Example:

create table example{


ID int,
}
A numeric value can also be stored as decimals which can be classified in Float data
type.

create table example{


ID Float,
}
A numeric value can be a bool value which can just store the 0 (False) or 1(True).

create table example{


ID bool,
}

Characters:

The character values can be stored in the form of the strings or character, the data
which is stored statically stored in data type 'CHAR' and the data which needs to be
stored dynamically stored in 'VARCHAR'

create table example{


Name char(10),
Address Varchar(100)
}
Date and Time:

Date can be stored in the following given format by using the Date data type:

Date-YYYY MM DD

Year can be stored in the following given format by using the Year data type:

Year-YY/YYYY

Date and timing can be stored in combined format in the following given format by
using the DateTime data type:

Datetime-YYYY MM DD HH MM SS

This is how any data can be stored in the tables of database.

Constraints in SQL
The constraints which will be applied on the fields to maintain the data suppose the
column data should be unique or not null and many other constraints would help in
maintaining the data.

NOT NULL:

The Not Null constraint helps in creating the fields data which can't be allowed to have
any NULL value in the whole column data.

Example:

CREATE TABLE table1(

ID int NOT NULL,

Name varchar (100)

UNIQUE:

The UNIQUE constraint would help in having the data which is not going to be
duplicate in the same column.
Example:

CREATE TABLE table1(

ID int NOT NULL UNIQUE,

Name varchar (100)

PRIMARY KEY:

The primary key is the key which can be just assigned to only one field in one table,
and this primary key would help in making the fields UNIQUE as well as NOT NULL.

Example:

CREATE TABLE table1(

ID int PRIMARY KEY,

Name varchar (100)

FOREIGN KEY:

The Foreign key is a key which belongs to the other table primary key, suppose you
have a ID of the orders table, and you want to reference that ID to the another table
named customers then this constraint would be helpful.

Example:

create table customers(

c_id int NOT NULL PRIMARY KEY,

c_name varchar (100)

);

create table orders(

o_id int NOT NULL PRIMARY KEY,


o_no int,

c_id int FOREIGN KEY REFERENCES customers (c_id)

);

CHECK:

The check constraint would help in checking a particular condition while inserting the
data, suppose if you are feeding less than 18 age in a adult form than it not needs to be
submitted.

Example:

CREATE TABLE table1(

ID int,

Name varchar (100),

age int CHECK (age>=18)

DEFAULT:

The default constraint is used when we needs to have the default value when there is
no value will get entered by the user.

Example:

CREATE TABLE table1(

ID int,

Name varchar (100),

city varchar(100) DEFAULT 'Delhi'

)
SELECT, WHERE, AND, OR clause in SQL

SELECT clause:

The select clause helps in printing the values present in the table

Example:

SELECT * FROM example; // here example is the name of table already exist in
database

Output:

Name Age

Anupam 22

Kunal 20

Rishabh 25

WHERE clause:

The WHERE clause helps in making some decision inside the query data printing,
suppose you need to print the data whose age is 22.

SELECT * FROM example WHERE age = 22

Output:
Name Age

Anupam 22

AND & OR clause:

These clauses helps in making a decision when there is more than one condition is
required.

Suppose you need to print the values whose age is between 21 and 23

Example 1:

SELECT * FROM example WHERE age<23 and age>21;


Output:

Name Age

Anupam 22

Suppose you need to print the values whose age is less than 21 or greater than 26.

Example 2:

SELECT * FROM example WHERE age<21 OR age>26;

Output:
Name Age

Kunal 20

LIKE and TOP clause in SQL


.First of all, we are creating the table named “example”:

Create table(
Name varchar(100),
Age int
);
Then inserting the following data into the above given table:

Insert into example values(‘anupam’, 22);


Insert into example values(Kunal, 20);
Insert into example values(Rishabh, 25);
After creating and inserting the data into the table, we can perform any modification
into the table.

LIKE clause:

This clause helps to print the values whose particular value looks like something
specific.

Suppose, you need to print the values whose name is starting with A.

Example:

SELECT * FROM example WHERE Name LIKE ‘A%’;

Output:
Name Age

Anupam 22

Similarly , you need to print the values whose name is ending with m.

Example:

SELECT * FROM example WHERE Name LIKE ‘%m’;


Output:

Name Age

Anupam 22

TOP clause:

This clause helps in printing the values with the specific number of top values.

Print the top 2 queries of the table

Example:

SELECT TOP 2 * FROM example


Output:
Name Age

Anupam 22

Kunal 20

UPDATE and DELETE clause in SQL


UPDATE clause:

The UPDATE keyword uses in updating the rows data in the system.

Update the name to “ROHIT” whose age is 20

Example:

UPDATE example
SET name = ‘Rohit’
WHERE age = 20;
SELECT * FROM example;
Output:

Name Age

Anupam 22

Rohit 20

Rishabh 25
DELETE clause:

The delete keyword is used in deleting the particular query from the table data.

Suppose you need to delete the data from the table whose name is ‘Anupam’

Example:

DELETE * from example WHERE name = ‘Anupam’;


SELECT * FROM example
Output:

Name Age

Rohit 20

Rishabh 25

Operators In SQL

There are basically four types of operators in SQL.


1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Wildcard Operators

1. Arithmetic Operators: -
The mathematical operations are carried out by the arithmetic operators on the
numerical
data in SQL tables. On the numerical operands, these operators carry out the
operations
of addition, subtraction, multiplication, and division.
Example: -
I. SQL Addition Operator
SELECT operand1 + operand2;
II. SQL Subtraction Operator
SELECT operand1 - operand2;
III. SQL Multiplication Operator
SELECT operand1 * operand2;
IV. SQL Division Operator
SELECT operand1 / operand2;

2. Comparison Operators: -
The SQL comparison operators compare two distinct SQL table values and
determine
whether they are equal, greater, or less. The WHERE clause and SQL comparison
operators are combined in SQL queries.
Example: -
I. SQL Equal operator (=)
II. SQL Not Equal operator (! =)
III. SQL Greater Than operator (>)
IV. SQL Greater Than Equals to operator (>=)
V. SQL Less Than operator (<)
VI. SQL Less Than Equals to operator (<=)

Example of equal to operator: -


Let say in a class of students we need to find the records of those students whose
marks
are 70 out of hundred.
SELECT
* FROM Students_details
WHERE
marks = 70;

3. Logical Operators: -
Boolean operations, which produce the two outcomes True and False, are carried
out by
the logical operators in SQL. If the logical condition is met by both operands, these
operators return True.
Example: -
I. ALL operator: - It is used with SELECT, HAVING and WHERE statements.
II. AND operator: - It is used with WHERE clause.
III. OR operator: - It is used with WHERE clause.
IV. BETWEEN operator: -To show record within the range mentioned in query.
V. IN operator: - It is used with WHERE clause.
VI. NOT operator: - It is used to show records where condition results in false.
VII. ANY operator: - It is used to show records when at least one sub query value is
true.
VIII. LIKE operator: - It is used in WHERE clause with SELECT, UPDATE and DELETE
statements.

4. Wildcard Operators: -
To replace one or more characters in a string, use a wildcard character. The LIKE
operator uses wildcard characters. To look for a specific pattern in a column, use
the
LIKE operator in a WHERE clause.

Example: -
I. Words that starts with A: - WHERE WORD LIKE ‘A%’

II. Words that have A at any position: - WHERE WORD LIKE ‘%A%’

III. Words that have A at 2nd positon: - WHERE WORD LIKE ‘_A%’

IV. Words that end with A: - WHERE WORD LIKE ‘%A’

V. Words that have five alphabets and end with B: - WHERE WORD LIKE ‘____B’

JOINS
WHAT ARE JOINS

Joins in SQL are used to combine data or rows from two or more tables based on a
common field between them.

Let’s consider this example. We have two tables named student and studentcourse.

Table Student

Roll no Name Address Phone Age

1 Harsh Delhi ********** 18


2 Pratik Bihar ********* 19

3 Priyanka Gujarat ********* 20

4 Deep Kolkata ********* 18

5 Rohit Chennai ********* 19

6 Shailja Pune ********* 20

7 Shipra Mumbai ********* 21

Table StudentCourse

Course_id Roll_No

1 1

2 5

2 3
5 2

3 6

Now suppose we want to fetch the course_id of the student Rohit. We can see that name
and course_id are in different columns, but there is a common attribute in both of the
tables that is Roll_No. So what we can do is, we can take the roll_no of the Rohit from
table student and then from roll_no we can take the course_id from the table
StudentCourse.

Note: We can do other things as well like we want to check the age of students who
have the same course_ids. So we can take roll_no’s from table StudentCourse and then
from table Student we will check the ages of those students.

Types of joins-

There can be some problems while joining the tables in SQL like for example, for any
entry in table A there is a possible situation that entry is not present in table B. So for
dealing with these kinds of scenarios we have different types of joins. These are-

Inner join- Inner join will give the common values from both the tables as the resultant
set.So for example if we apply inner join on the above table then it will give the resultant
set as values having common roll_no’s.

Left Join- It will give all the values from table1 and will provide only the matching
values from table2 and if no value is present for any value in table2 than it will provide
NULL .So from the above table it will give all the values from table1 and matching values
from table2.

Right Join- It will give all the values from table2 and only matching values with table1
and if no value is present for any value in table1 then it will provide NULL . So from the
above table it will give all the values from table2 and matching values from table1.

Full Join/Outer Join- It will give all the values from table1 and table2.
UNION
The union clause is used to combine two separate select statements and produce the
result set as a union of both the select statements.

Syntax for union clause is-

SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2;

This statement is used if we want that our resultant set contains distinct values.

SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM


table2;

This statement is used if we want that our resultant set contains duplicate values too.

Notes: The fields used in both the select statements must be in the same order, number
and data type.

The Union clause produces distinct values in the result set, to fetch the duplicate values
too UNION ALL must be used instead of UNION.

Student

ROLL NO NAME ADDRESS PHONE AGE

1 RAM DELHI ********* 18

2 RAMESH DELHI ******** 18

3 SUJIT DELHI ********* 20


4 SURESH DELHI ********* 18

3 SUJIT DELHI ******** 20

2 RAMESH DELHI ******** 18

Student_Details

ROLL NO BRANCH GRADE

1 IT O

2 CSE E

3 CSE O

4 ME A

So the syntax will be for not wanting duplicates in the resultant set will be
SELECT ROLL_NO FROM Student UNION SELECT ROLL_NO FROM Student Details;

And if we want duplicates as well then the result will be-

SELECT ROLL_NO FROM Student UNION ALL SELECT ROLL_NO FROM Student Details;

Output -

For query1 the output will be 4 rows from the beginning joined from union

For query2 the output will be all the rows.

Clone Tables using SQL


Suppose you are having the following database(Table1):

S.No. Name Class Roll

1 Anupam 12 23

2 Kunal 12 25

First of all, we need to create the structure of the database by using the following SQL
command:

CREATE TABLE Table2 LIKE Table1;


This command would create a structure of the table as shown below:
S.No. Name Class Roll

After execution of the above steps, we can simply copy the data of table1 to table2 by
using the following command:

INSERT INTO Table2 SELECT * FROM Table1;

After executing the command we will having our Table2 as

S.No. Name Class Roll

1 Anupam 12 23

2 Kunal 12 25

Handling Duplicates
In this , we would learn how to handle a table which is having the duplicate values in
the same table but we just need to have the values which is not duplicate in the list.

Let's take an example, we are having a table which is having the name "Anupam" more
than one time:

Table Name: Details

Name Roll Number Department


Anupam 1 CSE

Anupam 2 ECE

Anupam 3 EEE

Suppose we just need to print the data only once with the same name than this
condition would help in handling duplicates.

This following given line would help in removing the duplicated data in case of similar
name removal.

SELECT DISTINCT Name FROM Details

After using the command, we will just get one record with the name "Anupam".

DCL Commands
-> We are aware that SQL enables a user to specify the structure, classification, and
relationships among the data items to be stored as well as how to access the data from
the database.

-> The user can also modify and change the current data in the database of an
application software.

-> Thus, we will discover how SQL may be used in this article to deny a user the ability
to alter, add to, or retrieve data and safeguard all data from unauthorised access. Data
Control Language (DCL) in SQL is used for this.

-> Data Control Language (DCL) is the name given to the set of SQL commands that
allow a user to access, modify, or interact with the various rights needed to control the
database.

There are basically two commands used in DCL: -

1. GRANT: -The GRANT DCL command is used to grant (provide access to) security
rights to particular database users. It mostly serves to limit user access to INSERT,
SLECT, UPDATE, DELETE etc. or to provide access to user’s data.
2. REVOKE: -The REVOKE DCL command is used to revoke access that has been
granted using the GRANT command. Removing the authorization that was granted to
carry out particular operations is the main application of going back to the time when
no access was specified.

Some of the examples through which we will try to understand these two operations
are: -
Examples of GRANT: -

I. At first, we must create the session


GRANT CREATE SESSION TO mytab;

II. How to allow user to create a table


GRANT CREATE TABLE TO mytab;

III. Now after allowing to create table how to grant permission for creating
any table
GRANT CREATE ANY TABLE TO mytab;

IV. GRANTING ALL THE POSSIBLE PRIVILEGES TO THE USER


GRANT sysdba TO mytab;

Examples of REVOKE: -

I. Take back all Permissions


REVOKE CREATE TABLE FROM mytab;
II. To Revoke a CREATE TABLE privilege from testing ROLE
REVOKE CREATE TABLE FROM testing;

III. Syntax to drop a role from database


DROP ROLE role_name;
TCL Commands
-> TCL stands for Transaction control language.

-> Transaction is what results from several instructions being executed one after the
other in a database.

-> The user can manage the transactions that occur in a database by using particular
SQL commands called as TCL commands.
Particularly they are: -

1. COMMIT: -
To save all transaction-related changes to the disc permanently in SQL,
use the COMMIT command. When DDL commands like INSERT,
UPDATE, and DELETE are performed, the modifications they make
become permanent only after the current session is closed.

Example: -
Basic syntax for using COMMIT command is: -
BEGIN TRANSACTION;
(A set of SQL statements)
COMMIT TRANSACTION;
More simplified version of using this command is: -
(A set of SQL statements)
COMMIT;

2. ROLLBACK: -
The COMMIT command's ROLLBACK option resets the database to its
initial state.
It is employed to return the database to its most recently committed state.

Example: -
So let say we deleted the record of age where age is equal to 30 years.
Now we have to ROLLBACK that. So, syntax of this is: -
DELETE FROM CUSTOMERS
WHERE age = 30;
ROLLBACK;
So, this query will get back the deleted values again to the table.

3. SAVEPOINT: -
The database operations may be split up into different components. For
instance, we may think of the delete command as one half of the
transaction and all the insert-related queries that we would run
sequentially as the other.
We may store these several components of the same transaction using
various names by utilising the SAVEPOINT command.

EXAMPLE: -
Syntax of SAVEPOINT Command is shown below.
SAVEPOINT Name_of_Savepoint;

Syntax for rolling back to SAVEPOINT is: -


ROLLBACK TO Name_of_Savepoint;

FUNCTION IN SQL-
DATE FUNCTIONS

The first function in SQL is GETDATE(). This GETDATE() function will return the
current date and time.

Syntax-

SELECT GETDATE();

Output-

2022-10-27 19:52:15

We can also provide some ALIAS to this and the syntax for it will be -

SELECT GETDATE() AS CurrentDateTime;

Output-

2022-10-27 19:52:15

We have other types of date time functions in SQL. These are-

DATEPART- This function will select a certain part from a date and the part that is
going to split will depend on us. It takes two parameters, one is what part you want to
select and second is from which date we want to select.
Syntax, if we want to select the year

SELECT DATEPART(yy, ‘1999-12-19 13:25:42.666’);

Output-

1999

Syntax, if we want to select the month

SELECT DATEPART(mm, ‘1999-12-19 13:25:42.666’);

Output-

12

Syntax, if we want to select the day

SELECT DATEPART(dd, ‘1999-12-19 13:25:42.666’);

Output-

19

DATEADD- It is used to add a certain number to a specific date that we are providing.
It takes three parameters, first parameter is in which you want a change, second is the
number to add and third is the date and time.

Syntax -If we want to add a certain number to the date. In this we want to add 10 to the
date 19 so output should be 29.

SELECT DATEADD(dd,10,‘1999-12-19 13:25:42.666’);

Output-

1999-12-29 13:25:42.666

DATEDIFF- It will return the difference between the two dates. It takes three
parameters, first is the parameter in which you want to change, second and third are
the two dates.

SELECT DATEADD(dd, ‘1999-12-19’, ‘1999-12-31’);

Output-
12

The difference between 31 and 19 is 12.

SUBSTRING-

Substrings are the part of the strings and we can apply them to SQL as well.

It takes three parameters, first is the parent string, second is the position from where
you want to fetch a substring and third is the length of the substring.

Syntax-

SELECT SUBSTRING(‘Campusmonk’,6,5);

Output- smonk

Note: If this is applied on a table then table name is written in place of the parent string.

LCASE, UCASE, CONCAT, etc-

We have different string functions in SQL. These are-

ASCII- It takes the parameter of which you want the ASCII value and returns the ASCII
value of it.

Syntax-

SELECT ASCII(‘A’);

Output-

65

Note: We can directly apply it on a column name by writing column name instead of the
character provided.

CHAR- This function will give the character by taking an integer as an input.

Syntax-

SELECT CHAR(65);
Output-

CONCAT- This function is used to concatenate two strings. It can take any number of
strings as a parameter.

Syntax-

SELECT CONCAT(‘GEEKS’,’FOR’,’GEEKS’);

Output-

GEEKSFORGEEKS

DATALENGTH- It will give the length of the data that we pass in the function.

Syntax-

SELECT DATALENGTH( ‘Geeks’);

Output-

Note: For length, we can also use the LEN function.

LEFT- This function will return the number of characters mentioned from left.

Syntax-

SELECT LEFT(‘campusmonk’, 6);

Output-

campus

Right- This function will return the number of characters mentioned from right.

Syntax-

SELECT RIGHT(‘campusmonk’, 3);

Output-

onk
LOWER- This function will return all the characters in the lower case.

Syntax-

SELECT LOWER(‘CAMPUS’);

Output-

campus

UPPER- This function will return all the characters in the upper case.

SELECT UPPER(‘campus’);

Output-

CAMPUS

REVERSE-This function will return the characters in reverse.

Syntax-

SELECT REVERSE(‘campus’);

Output-

Supmac

VIEWS(WHAT ARE VIEWS, ADVANTAGES OF VIEWS, CRUD


IN VIEWS)
VIEWS IN SQL
A view is a virtual table based on the result-set of an SQL statement. It contains rows
and columns like a real table. The fields it contains are from a real table only. It will have
a combination of all the tables that we mention.

After combining it will give a view of one single table only.

Example -

Table Customer (C_Name, C_ID, P_ID, C_NO, C_ADDRESS)

Table Products(P_Name, P_Price, P_MAN_DATE, P_EXP_DATE)


View(C_Name, P_Name, P_ID, P-Price, P_MAN_DATE, P_EXP_DATE)

Note1: We can also create this by using joins but creating a view is much easier.

Note2: View has an advantage that we can put only selected columns in it which we
want to show, we don’t have to put all the columns in it.

ADVANTAGES OF VIEWS-

Simplicity- Joining two or more tables can be done using joins as well but creating a
view is much simpler.

Security- View gives us a choice to put only those columns which we want to, so every
column is not accessible by everyone providing security.

The data is safe because it is still present in the parent table.

CRUD OPERATIONS IN VIEW-

CRUD stands for create, read , update and delete. These are the operations we can
perform on a view.

How do we create a view-

Syntax-

CREATE VIEW view_name AS

SELECT column1, column2,....

From table_name

Where condition;

Example-

Table Customer (C_Name, C_ID, P_ID, C_NO, C_ADDRESS)

Table Products(P_Name, P_Price, P_MAN_DATE, P_EXP_DATE)

View(C_Name, P_Name, P_ID, P-Price, P_MAN_DATE, P_EXP_DATE)

Creating a view-
CREATE VIEW [Description] AS SELECT C.C_Name, P.P_Name, P.P_ID, P.P_Price,
P.P_MAN_DATE, P.P_EXP_DATE

FROM Customer C, Products P ;

Reading a view-

SELECT * FROM [Description];

Updating a view-

CREATE OR REPLACE VIEW Description AS

SELECT C.C_Name, P.P_Name, P.P_ID, P.Price, P.P_MAN_DATE,

P.P_EXP_DATE, C_NO

FROM Customer C, Products P;

Deleting a view-

DROP VIEW [Description];

Normalization DBMS
Database normalization is the process of organizing the attributes of the database to
reduce or eliminate data redundancy (having the same data but at different places) .

Problems because of data redundancy

Data redundancy unnecessarily increases the size of the database as the same data is
repeated in many places. Inconsistency problems also arise during insert, delete and
update operations.

Functional Dependency

Functional Dependency is a constraint between two sets of attributes in relation to a


database. A functional dependency is denoted by an arrow (→). If an attribute A
functionally determines B, then it is written as A → B.
For example, employee_id → name means employee_id functionally determines the
name of the employee. As another example in a timetable database, {student_id, time}
→ {lecture_room}, student ID and time determine the lecture room where the student
should be.

Normalization is the process of minimizing redundancy from a relation or set of


relations. Redundancy in relation may cause insertion, deletion, and update anomalies.
So, it helps to minimize the redundancy in relations. Normal forms are used to eliminate
or reduce redundancy in database tables.

1. First Normal Form

If a relation contain composite or multi-valued attribute, it violates first normal form or


a relation is in first normal form if it does not contain any composite or multi-valued
attribute. A relation is in first normal form if every attribute in that relation is singled
valued attribute.

Example 1 – Relation STUDENT in table 1 is not in 1NF because of multi-valued attribute


STUD_PHONE. Its decomposition into 1NF has been shown in table 2.

2. Second Normal Form

To be in second normal form, a relation must be in first normal form and relation must
not contain any partial dependency. A relation is in 2NF if it has No Partial Dependency,
i.e., no non-prime attribute (attributes which are not part of any candidate key) is
dependent on any proper subset of any candidate key of the table.
Partial Dependency – If the proper subset of candidate key determines non-prime
attribute, it is called partial dependency.

Consider following functional dependencies in relation R (A, B , C, D )

AB -> C [A and B together determine C]

BC -> D [B and C together determine D]

In the above relation, AB is the only candidate key and there is no partial dependency,
i.e., any proper subset of AB doesn’t determine any non-prime attribute.

3. Third Normal Form –


A relation is in third normal form, if there is no transitive dependency for non-prime
attributes as well as it is in second normal form.
A relation is in 3NF if at least one of the following condition holds in every non-trivial
function dependency X –> Y

X is a super key.

Y is a prime attribute (each element of Y is part of some candidate key).

Transitive dependency – If A->B and B->C are two FDs then A->C is called transitive
dependency.

Example 1 – In relation STUDENT given in Table 4,


FD set: {STUD_NO -> STUD_NAME, STUD_NO -> STUD_STATE, STUD_STATE ->
STUD_COUNTRY, STUD_NO -> STUD_AGE}
Candidate Key: {STUD_NO}
For this relation in table 4, STUD_NO -> STUD_STATE and STUD_STATE ->
STUD_COUNTRY are true. So STUD_COUNTRY is transitively dependent on STUD_NO.
It violates the third normal form. To convert it in third normal form, we will
decompose the relation STUDENT (STUD_NO, STUD_NAME, STUD_PHONE,
STUD_STATE, STUD_COUNTRY_STUD_AGE) as:
STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_AGE)
STATE_COUNTRY (STATE, COUNTRY)

You might also like