0% found this document useful (0 votes)
10 views47 pages

Dbms Unit 3 Part1

SQL, or Structured Query Language, is a standard language used for managing relational databases, allowing users to create, retrieve, and manipulate data. It includes various commands categorized into DDL, DQL, DML, DCL, and TCL, each serving different functions such as defining database structures and manipulating data. Key operations include creating databases and tables, inserting, updating, and deleting records, as well as using aggregate functions for data analysis.

Uploaded by

shinchanm1809
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views47 pages

Dbms Unit 3 Part1

SQL, or Structured Query Language, is a standard language used for managing relational databases, allowing users to create, retrieve, and manipulate data. It includes various commands categorized into DDL, DQL, DML, DCL, and TCL, each serving different functions such as defining database structures and manipulating data. Key operations include creating databases and tables, inserting, updating, and deleting records, as well as using aggregate functions for data analysis.

Uploaded by

shinchanm1809
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

What is SQL

• Structured Query Language is a standard Database language which is


used to create, maintain and retrieve the relational database.
• Following are some interesting facts about SQL:
• SQL is case insensitive. But it is a recommended practice to use
keywords (like SELECT, UPDATE, CREATE, etc) in capital letters and use
user defined things (liked table name, column name, etc) in small
letters.
• We can write comments in SQL using “–” (double hyphen) at the
beginning of any line.
• SQL is the programming language for relational databases (explained
below) like MySQL, Oracle, Sybase, SQL Server, Postgre, etc. Other non-
relational databases (also called NoSQL) databases like MongoDB,
DynamoDB, etc do not use SQL
• Although there is an ISO standard for SQL, most of the
implementations slightly vary in syntax. So we may encounter queries
that work in SQL Server but do not work in MySQL.
• What is Relational Database?
– Relational database means the data is stored as well as retrieved
in the form of relations (tables).
• These are some important terminologies that are used in terms of
relation.
• Attribute: Attributes are the properties that define a
relation. e.g.; ROLL_NO, NAME etc.
• Tuple: Each row in the relation is known as tuple.
• Degree: The number of attributes in the relation is known as
degree of the relation.
• Cardinality: The number of tuples in a relation is known as
cardinality.
• Column: Column represents the set of values for a
particular attribute.
• The queries to deal with relational database can
be categories as SQL commands

• These SQL commands are mainly categorized into


Five categories as:

– DDL – Data Definition Language


– DQL– Data Query Language
– DML – Data Manipulation Language
– DCL – Data Control Language
– TCL – Transaction Control Language.
Types of SQL Commands

SQL Commands

DDL DQL DML DCL TCL

INSERT
CREATE GRANT
SELECT COMMIT
UPDATE
ALTER

DELETE
DROP REVOKE ROLLBACK

MERGE
RENAME

CALL
SAVEPOINT
TRUNCATE

COMMENT
Basic SQL query
DDL commands
• Data Definition Language (DDL) or Schema Definition Language,
statements are used to define the database structure or schema.
• These statements handle the design and storage of database
objects.
CREATE:
CREATE DATABASE:
The CREATE DATABASE statement is used to create a new SQL
database.
Syntax:
CREATE DATABASE databasename;
Example :
• The following SQL statement creates a database called "testDB":

CREATE DATABASE testDB ;

CREATE TABLE:
The CREATE TABLE statement is used to create a new table in a
database.
Syntax:
CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype, .... );

• The column parameters specify the names of the columns of the


table.
• The datatype parameter specifies the type of data the column can
hold (e.g. varchar, integer, date, etc.).
Example:
The following example creates a table called "Persons" that contains
five columns: PersonID, LastName, FirstName, Address, and City:

CREATE TABLE Persons ( PersonID int, LastName varchar(255),


FirstName varchar(255), Address varchar(255), City varchar(255) );

DESC Statement (Describe Table):


