Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Dbms Unit III

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 56

UNIT-III

Part-A
Basics of SQL:
 SQL, pronounced "sequel" (or S-Q-L, if you prefer) is a
standard language for accessing and manipulating
databases.
What is SQL?
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
• SQL became a standard of the American National
Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in
1987.
Applications of SQL:
• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a database
• SQL can create views in a database
• SQL can set permissions on tables, procedures, and views
DDL

• Data Definition Language (DDL) statements are used to define the database structure
or schema. Data Definition Language describes how the data should exist in the
database, therefore language statements like CREATE TABLE or ALTER TABLE
belong to the DDL. DDL is about "metadata".

• DDL includes commands such as CREATE, ALTER, and DROP statements.DDL are
used to CREATE, ALTER, OR DROP the database objects (Table, Views, Users).

• Data Definition Language (DDL) is used in different statements :


• CREATE - to create objects in the database
• ALTER - alters the structure of the database
• DROP - delete objects from the database
• TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
• COMMENT - add comments to the data dictionary
• RENAME - rename an object
A) CREATE TABLE
Syntax:
CREATE TABLE table_name(
Col_name1 datatype(),
Col_name2 datatype(),…
Col_namen datatype(),
);
Example: Here, we are creating a sample table.
CREATE TABLE Student
(
id int,
name varchar(50),
mobilenumber int
);
B) ALTER TABLE(Alters table by adding/deleting columns)
1) ADD
Syntax:
ALTER TABLE table_name
ADD Col_name datatype()...;
Example: Here, we are adding a new column to the existing table.
ALTER TABLE DDL ADD COLUMN DDL_Example varchar(50);
C) DROP TABLE(Deletes table permanently from database)
Syntax:
DROP Table name;
Example: Used to drop a table.
DROP TABLE DDL;
D) Truncate(used to delete all the rows(records) or particular row from the table but
table body will remain)
Syntax: Truncate table table_name;
E) COMMENT
Add comments to the data dictionary
F) RENAME
Rename a table
Syntax:
RENAME table table_name to new table_name
DML:
• DML is short name of Data Manipulation Language which deals
with data manipulation and includes most common SQL statements
such SELECT, INSERT, UPDATE, DELETE, etc., and it is used to
store, modify, retrieve, delete and update data in a database.
• SELECT - retrieve data from a database
• INSERT - insert data into a table
• UPDATE - updates existing data within a table
• DELETE - Delete all records from a database table
• DCL is short name of Data Control
Language which includes commands such as
GRANT and mostly concerned with rights,
permissions and other controls of the
database system.
• GRANT - allow users access privileges to the
database
• REVOKE - withdraw users access privileges
given by using the GRANT command
DCL:
• DCL is short name of Data Control Language which includes
commands such as GRANT and mostly concerned with rights,
permissions and other controls of the database system.
• GRANT - allow users access privileges to the database
• REVOKE - withdraw users access privileges given by using the
GRANT command
TCL:
• TCL is short name of Transaction Control Language which deals
with a transaction within a database.
• COMMIT - commits a Transaction
• ROLLBACK - rollback a transaction in case of any error occurs
• SAVEPOINT - to rollback the transaction making points within
groups
• SET TRANSACTION - specify characteristics of the transaction
Constraints:
• Constraints are the rules enforced on the data columns of a
table. These are used to limit the type of data that can go into a
table. This ensures the accuracy and reliability of the data in
the database.
• Constraints could be either on a column level or a table level.
The column level constraints are applied only to one column,
whereas the table level constraints are applied to the whole
table.
Following are some of the most commonly used constraints
available in SQL.
• NOT NULL - Ensures that a column cannot have a NULL value.
If we specify a field in a table to be NOT NULL. Then the field will never accept
null value.
CREATE TABLE Student ( ID int(6) NOT NULL, NAME varchar(10) NOT
NULL, ADDRESS varchar(20) );

• UNIQUE - Ensures that all values in a column are different. i.e. for a
particular column, all the rows should have unique values. We can have
more than one UNIQUE columns in a table.
CREATE TABLE Student ( ID int(6) NOT NULL UNIQUE, NAME
varchar(10), ADDRESS varchar(20) );

• CHECK - Ensures that all values in a column satisfies a specific


condition.

