0% found this document useful (0 votes)
13 views

DBMS Note

Database management system note

Uploaded by

ranjanbibek878
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

DBMS Note

Database management system note

Uploaded by

ranjanbibek878
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

SQL

SQLcommands are instructions. It is used to communicate with the database. It is


also used to performspecific tasks, functions, and queries of data.
SQLcan performvarious tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.

SQLCommands are mainly categorized into five categories:


1. DDL– Data Definition Language
2. DQL– Data Query Language
3. DML– Data Manipulation Language
4. DCL– Data Control Language
5. TCL– Transaction Control Language
1. Data Definition Language (DDL) :
DDLchanges the structure of the table like creating a table, deleting a table, altering
a table, etc.
All the command of DDLare auto-committed that means it permanently save all the
changes in the database.
Following are the some commands that come under DDL:
Create, Alter,Truncate , Drop
A. CREATE It is used to create a new table in the database.
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAMES DATATYPES [ ...]);
Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);
B . DROP: It is used to delete both the structure and record stored in the table.
Syntax: To DROPa table permanently frommemory
DROP TABLE table_name;
Example : DROP TABLE EMPLOYEE;
C. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.
1. Add:
With the use of ALTER table command we can add new columns existing table.
Syntax: To add a new column in the table
ALTER TABLE table_name ADD column_name column-definition;
EXAMPLE:
ALTER TABLE STU_DETAILS ADD (ADHAR_NUMVARCHAR2 (15));
2. Modify
With the use of ALTER table we can modify column and constraint in the existing table. These
statements can increase or decrease the column widths and changing a column frommandatory to
optional.
Syntax:
ALTER TABLE table_name MODIFY (column definitions....);

Example:
ALTER TABLE STU_DETAILS MODIFY (ADHAR_NUMVARCHAR2 (20));

3. Drop
You cannot only modify columns but you can also drop thementirely if it is no longer required in a
table. Using drop statement in alter command we can also remove the constraints formthe table.
Syntax: To drop a column froma table.
ALTER TABLE table_name DROP COLUMN column_name;

Example:
ALTER TABLE STU_DETAILS DROP COLUMN ADHAR_NUM;

4. Rename:
SQLprovides the facility to change the column name by using a ALTER TABLE statement.
Syntax:
ALTER TABLE TABLE_NAME RENAME COLUMN <OLD_TABLENAME> to <NEW_TABLENAME>;
Example:
ALTER TABLE STUDENT Rename column STU_NAME toSTUDENT_NAME;
D. TRUNCATE: It is used to delete all the rows fromthe table and free the space containing the
table.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE EMPLOYEE;
2. Data Manipulation Language

DMLcommands are used to modify the database. It is responsible for all formof
changes in the database.
The command of DMLis not auto-committed that means it can't permanently save all
the changes in the database. They can be rollback.
Following are the some commands that come under DML:
INSERT,UPDATE,DELETE
a. INSERT: The INSERT statement is a SQLquery. It is used to insert data into the row of a
table.
Syntax: To add row in a table
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N) VALUES (value1, value2, value3, .... v
alueN);
OR
INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN);
EXAMPLE
INSERT INTO STUDENT(Author, Subject) VALUES (‘Sonoo’, ‘DBMS’);
OR
INSERT INTO STUDENT VALUES (‘Sonoo’, ‘DBMS’);
b. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax: To update record in a table
UPDATE table_name SET [column_name1= value1] [WHERE CONDITION] ;
EXAMPLE
UPDATE students SET User_Name = 'Sonoo' WHERE Student_Id = '3'

b. DELETE: It is used to remove one or more row froma table.


Syntax: To Delete a record fromtable
DELETE FROMtable_name [WHERE condition];
EXAMPLE
DELETE FROMstudent WHERE Author=’Sonoo’;

d. SELECT: This is the same as the projection operation of relational algebra. It is used to select the
attribute based on the condition described by WHERE clause.
Syntax: It is used for retrieve the records fromtable
SELECT expressions FROMTABLES WHERE conditions;
Example:
SELECT emp_name FROMemployee WHERE age > 20;

