You are on page 1of 139

MODULE 4

Structured Query Language (SQL)


Overview of SQL
 SQL which stands for Structured Query Language is a language to manage and
communicate with databases.
 For instance, it is used for database creation, deletion, update rows by fetching rows,
modifying rows, etc.
 SQL statements are used for tasks like updating data on a database or retrieving data
from a database.
 SQL is an ANSI (American National Standards Institute) standard language. There
are other versions of the SQL language like T-SQL by Microsoft, PSQL by
Interbase/ Firebird, etc.
 Therefore, the most common relational database management systems that use SQL
are Sybase, Microsoft SQL Server, Oracle, Ingres, Access, etc.
 Despite that most of these database systems use SQL, most of them have other
additional proprietary extensions that are made particularly for their system.
What is SQL?
 SQL (Structured Query Language) is a relational query language that is used for
interacting with the database.
 SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in a relational database.
 SQL is the standard language for Relational Database System. All the Relational
Database Management Systems (RDMS) like MySQL, MS Access, Oracle,
Sybase, Informix, Postgres and SQL Server use SQL as their standard database
language.
Also, they are using different dialects, such as −
• MS SQL Server using T-SQL,
• Oracle using PL/SQL,
• MS Access version of SQL is called JET SQL (native format) etc.
What Can SQL do?
• 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
Rules:
SQL follows the following rules:
• Structure query language is not case sensitive. Generally, keywords of SQL are
written in uppercase.
• Statements of SQL are dependent on text lines. We can use a single SQL statement
on one or multiple text line.
• Using the SQL statements, you can perform most of the actions in a database.
• SQL depends on tuple relational calculus and relational algebra
SQL Process
 When you are executing an SQL command for any RDBMS, the system determines
the best way to carry out your request and SQL engine figures out how to interpret
the task.
 There are various components included in this process.
 These components are −
• Query Dispatcher
• Optimization Engines
• Classic Query Engine
• SQL Query Engine, etc.
 A classic query engine handles all the non-SQL queries, but a SQL query engine
won't handle logical files.
Why SQL?
1. Common querying language
 As mentioned above, SQL is a standard for database language. It is used by most of
the database programs present. (i.e. SQL Server, MYSQL, SQLite, etc.)
2. Easy to learn
 Yes, SQL can be considered as an easy language. SQL uses English like language
statements, thus most people can easily understand SQL with a basic level of
knowledge. Furthermore, SQL is an open-source program so learning resources can
be effortlessly found.
3. Efficient and easy methods
 SQL is an efficient way of handling data. Complex results can be produced with
basic queries. With this simple querying method, data analysis, data manipulation,
and data testing can be done easier and faster.
Types of SQL Commands
 1. DQL (Data Query Language)
 DQL is used for retrieving the saved records from the database.
Data Definition Language Commands

 A data definition language (DDL) is a programming language that is used to define and alter the
structure of database items. Views, schemas, tables, and indexes are examples of database objects.
 In certain cases, this word is referred to as data description language since it defines the columns and
records in a database table.
 DDL is now incorporated into any formal language for expressing data in the database industry. It is,
nevertheless, considered a subset of SQL (Structured Query Language)
 SQL frequently combines imperative verbs with ordinary English, such as phrases, to make database
changes. As a result, DDL does not appear in a SQL database as a distinct language, but it does
describe modifications to the database schema.
 It deals with descriptions of the database schema to build and alter the structure of objects in a
database. Unlike data manipulation language (DML) commands, which are used to modify data, DDL
commands are used to change the database structure, such as adding new tables or objects, as well as
all of their properties (data type, table name, etc.).
 CREATE, ALTER, DROP, and TRUNCATE are the most often used DDL in SQL queries.
1. CREATE

 This command creates a new table using a specific syntax. The syntax for the CREATE statement is as
follows:

 CREATE TABLE [NAME OF TABLE] ([column definitions]) [parameters for table];

 For example:

 CREATE TABLE Employee (Employee Id INTEGER PRIMARY KEY, First name CHAR (50) NULL,
Last name CHAR (75) NOT NULL);

 Every command preceding the semicolon is processed by the statement's required semicolon. The data type