SQL DESC statement use for describe the list of column definitions for
specified table. You can use either DESC or DESCRIBE statement.
Syntax:
Describe table_name;
Example:
Describe persons ;

Field Type Null Key Default Extra

PersonID int YES NULL


LastName varchar(255) YES NULL

Firstname varchar(255) YES NULL


Address varchar(255) YES NULL
City varchar(255) YES NULL

Field indicates the column name, Type is the data type for the
column, NULL indicates whether the column can contain NULL
values, Key indicates whether the column is indexed, and Default
specifies the column's default value. Extra displays special
information about columns
ALTER TABLE:
The ALTER TABLE statement is used to add, delete, or modify columns
in an existing table. The ALTER TABLE statement is also used to add
and drop various constraints on an existing table.
ALTER TABLE - ADD Column
- To add a column in a table.
Syntax:
ALTER TABLE table_name ADD column_name datatype ;
Example : The following SQL adds an "Email" column to the "Persons"
table:
ALTER TABLE Persons ADD Email varchar(255) ;
Add Multiple Columns in table:
ALTER TABLE table_name ADD ( column_name1 datatype[(size)],
column_name2 datatype[(size)], ... );

ALTER TABLE - DROP COLUMN


It is used to delete a column in a table
Syntax:
ALTER TABLE table_name DROP COLUMN column_name;

Example: The following SQL deletes the "Email"


column from the "Persons" table:

ALTER TABLE Persons DROP COLUMN Email;


MODIFY EXISTING COLUMN IN TABLE:
To change the data type of a column in a table
Syntax: ALTER TABLE table_name MODIFY COLUMN column_name datatype;
RENAME THE EXISTING COLUMN IN A TABLE:
Syntax:
ALTER table table_name change old_column_name new_column_name datatype;

Example:
ALTER table persons change city district varchar(50);
RENAME:
RENAME command is used to set a new name for
any existing table.
Syntax (Rename Table):
RENAME TABLE old_table_name to new_table_name ;
Example:
RENAME TABLE persons to students_info;

The above query will rename the table persons to


students_info.
TRUNCATE:
• It is used to delete all the rows from the table
and free the space containing the table.
Syntax:
TRUNCATE TABLE table_name;

Example:
TRUNCATE TABLE Persons;

DROP TABLE / DATABASE:


The DROP TABLE / DATABASE statement is used to
drop an existing table in a database or a database.
Syntax:
DROP TABLE table_name;

Example :The following SQL statement drops the


existing table "Person":
DROP TABLE Person;
DML Commands
• The SQL commands that deals with the manipulation of data
present in the database belong to DML or Data Manipulation
Language and this includes most of the SQL statements.
• DML is responsible for all forms of data modification in a database.
INSERT: The insert statement is used to add new row to a table.
Syntax:
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N) VALUES (value1, value2, value3, ....
valueN );

OR

INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN);


Example
Insert the values into the following table (person).
Field Type Null Key Default Extra
ID int NO NULL
Name varchar(20) YES NULL
Age int YES NULL
Address varchar(20) YES NULL
SALARY int YES NULL

INSERT into person values (1,”ram”,32,”Chennai”,2000),(2,”sam”,28,”Hyd”,2500),


(3,”Henry”,30,”Bangalore”,5000),(4,”Adam”,29,”Pune”,6500),(5,”Alice”,25,”Delhi”,8500);
SELECT:
SELECT statement is used to fetch the data from a database table
which returns this data in the form of a result table. These result
tables are called result-sets.
Syntax:
SELECT column1, column2, columnN FROM table_name;
Example:
To fetch all the fields of the table,
SELECT * FROM person ;
ID Name Age Address SALARY

1 Ram 32 Chnnai 2000


2 Sam 28 Hyd 2500
3 Henry 30 Banglore 5000
4 Adam 29 Pune 6500
5 Alice 25 Delhi 8500
To fetch selected fields (ID, NAME) of the table,
SELECT ID, NAME FROM person;