3. Data Control Language


DCLcommands are used to grant and take back authority fromany database user.
Following are the some commands that come under DCL:
Grant,Revoke
Syntax:
GRANT <obj_priv> ON <obj_name> To <username>;
Example
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

b. Revoke: It is used to take back permissions fromthe user.


Syntax:
REVOKE <obj_priv> ON <obj_name> FROM<username>;
Example :
REVOKE SELECT, UPDATE ON MY_TABLE FROMUSER1, USER2;
4. Transaction Control Language
Transactions are atomic i.e. either every statement succeeds or none of statement succeeds. There
are number of Transaction Control statements available that allow us to control thisbehavior.
These statements ensure data consistency. TCLcommands can only use with DMLcommands like
INSERT, DELETE and UPDATE only.
Following are the some commands that come under TCL:
Commit, Rollback , Save point
a. Commit: Commit command is used to save all the transactions to the database. It makes your
changes permanent and ends the transaction.
Syntax: To permanently save the changes
COMMIT;
Example:
DELETE FROMCUSTOMERS WHERE AGE = 25;
COMMIT;
c. Rollback:
Rollback command is used to undo transactions that have not already been saved to the
database. Rollback also serves to end the current transaction and begin a new one.

Syntax: To remove the changes


ROLLBACK;
Example:
DELETE FROMCUSTOMERS WHERE AGE = 25;
ROLLBACK;
d. SAVEPOINT:
It is used to roll the transaction back to a certain point without rolling back the entire
transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;

SQLOperator
The SQLreserved words and characters are called operators, which are used with a WHERE clause
in a SQLquery. In SQL, an operator can either be a unary or binary operator. The unary operator
uses only one operand for performing the unary operation, whereas the binary operator uses two
operands for performing the binary operation.
SQLOperator Symbols
Operators
**
Exponentiation operator
+, -
Identity operator, Negation operator
*, /
Multiplication operator, Division operator
+, -, ||
Addition (plus) operator, subtraction (minus) operator, String Concatenation operator
=, !=, <, >, <=, >=, ISNULL, LIKE, BETWEEN, IN
Comparison Operators
NOT
Logical negation operator
&& or AND
Conjunction operator
OR
Inclusion operator

Types of Operator
SQLoperators are categorized in the following categories:
● SQLArithmetic Operators
● SQLComparison Operators
● SQLLogical Operators
● SQLSet Operators
● SQLBit-wise Operators
● SQLUnary Operators

Arithmetic Operators
The Arithmetic Operators performthe mathematical operation on the numerical data of the SQL
tables. These operators performaddition, subtraction, multiplication, and division operations on the
numerical operands.
Following are the various arithmetic operators
1. SQLAddition Operator (+)
2. SQLSubtraction Operator (-)
3. SQLMultiplication Operator (*)
4. SQLDivision Operator (/)
5. SQLModulus Operator (%)
1. SQLAddition Operator (+)
The Addition Operator in SQLperforms the addition on the numerical data of the database table. In
SQL, we can easily add the numerical values of two columns of the same table by specifying both the
column names as the first and second operand.
Example :
SELECT Emp_Salary + 20000 as Emp_New_Salary FROMEmployee_details;

2. SQLSubtraction Operator (-)


The Subtraction Operator in SQLperforms the subtraction on the numerical data of the database
table. In SQL, we can easily subtract the numerical values of two columns of the same table by
specifying both the column names as the first and second operand.
Example :
SELECT Emp_Salary - 5000 as Emp_New_Salary FROMEmployee_details;

3. SQLMultiplication Operator (*)


The Multiplication Operator in SQLperforms the Multiplication on the numerical data of the
database table.
Example :
SELECT Emp_Salary * 2 as Emp_New_Salary FROMEmployee_details;

4. SQLDivision Operator (/)


The Division Operator in SQLdivides the operand on the left side by the operand on
the right side.
Example :
SELECT Emp_Salary / 2 as Emp_New_Salary FROMEmployee_details;

5. SQLModulus Operator (%)