is specified in this case by the string CHAR. DATE, NUMBER, and INTEGER are examples of other data
types.
2. ALTER

 Altering a database table is done with the modify command. This command may be used to add new
columns to a database table, delete existing columns, and even modify the data type of the columns
concerned.

 The syntax of an Alter command is as follows:

 Alter object type object name object parameters;

 For example:

 ALTER TABLE Employee ADD PRIMARY KEY (employee_pk);

 To create a constraint and enforce a unique value, we introduced a unique primary key to the table in this
example. On the Employee table, the constraint "employee pk" is a primary key.
3. DROP

 Drop command is used to remove items from a database, such as tables, indexes, and
views. Because a DROP command cannot be reversed, once an item is deleted, it
cannot be recovered.

 The syntax for the Drop statement is: DROP object type object name;

 For example:

 DROP TABLE Employee;

 Here, in this example employee tables are being deleted.


4. TRUNCATE

 The TRUNCATE command, like DROP, is used to rapidly delete all records from a table. Unlike
DROP, which totally destroys a table, TRUNCATE keeps the table's whole structure so it may be
reused afterward.

 The syntax for the Truncate command goes like this:


 TRUNCATE TABLE table_name;

 For example:

 TRUNCATE TABLE Employee;

 Here all the extents of the Employee table are marked for deallocation in this example, so they're
deemed vacant for reuse.
• The databases for which the user's role has the OWNERSHIP or USAGE privilege
are listed in the SHOW DATABASES output.
• The schemas for which the user's role has the OWNERSHIP or USAGE privilege are
included in the SHOW SCHEMAS output.
• The tables for which the user's role has any privileges are included in the SHOW
TABLES output. The USAGE privilege on the parent database and schema must also
be granted to the role.
The following clauses can be used to control the output of most SHOW commands:
• The optional LIKE clause can be used to filter the list of items returned by name.
• The database object types provide an optional IN clause that may be used to limit the
command's scope to a single schema or database, or the whole account.
7. DESCRIBE

 It describes the details for any specified object in the Database.

 The syntax for DESCRIBE command is:

 DESC<object_type> <object_name>
Data Manipulation Language Commands

• ML is an abbreviation of Data Manipulation Language.


• The DML commands in Structured Query Language change the data
present in the SQL database. We can easily access, store, modify,
update and delete the existing records from the database using DML
commands.

Following are the four main DML commands in SQL:


1.SELECT Command
2.INSERT Command
3.UPDATE Command
4.DELETE Command
SELECT DML Command
 SELECT is the most important data manipulation command in Structured Query
Language.
 The SELECT command shows the records of the specified table.
 It also shows the particular record of a particular column by using the WHERE
clause.

Syntax of SELECT DML command


 SELECT column_Name_1, column_Name_2, ….., column_Name_N
FROM Name_of_table;
 Here, column_Name_1, column_Name_2, ….., column_Name_N are the names
of those columns whose data we want to retrieve from the table.
 If we want to retrieve the data from all the columns of the table, we have to use the
following SELECT command:
 SELECT * FROM table_name;
INSERT DML Command

 INSERT is another most important data manipulation command in Structured Query Language, which allows
users to insert data in database tables.
 Syntax of INSERT Command
 INSERT INTO TABLE_NAME ( column_Name1 , column_Name2 , column_Name3 , .... column_NameN ) V
ALUES (value_1, value_2, value_3, .... value_N ) ;
 Example 1: This example describes how to insert the record in the database table.
 Let's take the following student table, which consists of only 2 records of the student.

INSERT INTO Student (Stu_id, Stu_Name, Stu_Marks, Stu_Age) VALUES (104, Anmol, 89, 19);
UPDATE DML Command

 UPDATE is another most important data manipulation command in Structured Query Language, which
allows users to update or modify the existing data in database tables.
 Syntax of UPDATE Command
 UPDATE Table_name SET [column_name1= value_1, ….., column_nameN = value_N] WHERE CO
NDITION;
 Here, 'UPDATE', 'SET', and 'WHERE' are the SQL keywords, and 'Table_name' is the name of the table
whose values you want to update.
UPDATE Student SET Stu_Marks = 80, Stu_Age = 21 WHERE Stu_Id = 103 AND Stu_Id = 2
02;
 DELETE DML Command

 DELETE is a DML command which allows SQL users to remove single or multiple existing records from