ID Name
1 Ram
2 Sam
3 Henry
4 Adam
5 Alice

UPDATE
UPDATE Query is used to modify the existing records in a table. The WHERE clause with the
UPDATE query to update the selected rows, otherwise all the rows would be affected.
Syntax:
UPDATE table_name SET column1 = value1, column2 = value2...., columnN =
valueN WHERE [condition];
Example:
Update the ADDRESS for a customer whose ID number is 5 in the
table.
UPDATE person SET ADDRESS = “LONDON” WHERE ID = 5;
Now, the PERSON table would have the following records,
ID Name Age Address SALARY
1 Ram 32 Chnnai 2000
2 Sam 28 Hyd 2500
3 Henry 30 Banglore 5000
4 Adam 29 Pune 6500
5 Alice 25 LONDON 8500

To modify all the ADDRESS and the SALARY column values in the Person
table, not need to use the WHERE clause as the UPDATE query would be
enough as shown in the following code block.
UPDATE person SET ADDRESS = “LONDON” , SALARY = 5000;

ID Name Age Address SALARY


1 Ram 32 LONDON 5000
2 Sam 28 LONDON 5000
3 Henry 30 LONDON 5000
4 Adam 29 LONDON 5000
5 Alice 25 LONDON 5000

DELETE
DELETE Query is used to delete the existing records from a table.
You can use the WHERE clause with a DELETE query to delete the
selected rows, otherwise all the records would be deleted.
Syntax:
DELETE FROM table_name WHERE [condition];

Example The following code has a query, which will DELETE a


customer, whose ID is 5.
DELETE FROM person WHERE ID = 5;
Now, the person table would have the following records.
ID Name Age Address SALARY
1 Ram 32 LONDON 5000
2 Sam 28 LONDON 5000
3 Henry 30 LONDON 5000
4 Adam 29 LONDON 5000

To DELETE all the records from the Person table, no need to use the WHERE clause and the
DELETE query would be as follows –
DELETE FROM person;
UNION
The UNION operator is used to combine the
result-set of two or more SELECT statements.
• Each SELECT statement within UNION must
have the same number of columns.
• The columns must also have similar data
types.
• The columns in each SELECT statement must
also be in the same order
INTERSECT
The SQL INTERSECT clause/operator is used to combine two SELECT statements. But it
returns only common rows returned by the two SELECT statements.
Syntax:

SELECT column_name(s) FROM table1 {UNION / INSTERSECT} SELECT column_name(s)


FROM table2;

Except
The SQL EXCEPT clause/operator is used to combine two SELECT statements
and returns rows from the first SELECT statement that are not returned by
the second SELECT statement. This means EXCEPT returns only rows, which
are not available in the second SELECT statement.
Syntax :
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] EXCEPT
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]

Nested Query
• A Subquery or Inner query or a Nested query is a query within
another SQL query and embedded within the WHERE clause.
• A subquery is used to return data that will be used in the main
query as a condition to further restrict the data to be retrieved.
• Subqueries can be used with the SELECT, INSERT, UPDATE, and
DELETE statements along with the operators like =, , >=, <=, IN,
BETWEEN, etc.
• There are a few rules that subqueries must follow −
• Subqueries must be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause,
unless multiple columns are in the main query for the
subquery to compare its selected columns.
• An ORDER BY command cannot be used in a subquery,
although the main query can use an ORDER BY. The GROUP
BY command can be used to perform the same function as
the ORDER BY in a subquery.
• Subqueries that return more than one row can only be used
with multiple value operators such as the IN operator.
• A subquery cannot be immediately enclosed in a set function.
• The BETWEEN operator cannot be used with a subquery.
However, the BETWEEN operator can be used within the
subquery.
Subqueries with the SELECT Statement
Subqueries are most frequently used with the SELECT statement. The
basic syntax is as follows
Syntax:

SELECT column_name [, column_name ] FROM table1 [, table2 ] WHERE column_name