The Modulus Operator in SQLprovides the remainder when the operand on the left side
is divided by the operand on the right side.
Example :
SELECT First_operand % Second_operand as Remainder FROMEmployee_details;

SQLComparisonOperators

1. SQLEqual Operator (=)


2. SQLNot Equal Operator (!=)
3. SQLGreater Than Operator (>)
4. SQLGreater Than Equals to Operator (>=)
5. SQLLess Than Operator (<)\
6. SQLLess Than Equals to Operator (<=)
1. SQLEqual Operator (=)
This operator is highly used in SQLqueries. The Equal Operator in SQLshows only data
that matches the specified value in the query.
This operator returns TRUE records fromthe database table if the value of both
operands specified in the query is matched.
Example :
SELECT * FROMEmployee_details WHERE Emp_Salary = 30000;
2. SQLEqual Not Operator (!=)
The Equal Not Operator in SQLshows only those data that do not match the query's specified
value.
Example :
SELECT * FROMEmployee_details WHERE Emp_Salary != 45000;
3. SQLGreater Than Operator (>)
The Greater Than Operator in SQLshows only those data which are greater than the
value of the right-hand operand.
Example :
SELECT * FROMEmployee_details WHERE Emp_Id > 202;

4. SQLGreater Than Equals to Operator (>=)


The Greater Than Equals to Operator in SQLshows those data fromthe table which are
greater than and equal to the value of the right-hand operand.
Example :
SELECT * FROMEmployee_details WHERE Emp_Id >= 202;
5. SQLLess Than Operator (<)
The Less Than Operator in SQLshows only those data fromthe database tables
which are less than the value of the right-side operand.

This comparison operator checks that the left side operand is lesser than the right
side operand. If the condition becomes true, then this operator in SQLdisplays the data which is
less than the value of the right-side operand.

Example :

SELECT * FROMEmployee_details WHERE Emp_Id < 204;


6. SQLLess Than Equals to Operator (<=)
The Less Than Equals to Operator in SQLshows those data fromthe table which are
lesser and equal to the value of the right-side operand.

Example:

SELECT * FROMEmployee_details WHERE Emp_Id <= 203;

SQLLogical Operators
The Logical Operatorsin SQLperformthe Boolean operations, which give two results
True and False. These operators provide True value if both operands match the logical condition.

The Logical Operators in SQLare as follows:


1. SQLANDOPERATOR
2. SQLOR OPERATOR
3. SQLNOT OPERATOR
4. SQLBETWEENOPERATOR
5. SQLINOPERATOR
6. SQLLIKE OPERATOR
1. SQLANDOPERATOR :
The SQLANDoperator is used with the where clause in the SQLQuery. ANDoperator in SQL
returns only those records which satisfy both the conditions in the SQLquery.

Example:
Write a query to retrieve only those records of employees fromthe employees table where
the designation is 'Project Manager' and the City to which the employee belongs to is Mumbai.
SELECT * FROMemployees WHERE City = ‘Mumbai’ AND Designation = ‘Project Manager’;
2. SQLOR OPERATOR :
The SQLOR operator is used with the where clause in an SQLQuery. ANDoperator in SQL
returns only those records that satisfy any of the conditions in the SQLquery.

Example:
Write a query to retrieve only those records of employees fromthe employees table where
the employee's designation is 'SystemEngineer' or the city to which the employee belongs is Mumbai.
SELECT * FROMemployees WHERE Designation = ‘SystemEngineer’ OR City = ‘Mumbai’;
3. SQLNOT OPERATOR :
NOT operator in SQLshows those records fromthe table where the criteria is not met.
NOT operator is used with where clause in a SELECT query.

Example:
Write a query to retrieve only those records of employees fromthe employees table where
the employee's designation is not Project Manager.
SELECT * FROMemployees WHERE NOT Designation = ‘Project Manager’;
4. SQLBETWEENOPERATOR :
This operator displays the records which fall between the given ranges in the SQL
query. The results of the BETWEENoperator include begin and end values of the given
range.
Example:
Write a query to retrieve only those records of an employee fromthe employees table
where employee salary lies between 50000 to 90000.
SELECT * FROMemployees WHERE Salary BETWEEN 50000 AND 90000;