the database tables.
 This command of Data Manipulation Language does not delete the stored data permanently from the
database. We use the WHERE clause with the DELETE command to select specific rows from the table.
 Syntax of DELETE Command
 DELETE FROM Table_Name WHERE condition;
DELETE FROM Student WHERE Stu_Marks > 70 ;
Data Control Language Commands

 Data control language (DCL) is used to access the stored data. It is mainly used for
revoke and to grant the user the required access to a database. In the database, this
language does not have the feature of rollback.
 It is a part of the structured query language (SQL).
 It helps in controlling access to information stored in a database. It complements the
data manipulation language (DML) and the data definition language (DDL).
 It is the simplest among three commands.
 It provides the administrators, to remove and set database permissions to desired users
as needed.
 These commands are employed to grant, remove and deny permissions to users for
retrieving and manipulating a database.
 DCL commands are as follows:
1. GRANT
2. REVOKE
 It is used to grant or revoke access permissions from any database user.
1. GRANT COMMAND
 GRANT command gives user's access privileges to the database.
 This command allows specified users to perform specific tasks.
Syntax:
GRANT <privilege list>
ON <relation name or view name>
TO <user/role list>;

Here,
 privilege names are SELECT,UPDATE,DELETE,INSERT,ALTER,ALL
 Object name is table name
 user is the name of the user to whom we grant privileges
Example : GRANT Command

 GRANT ALL ON employee


TO ABC;
[WITH GRANT OPTION]

 In the above example, user 'ABC' has been given permission to view and
modify the records in the 'employee' table.
2. REVOKE COMMAND
 REVOKE command is used to cancel previously granted or denied permissions.
 This command withdraw access privileges given with the GRANT command.
 It takes back permissions from user.
 Syntax:
REVOKE <privilege list>
ON <relation name or view name>
FROM <user name>;

 Here,
 privilege names are SELECT,UPDATE,DELETE,INSERT,ALTER,ALL
 objectname is table name
 user is the name of the user whose privileges are removing
 Example : REVOKE Command
 REVOKE UPDATE
ON employee
FROM ABC;
Transaction Control Language Commands(TCL)

 In SQL, TCL stands for Transaction control language.


 A single unit of work in a database is formed after the consecutive execution of commands is
known as a transaction.
 There are certain commands present in SQL known as TCL commands that help the user
manage the transactions that take place in a database.
 COMMIT, ROLLBACK and SAVEPOINT are the most commonly used TCL commands in
SQL.
SQL Commit

 COMMIT is the SQL command that is used for storing changes performed by a
transaction. When a COMMIT command is issued it saves all the changes since
last COMMIT or ROLLBACK.

 Syntax for SQL Commit


Commit;
DELETE from Customer where State = 'Texas'; COMMIT;
SQL RollBack

 ROLLBACK is the SQL command that is used for reverting changes performed by a transaction. When a
ROLLBACK command is issued it reverts all the changes since last COMMIT or ROLLBACK.

 Syntax for SQL Rollback


Rollback;
 Post the DELETE command if we publish ROLLBACK it will revert the change that is performed due to the delete
command. Updated Command with ROLLBACK
3. SAVEPOINT :

This command is used to save the data at a particular point temporarily, so that
whenever needed can be rollback to that particular point.

 Syntax:

Savepoint A;
If on the above table savepoint is performed:

INSERT into STUDENT VALUES ('Jack', 95);


Commit;

UPDATE NAME
SET NAME= ‘Rossie’
WHERE marks= 70;
SAVEPOINT A;

INSERT INTO STUDENT VALUES (‘Zack’, 76);


Savepoint B;

INSERT INTO STUDENT VALUES (‘Bruno’, 85);


Savepoint C;

SELECT * FROM STUDENT;


Integrity Constraints
• SQL constraints are used to specify rules for the data in a table.
• Constraints 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 table. If there is any violation between the
constraint and the data action, the action is aborted.
• Constraints can be column level or table level.
• Column level constraints apply to a column, and table level constraints apply to the whole
table.
 In DBMS, Integrity constraints can be defined as a set of rules that are used to