OPERATOR (SELECT column_name [, column_name ] FROM table1 [, table2 ] [WHERE])

Subqueries with the INSERT Statement


Subqueries also can be used with INSERT statements. The INSERT
statement uses the data returned from the subquery to insert into
another table. The selected data in the subquery can be modified
with any of the character, date or number functions.
The basic syntax is as follows
INSERT INTO table_name [ (column1 [, column2 ]) ] SELECT [ *|column1 [, column2 ] FROM
table1 [, table2 ] [ WHERE VALUE OPERATOR ]
Subqueries with the UPDATE Statement
The subquery can be used in conjunction with the UPDATE statement.
Either single or multiple columns in a table can be updated when
using a subquery with the UPDATE statement.
The basic syntax is as follows
UPDATE table SET column_name = new_value [ WHERE OPERATOR [ VALUE ] (SELECT
COLUMN_NAME FROM TABLE_NAME) [ WHERE) ]

Subqueries with the DELETE Statement


The subquery can be used in conjunction with the DELETE statement
like with any other statements mentioned above.
The basic syntax is as follows.

DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME


FROM TABLE_NAME) [ WHERE) ]
Aggregate Operators
To calculate aggregate values, one requires some aggregate operators
to perform this task. These operators run over the columns of a
relation. The total number of five aggregate operators is supported by
SQL and these are:
1. COUNT – To calculate the number of values present in a particular
column.
2. SUM – To calculate the sum of all the values present in a
particular column.
3. AVG – To calculate the average of all the values present in a
particular column.
4. MAX – To find the maximum of all the values present in a
particular column.
5. MIN – To find the minimum of all the values present in a
particular column.
SELECT <Function_Name> (<Parameter>) FROM <Table_Name>
For COUNT, SUM, and AVG- DISTINCT is specified in conjunction in
order to eliminate any duplicate data. But for MAX and MIN- DISTINCT
is not required to be specified as that will anyway not going to affect
the output.
Count Function:

• The COUNT function returns the total number of values in the


specified field. It works on both numeric and non-numeric data
types. All aggregate functions by default exclude nulls values before
working on the data.
• COUNT (*) is a special implementation of the COUNT function that
returns the count of all the rows in a specified table. COUNT (*) also
considers Nulls and duplicates.
Consider the table emp:
Eid Ename Dept Salary
1 Sam CSE 10000
2 Smith IT 20000
3 Ben CSE 30000
4 Victor IT 30000
5 Henry EEE 50000
6 John ECE Null

Example,
Select count(*) from emp;

Select (count(salary)) from emp;

5
Min Function

• The MIN function returns the smallest value in the specified table
field.
Example:
Select min(salary) from emp;
10000
Max Function

• The MAX function is the opposite of the MIN function. It returns


the largest value from the specified table field.
Example:
Select max(salary) from emp;
50000
Sum Function
The MySQL SUM function 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.
Example:
Select sum(salary) from emp;
140000
Avg Function
MySQL AVG function returns the average of the values in a specified
column. Just like the SUM function, it works only on numeric data
types.
Example:
Select avg(salary) from emp;
28000.0000
DISTINCT Keyword
The DISTINCT keyword that allows us to omit duplicates from our
results. This is achieved by grouping similar values together.
Example:
select sum(distinct(salary)) from emp;
110000
select count(distinct(salary)) from emp;
4
NULL values
• The SQL NULL is the term used to represent a missing value. A
NULL value in a table is a value in a field that appears to be blank.
• A field with a NULL value is a field with no value. It is very
important to understand that a NULL value is different than a zero
value or a field that contains spaces.
Syntax:
The basic syntax of NULL while creating a table.
SQL> CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR
(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY
DECIMAL (18, 2), PRIMARY KEY (ID) );
• Here, NOT NULL signifies that column should always accept an
explicit value of the given data type. There are two columns where
we did not use NOT NULL, which means these columns could be
NULL.
• A field with a NULL value is the one that has been left blank during
the record creation.
Example :
The NULL value can cause problems when selecting data. However,
because when comparing an unknown value to any other value, the
result is always unknown and not included in the results. You must
use the IS NULL or IS NOT NULL operators to check for a NULL value.
Consider the following CUSTOMERS table having the records as
shown below.

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kuashik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP
7 Muffy 24 Indore