5. SQLINOPERATOR :
When we want to check for one or more than one value in a single SQLquery, we use IN
operator with the WHERE clause in a SELECT query.
Example:
Write a query to retrieve only those records of employees fromthe employees table
where the city to which the employee belongs to iseither Mumbai, Bangalore, or Pune.
SELECT * FROMemployees WHERE City IN (‘Mumbai’, ‘Bangalore’, ‘Pune’);

6. SQLLIKE OPERATOR :
LIKE Operator in SQLdisplays only those data fromthe table which matches the pattern
specified in the query. Percentage (%) and underscore (_) are the two wildcard operators
used with LIKE Operator to performpattern matching tasks.
Example:
Write a query to retrieve only those records of employees fromthe employees table
whose salary starts with the digit 5.
SELECT * FROMemployees WHERE Salary LIKE ‘5%’;

SQLSet Operation:
The SQLSet operation is used to combine the two or more SQLSELECT statements.

Types of Set Operation


1. Union
2. UnionAll
3. Intersect
4. Minus
1. Union
The SQLUnion operation is used to combine the result of two or more SQLSELECT queries.
In the union operation, all the number of datatype and columns must be same in both the
tables on which UNIONoperation is being applied.
The union operation eliminates the duplicate rows fromits result set.
Syntax :
SELECT column_name FROMtable1 UNION SELECT column_name FROMtable2;
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
SELECT column_name FROMtable1 UNION ALL SELECT column_name FROMtable2;

3. Intersect
It is used to combine two SELECT statements. The Intersect operation returns the common
rows fromboth the SELECT statements.
In the Intersect operation, the number of datatype and columns must be the same.
It has no duplicates and it arranges the data in ascending order by default.
Syntax:
SELECT column_name FROMtable1 INTERSECT SELECT column_name FROMtable2;

4. Minus
It combines the result of two SELECT statements. Minus operator is used to display the
rows which are present in the first query but absent in the second query.
It has no duplicates and data arranged in ascending order by default.
Syntax:
SELECT column_name FROMtable1 MINUS SELECT column_name FROMtable2;

Aggregate Functions:
SQLaggregation function is used to performthe calculations on multiple rows of a single
column of a table. It returns a single value.
1. COUNT FUNCTION
COUNT function is used to Count the number of rows in a database table. It can work on
both numeric and non-numeric data types.
COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.
Syntax :
SELECT COUNT(COLUMNNAME) FROMTABLE_NAME ;
2. SUMFunction
Sumfunction is used to calculate the sumof all selected columns. It works on numeric
fields only.
Syntax :
SELECT SUM(COLUMNNAME) FROMTABLE_NAME ;

3. AVGFunction
The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.
Syntax :
SELECT AVG(COLUMNNAME) FROMTABLE_NAME ;
4. MAXFunction
MAX function is used to find the maximumvalue of a certain column. This function
determines the largest value of all selected values of a column.
Syntax :
SELECT MAX(COLUMNNAME) FROMTABLE_NAME ;
5. MINFunction
MINfunction is used to find the minimumvalue of a certain column. This function
determines the smallest value of all selected values of a column.

Syntax :
SELECT MIN(COLUMNNAME) FROMTABLE_NAME ;

Constraintsin SQL:
SQLconstraints are used to specify rules for the data in a table. Constraintsare used to limit
the type of data that can go into a table.

Constraints available in SQLare:


1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGNKEY
5. CHECK
6. DEFAULT
1. NOT NULL
NULLmeans empty, i.e., the value is not available.
Whenever a table's column is declared as NOT NULL, then the value for that column cannot
be empty for any of the table's records.
Syntax :
CREATE TABLE TableName (ColumnName1 datatype NOT NULL, ColumnName2 datatype,…., Col
umnNameN datatype);