CREATE TABLE Student ( ID int(6) NOT NULL, NAME varchar(10)


NOT NULL, AGE int NOT NULL CHECK (AGE >= 18) );
PRIMARY KEY
• Primary Key is a field which uniquely identifies each row in
the table.
• If a field in a table as primary key, then the field will not be
able to contain NULL values as well as all the rows should
have unique values for this field.
CREATE TABLE Student ( ID int(6) NOT NULL UNIQUE,
NAME varchar(10), ADDRESS varchar(20), PRIMARY
KEY(ID) );
FOREIGN KEY
• Foreign Key is a field in a table which uniquely identifies each
row of a another table. That is, this field points to primary key
of another table.
Syntax:
CREATE TABLE Orders ( O_ID int NOT NULL, ORDER_NO
int NOT NULL, C_ID int, PRIMARY KEY (O_ID),
FOREIGN KEY (C_ID) REFERENCES Customers(C_ID) )
• DEFAULT - Sets a default value for a column when no value
is specified.
• This constraint is used to provide a default value for the fields.

For example, the below query will create a table named


Student and specify the default value for the field AGE as 18.
CREATE TABLE Student ( ID int(6) NOT NULL, NAME
varchar(10) NOT NULL, AGE int DEFAULT 18 );
• INDEX - Used to create and retrieve data from the database
very quickly
IN Operator:
• The IN operator allows you to specify multiple values in a
WHERE clause.
• The IN operator is a shorthand for multiple OR conditions.
IN Syntax
SELECT column_name(s) FROM table_name
WHERE column_name IN (value1, value2, ...);
Example:
SELECT name from students
WHERE city IN (‘hyd’,’bangalore’,chennai’);
Aggregate Functions:
• In database management an aggregate function is a function where the
values of multiple rows are grouped together as input on certain criteria to
form a single value of more significant meaning.
Various Aggregate Functions
1) Count()
The COUNT function returns the total number of values in the specified field.
It works on both numeric and non-numeric data types.
SELECT COUNT(`movie_id`) FROM `movierentals` WHERE `movie_id` =
2;
2) Sum()
SUM function which returns the sum of all the values in the specified
column. SUM works on numeric fields only. Null values are excluded
from the result returned.
SELECT SUM(`amount_paid`) FROM `payments`;
3) Avg()
AVG function returns the average of the values in a specified
column. Just like the SUM function, it works only on
numeric data types.
SELECT AVG(`amount_paid`) FROM `payments`;
4) Min()
The MIN function returns the smallest value in the specified
table field.
SELECT MIN(`year_released`) FROM `movies`;
5.Max();
The MAX function is the opposite of the MIN function.
It returns the largest value from the specified table field.
SELECT MAX(`year_released`) FROM `movies`;
Built-in functions:
• Built-In functions are used in SQL SELECT expressions to
calculate values and manipulate data. These functions can be
used anywhere expressions are allowed.
• In SQL a built-in function is a piece for programming that takes
zero or more inputs and returns a value.
Numeric Functions:
Numeric Functions are used to perform operations on numbers
and return numbers.
Following are the numeric functions defined in SQL:
1.ABS(): It returns the absolute value of a number.
• Syntax: SELECT ABS(-243.5);Output: 243.5
2. ACOS(): It returns the cosine of a number.
• Syntax: SELECT ACOS(0.25);Output: 1.318116071652818
3. ASIN(): It returns the arc sine of a number.
Syntax: SELECT ASIN(0.25);Output: 0.25268025514207865
4. ATAN(): It returns the arc tangent of a number.
Syntax: SELECT ATAN(2.5);Output: 1.1902899496825317
5. CEIL(): It returns the smallest integer value that is greater than or equal
to a number.
Syntax: SELECT CEIL(25.75);Output: 26
6. CEILING(): It returns the smallest integer value that is greater than or
equal to a number.
Syntax: SELECT CEILING(25.75);Output: 26
7. COS(): It returns the cosine of a number.
Syntax: SELECT COS(30);Output: 0.15425144988758405
8. COT(): It returns the cotangent of a number.
Syntax: SELECT COT(6);Output: -3.436353004180128
9. DEGREES(): It converts a radian value into degrees.
Syntax: SELECT DEGREES(1.5);Output: 85.94366926962348
10. DIV(): It is used for integer division.
Syntax: SELECT 10 DIV 5;Output: 2
11. EXP(): It returns e raised to the power of number.
Syntax: SELECT EXP(1);Output: 2.718281828459045
12. FLOOR(): It returns the largest integer value that is less than or equal to a
number.
Syntax: SELECT FLOOR(25.75);Output: 25
13. GREATEST(): It returns the greatest value in a list of expressions.
Syntax: SELECT GREATEST(30, 2, 36, 81, 125);Output: 125
14. LEAST(): It returns the smallest value in a list of expressions.
• Syntax: SELECT LEAST(30, 2, 36, 81, 125);
Date Functions
The following table lists the most important built-in date functions in SQL
• GETDATE()Returns the current date and time
Select getdate() as currentdatetime
• DATEPART()Returns a single part of a date/time
Select datepart(day, getdate()) as currentdate
• DATEADD()Adds or subtracts a specified time interval from a date
Select dateadd(day, 10, getdate()) as after10daysdatetimefromcurrentdatetime
• DATEDIFF()Returns the time between two dates
DATEDIFF(datepart, startdate, enddate)
• CONVERT()Displays date/time data in different formats
SELECT CONVERT(VARCHAR(19),GETDATE()) SELECT
CONVERT(VARCHAR(10),GETDATE(),10) SELECT
CONVERT(VARCHAR(10),GETDATE(),110)
String Functions:
String functionsare used to perform a operation on input string and
return an output string.
Following are the string functions defined in SQL:
1. ASCII(): This function is used to find the ASCII value of a
character.
• Syntax: SELECT ascii('t'); Output: 116.
2. CHAR_LENGTH(): Doesn’t work for SQL Server. Use LEN() for
SQL Server. This function is used to find the length of a word.
• Syntax: SELECT char_length('Hello!'); Output: 6
3. CHARACTER_LENGTH(): Doesn’t work for SQL Server. Use
LEN() for SQL Server. This function is used to find the length of a
line.
• Syntax: SELECT CHARACTER_LENGTH('geeks for geeks');
Output: 15
4. CONCAT(): This function is used to add two words or strings.
Syntax: SELECT 'Geeks' || ' ' || 'forGeeks' FROM dual; Output:
‘GeeksforGeeks’
5. CONCAT_WS(): This function is used to add two words or strings
with a symbol as concatenating symbol.
Syntax: SELECT CONCAT_WS('_', 'geeks', 'for', 'geeks'); Output:
geeks_for_geeks
6. FORMAT(): This function is used to display a number in the given
format.
Syntax: Format("0.981", "Percent"); Output: ‘98.10%’
7. LCASE(): This function is used to convert the given string into
lower case.
Syntax: LCASE ("GeeksFor Geeks To Learn"); Output:
geeksforgeeks to learn
8. LEFT(): This function is used to SELECT a sub string from the left
of given size or characters.
Syntax: SELECT LEFT('geeksforgeeks.org', 5); Output: geeks
SET Operations:
SQL supports few Set operations which can be performed on the
table data. These are used to get meaningful results from data
stored in the table, under different special conditions.
• UNION
• UNION ALL
• INTERSECT
• MINUS or EXCEPT
1. UNION Operation
• UNION is used to combine the results of two or
more SELECT statements. However it will eliminate duplicate
rows from its result set.
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;
2.Union All
Union All operation is equal to the Union operation. It returns the
set without removing duplication and sorting the data.
SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2;
3. Intersect
It is used to combine two SELECT statements. The Intersect
operation returns the common rows from both the SELECT
statements.
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;
4. Minus or Except:
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.
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;
UNIT-III
Part-B
Sub query:
A query with in another query
Outer query-main query
Inside-subquery
You can use Subquery with SELECT,
UPDATE, INSERT, DELETE statements
along with the operators like =, <, >,
>=, <=, IN, BETWEEN, etc.
Syntax:
SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHER
E condition );
Sub query is enclosed with Parenthesis();
Sub queries are not dependent on outer query
Co-related sub query:

• The outer query will get executed first and for


every row of outer query, inner query will get
executed. So the inner query will get executed
as many times as no.of rows in result of the
outer query.
• The outer query output can use the inner query
output for comparison. This means inner query
and outer query dependent on each other.
Syntax:
SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHER
E condition );
Group BY:
The GROUP BY statement groups
rows that have the same values.
The GROUP BY statement is often
used with aggregate functions
(COUNT, MAX, MIN, SUM, AVG)
to group the result-set by one or more
columns.
Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
Having:
The HAVING Clause enables you to specify
conditions that filter which group results
appear in the results.
Syntax:
SELECT column_name(s)
FROM table_name
GROUP BY column_name(s)
Having condition;
Order BY:
Sorts the data( in ascending or descending)
based on the requirements
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
Order by column_name asc or desc;
Exists:
Exists operator tests the existence of a record in
a subquery
Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WH
ERE condition);
ALL:
The ALL operator returns true if all of the sub
query values meet the condition.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WH
ERE condition);
ANY:
The ANY operator returns true if any of the sub
query values meet the condition.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WH
ERE condition);
Transaction control commands:
 Transaction Control Language(TCL) commands
are used to controls or manage transactions in
the database.
 These are used to manage the changes made
to the data in a table by DML statements.
TCL commands are
1.Commit 2.Savepoint 3.Roll-back
Properties of Transactions:
Transactions have the following four standard properties,
usually referred to by the acronym ACID.
• Atomicity − ensures that all operations within the work
unit are completed successfully. Otherwise, the transaction
is aborted at the point of failure and all the previous
operations are rolled back to their former state.
• Consistency − ensures that the database properly changes
states upon a successfully committed transaction.
• Isolation − enables transactions to operate independently
of and transparent to each other.
• Durability − ensures that the result or effect of a
committed transaction persists in case of a system failure.
Commit:
 COMMIT command is used to permanently