Now, following is the usage of the IS NOT NULLoperator

SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS


WHERE SALARY IS NOT NULL;
This would produce the following result −

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kuashik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00

Now, following is the usage of the IS NULL operator.

SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS WHERE SALARY IS NULL;
This would produce the following result −

ID NAME AGE ADDRESS SALARY


6 Komal 22 MP
7 Muffy 24 Indore
Triggers
• Triggers are the SQL statements that are automatically executed when there is
any change in the database. The triggers are executed in response to certain
events(INSERT, UPDATE or DELETE) in a particular table.
• A trigger is a procedure that is automatically invoked by the DBMS in response to
specified changes to the database, and is typically specified by the DBA. A
database that has a set of associated triggers is called an active database. A
trigger description contains three parts:
Event: A change to the database that activates the trigger.
Condition: A query or test that is run when the trigger is activated.
Action: A procedure that is executed when the trigger is activated and its
condition is true.
Triggers are, in fact, written to be executed in response to any of the following events

• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
• A database definition (DDL) statement (CREATE, ALTER, or DROP)
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event
is associated.
For example, a trigger can be invoked when a row is inserted into a
specified table or when certain table columns are being updated.
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Explanation of syntax:
• 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.
BEFORE and AFTER of Trigger:
BEFORE triggers run the trigger action before the
triggering statement is run.
AFTER triggers run the trigger action after the
triggering statement is run.
Benefits of Triggers :
Triggers can be written for the following purposes
• Generating some derived column values
automatically
• Enforcing referential integrity
• Event logging and storing information on table
access
• Auditing
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions
• Example:
Mysql> create table Sales (sid int primary key, itemid
int, qtysold int, price int, total int);
mysql> insert into sales values(101,8,10,90,0);
mysql> select * from sales;

sid itemid qtysold price total

101 8 10 90 0
mysql> create trigger t1
before insert
on Sales
for each row
begin
set new.total=new.qtysold*new.price;
end;
mysql> insert into Sales values(102,9,10,180,0); mysql> select * from
Sales;
sid itemid qtysold price total
101 8 10 90 0
102 9 10 180 1800

Mysql> drop trigger t1;


Active Databases

• Active Database is a database consisting of set of triggers. These


databases are very difficult to be maintained because of the
complexity that arises in understanding the effect of these triggers.
In such database, DBMS initially verifies whether the particular
trigger specified in the statement that modifies the database) is
activated or not, prior to executing the statement.
• If the trigger is active then DBMS executes the condition part and
then executes the action part only if the specified condition is
evaluated to true. It is possible to activate more than one trigger
within a single statement.
• In such situation, DBMS processes each of the trigger randomly. The
execution of an action part of a trigger may either activate other
triggers or the same trigger that Initialized this action. Such types of
trigger that activates itself is called as ‘recursive trigger’. The DBMS
executes such chains of trigger in some pre-defined manner but it
effects the concept of understanding
Features of Active Database
1. It possess all the concepts of a conventional
database i.e. data modelling facilities, query
language etc.
2. It supports all the functions of a traditional
database like data definition, data manipulation,
storage management etc.
3. It supports definition and management of ECA
rules.
4. It detects event occurrence.
5. It must be able to evaluate conditions and to
execute actions.
6. It means that it has to implement rule execution.
Advantages
1. Enhances traditional database functionalities
with powerful rule processing capabilities.
2. Enable a uniform and centralized description of
the business rules relevant to the information
system.
3. Avoids redundancy of checking and repair
operations.
4. Suitable platform for building large and efficient
knowledge base and expert systems.

You might also like