maintain the information’s quality. This ensures that the data integration is not
affected at all by data insertion, updation or other processes. Hence integrity
constraints are like insurance to guard the database if there is any accidental
damage.
 Types of Integrity Constraints
 Integrity constraints can be of four types:
1. Domain constraint
2. Entity integrity constraint
3. Referential integrity constraint
4. Key constraint
Referential Integrity in SQL

 A referential integrity constraint is also known as foreign key constraint.


 A foreign key is a key whose values are derived from the Primary key of another table.
 The table from which the values are derived is known as Master or Referenced Table and the
Table in which values are inserted accordingly is known as Child or Referencing Table.
 In other words, we can say that the table containing the foreign key is called the child table,
and the table containing the Primary key/candidate key is called the referenced or parent
table.
 When we talk about the database relational model, the candidate key can be defined as a set of
attribute which can have zero or more attributes.
Foreign Key Constraint OR Referential Integrity constraint.

There are two referential integrity constraint:


 Insert Constraint: Value cannot be inserted in CHILD Table if the value is not lying in MASTER
Table
 Delete Constraint: Value cannot be deleted from MASTER Table if the value is lying in CHILD
Table
 Suppose you wanted to insert Roll = 05 with other values of columns in SUBJECT Table, then you
will immediately see an error "Foreign key Constraint Violated" i.e. on running an insertion
command as:
 Insert into SUBJECT values(5, 786, OS); will not be entertained by SQL due to Insertion
Constraint ( As you cannot insert value in a child table if the value is not lying in the master table,
since Roll = 5 is not present in the master table, hence it will not be allowed to enter Roll = 5 in
child table )
Referential Integrity in SQL Server
 In this section, we will cover the list of Referential Integrity in SQL Server and their advantages. The
following is the available list of Referential Integrity constraint options in SQL Server.
 No Action: This is the default behavior. If you created a Foreign key without mentioning the Referential
Integrity, it would automatically assign No Action. If you set the Referential Integrity as No Action and
perform an update or delete in the parent table, it will throw an error message.
 Cascade: If you set the Referential Integrity as Cascade. And if you perform an update or delete in the
parent table, then those changes will automatically be applied to the dependent table rows.
 Set Default: If you set the SQL Server Referential Integrity as Default. When performing an update or
delete in the parent table, the foreign key column values will be replaced by the default value.
 Set Null: If you set the Referential Integrity as Set Null and perform an update or delete in the parent
table, the dependent records will become Nulls.
Concat()
SQL Set Operation
 The SQL Set operation is used to combine the two or more SQL SELECT
statements.
Types of Set Operation
 Union
 UnionAll
 Intersect
 Minus
 Example:
The First table
3. Intersect
 The result set table will look like:
SQL Aggregate Functions
 SQL aggregation function is used to perform the calculations on multiple rows of a single column of a table. It returns
a single value.
 It is also used to summarize the data.
The SQL GROUP BY Statement
 The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some
functions. i.e if a particular column has same values in different rows then it will arrange these rows in a
group.
Important Points:
 GROUP BY clause is used with the SELECT statement.
 In the query, GROUP BY clause is placed after the WHERE clause.
 In the query, GROUP BY clause is placed before ORDER BY clause if used any.

SELECT column1, function_name(column2)


FROM table_name
WHERE condition
GROUP BY column1, column2
ORDER BY column1, column2;
O/P
Difference between Having and Where Clause in Group by statement

A HAVING clause is like a WHERE clause, but applies only to


groups as a whole (that is, to the rows in the result set
representing groups), whereas the WHERE clause applies to
individual rows. A query can contain both a WHERE clause and a
HAVING clause.
SQL HAVING Clause
Ram 2000 GOA
1. Now, suppose that you want to show those cities whose total salary of employees is more than 5000.
For this case, you have to type the following query with the HAVING clause in SQL:

SELECT SUM(Emp_Salary), Emp_City


FROM Employee
GROUP BY Emp_City
HAVING
SUM(Emp_Salary)>5000;
SQL Views
 Views in SQL are kind of virtual tables.
 A view also has rows and columns as they are in a real table in the
database.
 We can create a view by selecting fields from one or more tables
present in the database.
 A View can either have all the rows of a table or specific rows based
