Unit 3
Unit 3
The database developers and the users use this statement in SQL for creating the new
database in the database systems. It creates the database with the name which has
been specified in the Create Database statement.
In this syntax, Database_Name specifies the name of the database which we want to
create in the system. We have to type the database name in query just after the 'Create
Database' keyword.
Following are the most important points which are required to learn while creating a
database:
○ The database we want to create should be a simple and unique name, which can
be easily identified.
The same command is used in MySQL to create the new database for storing the
structured data.
There is no need to create the database in Oracle systems. In the Oracle database, we
can directly create the database tables.
Examples of Create Database statement in SQL
In this article, we took the following two examples which will help how to run and
perform the Create Database query in SQL:
Example 1:
This example creates the Student database. To create the Student database, you have
to type the following command in Structured Query Language:
When this query is executed successfully, then it will show the following output:
You can also verify that your database is created in SQL or not by using the following
query:
1. SHOW DATABASE ;
SQL does not allow developers to create the database with the existing database name.
Suppose if you want to create another Student database in the same database system,
then the Create Database statement will show the following error in the output:
So, firstly you have to delete the existing database by using the Drop Statement. You can
also replace the existing database with the help of Replace keyword.
If you want to replace the existing Student database, then you have to type the following
SQL query:
Example 2:
When this query is executed successfully, then it will show the following output:
You can also check that your database is created in SQL by typing the following query:
1. SHOW DATABASE ;
We know that SQL does not allow developers to create the database with the existing
database name.
Suppose, we want to create another Employee database in the same database system,
firstly, we have to delete the existing database using a drop statement, or we have to
replace the existing Employee database with the help of the 'replace' keyword.
To replace the existing Employee database with a new Employee database, we have to
type the following query in SQL:
DDL stands for Data Definition Language and refers to SQL commands used to create, modify, and
delete database structures such as tables, indexes, and views. DML stands for Data Manipulation
Language and refers to SQL commands used to insert, update, and delete data within a database.
DDL (Data Definition Language) is a type of SQL command used to define data structures and
modify data. It creates, alters, and deletes database objects such as tables, views, indexes, and
users. Examples of DDL statements include CREATE, ALTER, DROP and TRUNCATE.
DML (Data Manipulation Language) is a type of SQL command used to manipulate data in
a database. It inserts, updates, and deletes data from a database table. Examples of DML
statements include INSERT, UPDATE, and DELETE.
Syntax:
1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example:
1. 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
1. DROP TABLE table_name;
Example
1. 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.
Syntax:
EXAMPLE
1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
d. TRUNCATE: It is used to delete all the rows from the table and free the space
containing the table.
Syntax:
1. TRUNCATE TABLE table_name;
Example:
1. TRUNCATE TABLE EMPLOYEE;
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of
a table.
Syntax:
Or
For example:
b. UPDATE: This command is used to update or modify the value of a column in the
table.
Syntax:
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'
For example:
Explore the difference between DDL and DML commands in the below table.
Understand how DDL commands shape database structures, while DML
commands manipulate data within the database.
DDL DML
Changes made using DDL affect Changes made using DML affect the data
the structure of the database. stored in the database.
DDL statements are not DML statements are transactional,
transactional, meaning they meaning they can be rolled back if
cannot be rolled back. necessary.
DDL statements are typically DML statements are used during normal
used during the design and operation of a database.
setup phase of a database.
REVOKE: This command withdraws the user’s access privileges given by using the
GRANT command.
Syntax:
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
Advanced data manipulation using SQL
1. Data Transformation
Data obtained originally from a data source is often unprepared and messy. Data
transformation involves some processes like modifying and converting data types,
standardizing and normalizing data, and handling categorical data to make it fit for
insightful data analysis.
Consider a “student” table that has a “score” column. It stores numerical values of “text”
or VARCHAR type. In order to perform calculative analysis, you will need “integer” data
types. SQL offers CONVERT and CAST functions for data type conversion:
FROM student_db;
Suppose the “students” table has another column “gender”, but with variations like
“MALE”, “male”, “m”, “FEMALE”, “F”. This can make the data messy.
SELECT name,
CASE
ELSE ‘Unknown’
END AS new_gender
FROM students;
Handling conditional statements
Suppose you want to categorize student performance from the “score” column as ‘High,’
‘Medium,’ or ‘Low’, based on their scores:
CASE
ELSE ‘Low’
END AS score_category
FROM students;
3. Grouping data
SQL offers various functions for filtering and aggregating data to organize it according to a given
criteria.
The GROUP BY function is used along with SQL aggregate functions to group similar rows and
apply calculations to get the required results. Some common aggregate functions include SUM,
AVG, COUNT, MIN, and MAX.
Data Aggregation:
— to calculate sum of values for each group
FROM students
GROUP BY gender;
FROM students;
FROM students
GROUP BY age;
FROM students;
— to find minimum values in a column
FROM students;
4. SQL Unions
When combining multiple results based on similar sets—which may include the same
columns, the same order, or similar data types—you use the SQL UNION clause.
While UNION ALL permits duplicate records, the UNION clause only returns unique
records.
Let’s say there are two tables in a database, student_p and student_q, with the same
set of columns and different records, and you want to combine distinct rows from both of
the tables:
FROM student_p
UNION
FROM student_q;
5. Handling Time Series Data
Time series data includes TIMESTAMP, DATE, and DATETIME values, which are used
to keep track of time. Formatting time-based data is very crucial, as it can give you an
insightful analysis of data based on time. Time-based indexing improves query
performance and aids in query optimization for huge datasets.
To obtain time-based summary statistics such as daily, weekly, hourly, or annual results,
SQL aggregate functions such as SUM, AVG, and COUNT are used.
FROM sales
GROUP BY month
ORDER BY month;
6. JOIN Queries
Let’s create another table called Products. This is a table where the
students will buy the product.
create table products (
id int,
name varchar(100),
student_id int,
primary key (id)
);
insert into products values (1, 'LEGO', 2);
insert into products values (2, 'LEGO', 5);
insert into products values (3, 'Toy Train', 5);
insert into products values (4, 'Toy Train', 8);
insert into products values (5, 'Shirt', 10);
A JOIN Query is used when we have to query a column from a second
table. Normally there is a key from the first table that equates to a key
in the second table. It can be in the form of an ID or string.
● INNER JOIN
Inner Join is joining one or more tables and selecting the rows as long
as there is a match between both tables. It is like an INTERSECT.
Result:
● LEFT JOIN
LEFT JOIN selects all records from the left table and records that
match the right table.
SELECT s.first_name, s.last_name, p.name
From students s
LEFT JOIN products p
on p.student_id = s.id
This query will return all the records of the left table (students)
regardless of whether p.name is present. Notice that in that field p.name ,
it is null if there is no record of it.
● RIGHT JOIN
RIGHT JOIN selects all records from the right table and records that
match the left table.
FULL OUTER JOIN selects all records for both the left and right
tables.
Database Programming: Cursor
Cursor is a Temporary Memory or Temporary Work Station. It is Allocated by
Database Server at the Time of Performing DML(Data Manipulation Language)
operations on the Table by the User. Cursors are used to store Database Tables.
1: Declare Cursor
The first step is to declare the cursor using the below SQL statement:
We can declare a cursor by specifying its name with the data type CURSOR after the DECLARE
keyword. Then, we will write the SELECT statement that defines the output for the cursor.
2: Open Cursor
It's a second step in which we open the cursor to store data retrieved from the result set. We can
do this by using the below SQL statement:
1. OPEN cursor_name;
3: Fetch Cursor
It's a third step in which rows can be fetched one by one or in a block to do data manipulation
like insert, update, and delete operations on the currently active row in the cursor. We can do this
by using the below SQL statement:
We can also use the @@FETCHSTATUS function in SQL Server to get the status of the most
recent FETCH statement cursor that was executed against the cursor. The FETCH statement was
successful when the @@FETCHSTATUS gives zero output. The WHILE statement can be used
to retrieve all records from the cursor. The following code explains it more clearly:
1. WHILE @@FETCH_STATUS = 0
2. BEGIN
3. FETCH NEXT FROM cursor_name;
4. END;
4: Close Cursor
It's a fourth step in which the cursor should be closed after we finished work with a cursor. We
can do this by using the below SQL statement:
1. CLOSE cursor_name;
5: Deallocate Cursor
It is the fifth and final step in which we will erase the cursor definition and release all the system
resources associated with the cursor. We can do this by using the below SQL statement:
1. DEALLOCATE cursor_name;
○ Static Cursors
○ Dynamic Cursors
○ Forward-Only Cursors
○ Keyset Cursors
Static Cursors
The result set shown by the static cursor is always the same as when the cursor was first opened.
Since the static cursor will store the result in tempdb, they are always read-only. We can use the
static cursor to move both forward and backward. In contrast to other cursors, it is slower and
consumes more memory. As a result, we can use it only when scrolling is necessary, and other
cursors aren't suitable.
This cursor shows rows that were removed from the database after it was opened. A static cursor
does not represent any INSERT, UPDATE, or DELETE operations (unless the cursor is closed
and reopened).
Dynamic Cursors
The dynamic cursors are opposite to the static cursors that allow us to perform the data updation,
deletion, and insertion operations while the cursor is open. It is scrollable by default. It can detect
all changes made to the rows, order, and values in the result set, whether the changes occur
inside the cursor or outside the cursor. Outside the cursor, we cannot see the updates until they
are committed.
Forward-Only Cursors
It is the default and fastest cursor type among all cursors. It is called a forward-only cursor
because it moves only forward through the result set. This cursor doesn't support scrolling. It can
only retrieve rows from the beginning to the end of the result set. It allows us to perform insert,
update, and delete operations. Here, the effect of insert, update and delete operations made by the
user that affect rows in the result set are visible as the rows are fetched from the cursor. When the
row was fetched, we cannot see the changes made to rows through the cursor.
1. Forward_Only Keyset
2. Forward_Only Static
3. Fast_Forward
Keyset Driven Cursors
This cursor functionality lies between a static and a dynamic cursor regarding its ability to detect
changes. It can't always detect changes in the result set's membership and order like a static
cursor. It can detect changes in the result set's rows values as like a dynamic cursor. It can only
move from the first to last and last to the first row. The order and the membership are fixed
whenever this cursor is opened.
It is operated by a set of unique identifiers the same as the keys in the keyset. The keyset is
determined by all rows that qualified the SELECT statement when the cursor was first opened. It
can also detect any changes to the data source, which supports update and delete operations. It is
scrollable by default.
Fetch Data from the Cursor There is a total of 6 methods to access data from the
cursor. They are as follows:
1. FIRST is used to fetch only the first row from the cursor table.
2. LAST is used to fetch only the last row from the cursor table.
3. NEXT is used to fetch data in a forward direction from the cursor table.
4. PRIOR is used to fetch data in a backward direction from the cursor table.
5. ABSOLUTE n is used to fetch the exact nth row from the cursor table.
decremental way.
Whenever we execute an SQL query then there is the possibility of an error that is
unexpected. Cursor goes through each set of rows to return in an SQL query.
There are some very popular exceptions:
1. Duplicate Value: This type of error occur when the cursor tries to insert a
record or tuple which already exists in the database. these types of errors
can be avoided by handling proper error conf
2. Invalid Cursor State: Whenever the cursor is in an invalid state this type of
As a cursor has some limitations, it should only be used when there is no other choice.
These restrictions include:
1. When processing data, it imposes locks on a subset or the entire table.
2. The cursor updates table records one row at a time, which slows down its
performance.
3. While loops are slower than cursors, they do have more overhead.
4. Another factor that influences cursor speed is the quantity of rows and
columns brought into the cursor.
Trigger
A trigger is a stored procedure in a database that 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 specific table columns are updated in
simple words a trigger is a collection of SQL statements with particular names that are
stored in system memory. It belongs to a specific class of stored procedures that are
automatically invoked in response to database server events. Every trigger has a table
attached to it.
The following are the key differences between triggers and stored procedures:
1. Triggers cannot be manually invoked or executed.
2. There is no chance that triggers will receive parameters.
3. A transaction cannot be committed or rolled back inside a trigger.
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Explanation of Syntax
DDL Triggers
Output:
DML Triggers
The Data uses manipulation Language (DML) command events that begin with Insert,
Update, and Delete set off the DML triggers. corresponding to insert_table,
update_view, and delete_table.
SQL Server
create trigger deep
on emp
for
insert,update ,delete
as
print 'you can not insert,update and delete this table i'
rollback;
Output:
Logon Triggers
logon triggers are fires in response to a LOGON event. When a user session is created
with a SQL Server instance after the authentication process of logging is finished but
before establishing a user session, the LOGON event takes place. As a result, the
PRINT statement messages and any errors generated by the trigger will all be visible
in the SQL Server error log. Authentication errors prevent logon triggers from being
used. These triggers can be used to track login activity or set a limit on the number of
sessions that a given login can have in order to audit and manage server sessions.
Advantage of Triggers
The benefits of using triggers in SQL Server include the following:
1. Database object rules are established by triggers, which cause changes to be
undone if they are not met.
2. The trigger will examine the data and, if necessary, make changes.
3. We can enforce data integrity thanks to triggers.
4. Data is validated using triggers before being inserted or updated.
5. Triggers assist us in maintaining a records log.
6. Due to the fact that they do not need to be compiled each time they are run,
triggers improve the performance of SQL queries.
7. The client-side code is reduced by triggers, saving time and labor.
8. Trigger maintenance is simple.
Disadvantage of Triggers
The drawbacks of using triggers in SQL Server include the following:
1. Only triggers permit the use of extended validations.
2. Automatic triggers are used, and the user is unaware of when they are being
executed. Consequently, it is difficult to troubleshoot issues that arise in the
database layer.
3. The database server’s overhead may increase as a result of triggers.
4. In a single CREATE TRIGGER statement, we can specify the same trigger
action for multiple user actions, such as INSERT and UPDATE.
5. Only the current database is available for creating triggers, but they can still
make references to objects outside the database.