save any transaction into the database.
Syntax:
Begin Transaction
Insert into table-name values(1,’a’,20);
Commit;
Save-point:
SAVEPOINT command is used to temporarily
save a transaction so that you can rollback to
that point whenever required.
Syntax:
Begin Transaction
Insert into table-name values(1,’a’,20);
Savepoint A;
Rollback:
This command restores the database to last
commited state. It is also used
with SAVEPOINT command to jump to a savepoint
in an ongoing transaction.
Syntax:
Begin Transaction
Insert into table-name values(1,’a’,20);
Savepoint A;
Rollback A;
Commit:
Cursors:
 Cursor is a Temporary Memory or Temporary
Work Station.
 It is Allocated by Database Server at the Time
of Performing DML operations on Table by
User.
 Cursors are used to store Database Tables.
There are 2 types of Cursors: Implicit Cursors,
and Explicit Cursors. These are explained as
following below.
• Implicit Cursors:
Implicit Cursors are also known as Default
Cursors of SQL SERVER. These Cursors are
allocated by SQL SERVER when the user
performs DML operations.
• Explicit Cursors :
Explicit Cursors are Created by Users
whenever the user requires them. Explicit
Cursors are used for Fetching data from Table
in Row-By-Row Manner.
SQL cursor life cycle
How to create Explicit Cursor:
1.Declare a cursor
DECLARE cursor_name CURSOR FOR
select_statement;
2.Open:
Open cursor_name;
3.Fetch:
BEGIN FETCH NEXT FROM cursor_name; END;
Fetching the data can be
• FIRST is used to fetch only the first row from
cursor table.
LAST is used to fetch only last row from cursor
table.
NEXT is used to fetch data in forward direction
from cursor table.
PRIOR is used to fetch data in backward direction
from cursor table.
ABSOLUTE n is used to fetch the exact nth row
from cursor table.
• Close cursor connection.
Syntax : CLOSE cursor_name
• Deallocate cursor memory.
Syntax : DEALLOCATE cursor_name
Stored Procedure:
 A stored procedure in SQL is a type of code in
SQL that can be stored for later use and can be
used many times.
 whenever you need to execute the query,
instead of calling it you can just call the stored
procedure.
 Values or parameters can be passed through
stored procedures.
 Stored Procedures are created to perform one
or more DML operations on Database.
Syntax:Creating
CREATE PROCEDURE PROCEDURE_NAME
AS
SQL_STATEMENT
GO
Executing
Exec PROCEDURE_NAME
Passing parameters
create procedure selectcustomer @address
varchar(18),@city varchar(18)
AS
select * from customer where address=@address
AND city=@city
GO

• exec selectcustomer @address='jay


nagar',@city='bangalore';
Triggers:
• A trigger is a stored procedure in database
which automatically invokes whenever a
special event in the database occurs.
• For example, a trigger can be invoked when a
row is inserted into a specified table or when
certain table columns are being updated.
create trigger[trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]

create trigger [trigger_name]: Creates or replaces an existing trigger with the


trigger_name.
[before | after]: This specifies when the trigger will be executed.
{insert | update | delete}: This specifies the DML operation.
on [table_name]: This specifies the name of the table associated with the trigger.
[for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for
each row being affected.
[trigger_body]: This provides the operation to be performed as trigger is fired
Example:
1.create table Student(id int,name varchar(18),subj1
int,subj2 int,subj3 int,total int,percentage int);
2.create trigger stud_marks
before INSERT
on Student
for each row
set Student.total = Student.subj1 + Student.subj2 +
Student.subj3, Student.percentage = Student.total * 60 /
100;
3.Trigger execute
4.insert into Student values(0, "ABCDE", 20, 20, 20, 0, 0);
1 row affected
5.Select * from student:
tid | name | subj1 | subj2 | subj3 | total | per |
+-----+-------+-------+-------+-------+-------+------+ |
100 | ABCDE | 20 | 20 | 20 | 60 | 36 |

You might also like