on certain condition.
 SQL views provide a way to simplify complex queries by creating a
reusable template for frequently used queries. They also enable
developers to control access to sensitive data by limiting the
columns and rows that a user can see.
Ks,StudentMarks.AGE
JOINS

 SQL Join statement is used to combine data or rows from two or more tables
based on a common field between them. Different types of Joins are as
follows:
 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN
 The simplest Join is INNER JOIN.
 A. INNER JOIN
 The INNER JOIN keyword selects all rows from both the tables as long as the condition is satisfied.
This keyword will create the result-set by combining all rows from both the tables where the
condition satisfies i.e value of the common field will be the same.

 Syntax:
 SELECT table1.column1,table1.column2,table2.column1,.... FROM table1 INNER
JOIN table2 ON table1.matching_column = table2.matching_column;
Example Queries(INNER JOIN)
This query will show the names and age of students enrolled in different courses.

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student INNER


JOIN StudentCourse ON Student.ROLL_NO = StudentCourse.ROLL_NO;
B. LEFT JOIN
 This join returns all the rows of the table on the left side of the join and matches rows for the table on the
right side of the join. For the rows for which there is no matching row on the right side, the result-set will
contain null. LEFT JOIN is also known as LEFT OUTER JOIN.
C. RIGHT JOIN
 RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the
join and matching rows for the table on the left side of the join. For the rows for which there is no
matching row on the left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT
OUTER JOIN.
D. FULL JOIN
 FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN. The
result-set will contain all the rows from both tables. For the rows for which there is no matching, the
result-set will contain NULL values.
Nested Sub queries

 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.
Important Rule:

 A subquery can be placed in a number of SQL clauses like WHERE clause,


FROM clause, HAVING clause.
 You can use Subquery with SELECT, UPDATE, INSERT, DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
 A subquery is a query within another query. The outer query is known as the
main query, and the inner query is known as a subquery.
 Subqueries are on the right side of the comparison operator.
 A subquery is enclosed in parentheses.
 In the Subquery, ORDER BY command cannot be used. But GROUP BY
command can be used to perform the same function as ORDER BY
command.
1. Subqueries with the Select Statement
 SQL subqueries are most frequently used with the Select statement.
 Syntax
 A nested query is a query that has another query embedded within it. The embedded query is called a
subquery.
 A subquery typically appears within the WHERE clause of a query. It can sometimes appear in the FROM
clause or HAVING clause.

Teacher table

Class table
SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY
4500);
Subqueries with the UPDATE Statement
1. Example
We have the CUSTOMERS_BKP table available which is backup of CUSTOMERS
table. The following example updates SALARY by 0.25 times in the CUSTOMERS
table for all the customers whose AGE is greater than or equal to 27.

UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT


AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );
Subqueries with the DELETE Statement

DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM


CUSTOMERS_BKP WHERE AGE >= 27 );
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.
 These triggers help in maintaining the integrity of the data by
changing the data of the database in a systematic fashion.
1.CREATE TRIGGER: These two keywords specify that a triggered block is going to be declared.

2. TRIGGER_NAME: It creates or replaces an existing trigger with the Trigger_name. The trigger
name should be unique.
 BEFORE | AFTER: It specifies when the trigger will be initiated i.e. before the ongoing event
or after the ongoing event.

 INSERT | UPDATE | DELETE: These are the DML operations and we can use either of them
in a given trigger.

 ON[TABLE_NAME]: It specifies the name of the table on which the trigger is going to be
applied.

 FOR EACH ROW: Row-level trigger gets executed when any row value of any column
changes.

 TRIGGER BODY: It consists of queries that need to be executed when the trigger is called
/* Create a few records in this table */
INSERT INTO student(id, first_name, last_name) VALUES(1,'Alvaro', 'Morte’);
INSERT INTO student(id, first_name, last_name) VALUES(2,'Ursula', 'Corbero');
INSERT INTO student(id, first_name, last_name) VALUES(3,'Itziar', 'Ituno’);
INSERT INTO student(id, first_name, last_name) VALUES(4,'Pedro', 'Alonso’);
INSERT INTO student(id, first_name, last_name) VALUES(5,'Alba', 'Flores');

You might also like