2. UNIQUE
Duplicate values are not allowed in the columns to which the UNIQUE constraint is applied.
The column with the unique constraint will always contain a unique value.
This constraint can be applied to one or more than one column of a table, which means
more than one unique constraint can exist on a single table.
Syntax :
CREATE TABLE TableName (ColumnName1 datatype UNIQUE, ColumnName2 datatype,…., Colu
mnNameN datatype);
3. PRIMARY KEY
PRIMARY KEY Constraint is a combination of NOT NULLand Unique constraints.
NOT NULLconstraint and a UNIQUE constraint together forms a PRIMARY constraint.
Syntax :
CREATE TABLE TableName (ColumnName1 datatype PRIMARY KEY, ColumnName2 datatype,….,
ColumnNameN datatype);
4. FOREIGNKEY
Aforeign key is used for referential integrity.
When we have two tables, and one table takes reference fromanother table, i.e., the same
column is present in both the tables and that column acts as a primary key in one table.
That particular column will act as a foreign key in another table.
Syntax :

CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY KEY, ColumnNameN Datatyp


e(SIZE), FOREIGN KEY( ColumnName ) REFERENCES PARENT_TABLE_NAME(Primary_Key_Colu
mnName));
5. CHECK
Whenever a check constraint is applied to the table's column, and the user wants to insert
the value in it, then the value will first be checked for certain conditions before inserting
the value into that column.
Syntax :
CREATE TABLE TableName (ColumnName1 datatype CHECK (ColumnName1 Condition), Column
Name2 datatype,…., ColumnNameN datatype);

6. DEFAULT
Whenever a default constraint is applied to the table's column, and the user has not
specified the value to be inserted in it, then the default value which was specified while applying
the default constraint will be inserted into that particular column.
Syntax :
CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value, ColumnName2 datatype,…., Colum
nNameN datatype);

Viewsin SQL
Views in SQLare considered as a virtual table. Aview also contains rows and columns.
To create the view, we can select the fields fromone or more tables present in the
database.
Aview can either have specific rows based on certain condition or all the rows of a table.

1. Creating view
Aview can be created using the CREATE VIEWstatement. We can create a view froma
single table or multiple tables.
Syntax:
CREATE VIEWview_name AS SELECT column1, column2..... FROMtable_name WHERE conditi
on;

2. Creating View froma single table


In this example, we create a View namedDetailsViewfromthe table Student_Detail.
Syntax:
CREATE VIEWDetailsView AS SELECT NAME, ADDRESS FROMStudent_Details WHERE STU_ID
< 4;

3. Creating View frommultiple tables


View frommultiple tables can be created by simply include multiple tables in the SELECT
statement.

Syntax:
CREATE VIEWMarksView AS SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student
_Marks.MARKS FROMStudent_Detail, Student_Mark WHERE Student_Detail.NAME = Student
_Marks.NAME;

4. Deleting View
Aview can be deleted using the Drop View statement.
Syntax :
DROP VIEWview_name;

SQLSubQuery
ASubquery is a query within another SQLquery and embedded within the WHERE clause.

1. Subqueries with the Select Statement


SQLsubqueries are most frequently used with the Select statement.
Syntax :
SELECT column_name FROMtable_name WHERE column_name expression operator ( SELEC
T column_name fromtable_name WHERE ... );

2. Subqueries with the INSERT Statement


SQLsubquery can also be used with the Insert statement. In the insert statement, data
returned fromthe subquery is used to insert into another table.
Syntax:
INSERT INTO table_name (column1, column2, column3....) SELECT * FROMtable_name WH
ERE VALUE OPERATOR ;

3. Subqueries with the UPDATE Statement


The subquery of SQLcan be used in conjunction with the Update statement. When a
subquery is used with the Update statement, then either single or multiple columns in a table can be
updated.

Syntax:
UPDATE table SET column_name = new_value WHERE VALUE OPERATOR (SELECT COLUMN_
NAME FROMTABLE_NAME WHERE condition);

4. Subqueries with the DELETE Statement


The subquery of SQLcan be used in conjunction with the Delete statement just like any
other statements mentioned above.
Syntax :
DELETE FROMTABLE_NAME WHERE VALUE OPERATOR (SELECT COLUMN_NAME FROMTABLE_NAME
WHERE condition);

You might also like