1 of 128

PCA24C02J �ADVANCED DATABASE TECHNOLOGY�UNIT-2

2 of 128

INTRODUCTION TO SQL

Overview of the SQL Query Language

The SQL language has several parts:

Data-definition language (DDL). The SQL DDL provides commands for defining relation schemas, deleting relations, and modifying relation schemas.

Data-manipulation language (DML). The SQL DML provides the ability to query information from the database and to insert tuples into, delete tuples from, and modify tuples in the database.

Integrity. The SQL DDL includes commands for specifying integrity constraints that the data stored in the database must satisfy. Updates that violate integrity constraints are disallowed.

3 of 128

INTRODUCTION TO SQL

Overview of the SQL Query Language

View definition. The SQL DDL includes commands for defining views.

Transaction control. SQL includes commands for specifying the beginning

and ending of transactions.

Embedded SQL and dynamic SQL. Embedded and dynamic SQL define how

SQL statements can be embedded within general-purpose programming languages, such as C, C++, and Java.

Authorization. The SQL DDL includes commands for specifying access rights

to relations and views..

4 of 128

Data Types in SQL

  • char(n). Fixed length character string, with user-specified length n.
  • varchar(n). Variable length character strings, with user-specified maximum length n.
  • int. Integer (a finite subset of the integers that is machine-dependent).
  • smallint. Small integer (a machine-dependent subset of the integer domain type).
  • numeric(p,d). Fixed point number, with user-specified precision of p digits, with d digits to the right of decimal point. (ex., numeric(3,1), allows 44.5 to be stores exactly, but not 444.5 or 0.32)
  • real, double precision. Floating point and double-precision floating point numbers, with machine-dependent precision.
  • float(n). Floating point number, with user-specified precision of at least n digits.

5 of 128

Data Types in SQL

CHAR(Size)

It is used to specify a fixed length string that can contain numbers, letters, and special characters. Its size can be 0 to 255 characters. Default is 1.

VARCHAR(Size)

It is used to specify a variable length string that can contain numbers, letters, and special characters. Its size can be from 0 to 65535 characters.

BINARY(Size)

It is equal to CHAR() but stores binary byte strings. Its size parameter specifies the column length in the bytes. Default is 1.

VARBINARY(Size)

It is equal to VARCHAR() but stores binary byte strings. Its size parameter specifies the maximum column length in bytes.

TEXT(Size)

It holds a string that can contain a maximum length of 255 characters.

TINYTEXT

It holds a string with a maximum length of 255 characters.

MEDIUMTEXT

It holds a string with a maximum length of 16,777,215.

LONGTEXT

It holds a string with a maximum length of 4,294,967,295 characters.

ENUM(val1, val2, val3,...)

It is used when a string object having only one value, chosen from a list of possible values. It contains 65535 values in an ENUM list. If you insert a value that is not in the list, a blank value will be inserted.

SET( val1,val2,val3,....)

It is used to specify a string that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values at one time in a SET list.

BLOB(size)

It is used for BLOBs (Binary Large Objects). It can hold up to 65,535 bytes.

6 of 128

Data Types in SQL

CHAR(Size)

It is used to specify a fixed length string that can contain numbers, letters, and special characters. Its size can be 0 to 255 characters. Default is 1.

VARCHAR(Size)

It is used to specify a variable length string that can contain numbers, letters, and special characters. Its size can be from 0 to 65535 characters.

BINARY(Size)

It is equal to CHAR() but stores binary byte strings. Its size parameter specifies the column length in the bytes. Default is 1.

VARBINARY(Size)

It is equal to VARCHAR() but stores binary byte strings. Its size parameter specifies the maximum column length in bytes.

TEXT(Size)

It holds a string that can contain a maximum length of 255 characters.

TINYTEXT

It holds a string with a maximum length of 255 characters.

MEDIUMTEXT

It holds a string with a maximum length of 16,777,215.

LONGTEXT

It holds a string with a maximum length of 4,294,967,295 characters.

ENUM(val1, val2, val3,...)

It is used when a string object having only one value, chosen from a list of possible values. It contains 65535 values in an ENUM list. If you insert a value that is not in the list, a blank value will be inserted.

SET( val1,val2,val3,....)

It is used to specify a string that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values at one time in a SET list.

BLOB(size)

It is used for BLOBs (Binary Large Objects). It can hold up to 65,535 bytes.

7 of 128

SQL Syntax

  • An SQL relation is defined using the create table command:

create table r

(A1 D1, A2 D2, ..., An Dn,� (integrity-constraint1),� ...,� (integrity-constraintk))

    • r is the name of the relation
    • each Ai is an attribute name in the schema of relation r
    • Di is the data type of values in the domain of attribute Ai
  • Example:

create table instructor (� ID char(5),� name varchar(20),dept_name varchar(20),� salary numeric(8,2))

8 of 128

SQL Syntax

  • Some of The Most Important SQL Commands
  • SELECT - extracts data from a database
  • UPDATE - updates data in a database
  • DELETE - deletes data from a database
  • INSERT INTO - inserts new data into a database
  • CREATE DATABASE - creates a new database
  • ALTER DATABASE - modifies a database
  • CREATE TABLE - creates a new table
  • ALTER TABLE - modifies a table
  • DROP TABLE - deletes a table
  • CREATE INDEX - creates an index (search key)
  • DROP INDEX - deletes an index
  • All the SQL statements require a semicolon (;) at the end of each statement.

9 of 128

SQL Syntax

SQL CREATE TABLE Statement

In an SQL driven database, the data is stored in a structured manner, i.e. in the form of tables. To create a table, following syntax is used 

CREATE TABLE table_name(

column1 datatype,

column2 datatype,

column3 datatype,

.....

columnN datatype,

PRIMARY KEY( one or more columns )

);

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)

);

10 of 128

SQL Syntax

SQL DESC Statement

Every table in a database has a structure of its own.

To display the structure of database tables, we use the DESC statements. Following is the syntax −

DESC table_name;

DESC CUSTOMERS;

==========

SQL INSERT INTO Statement

The SQL INSERT INTO Statement is used to insert data into database tables. Following is the syntax −

INSERT INTO table_name( column1, column2....columnN) VALUES ( value1, value2....valueN);

INSERT INTO CUSTOMERS VALUES

(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),

(2, 'Khilan', 25, 'Delhi', 1500),

(3, 'kaushik', 23, 'Kota', 2000),

(4, 'Chaitali', 25, 'Mumbai', 6500));�

11 of 128

SQL Syntax

SQL SELECT Statement

In order to retrieve the result-sets of the stored data from a database table, we use the SELECT statement. Following is the syntax −

SELECT column1, column2....columnN FROM table_name;

To retrieve the data from CUSTOMERS table, we use the SELECT statement as shown below.

SELECT * FROM CUSTOMERS;

SQL UPDATE Statement

When the stored data in a database table is outdated and needs to be updated without having to delete the table, we use the UPDATE statement. Following is the syntax −

UPDATE table_name SET column1 = value1, column2 = value2....columnN=valueN [ WHERE CONDITION ];

To see an example, the following query will update the ADDRESS for a customer whose ID number is 6 in the table.

UPDATE CUSTOMERS SET ADDRESS = 'Pune' WHERE ID = 6;

12 of 128

SQL Syntax

SQL DELETE Statement

Without deleting the entire table from the database, you can also delete a certain part of the data by applying conditions. This is done using the DELETE FROM statement. Following is the syntax −

DELETE FROM table_name WHERE {CONDITION};

The following code has a query, which will DELETE a customer, whose ID is 6.

DELETE FROM CUSTOMERS WHERE ID = 6;

SQL DROP TABLE Statement

To delete a table entirely from a database when it is no longer needed, following syntax is used −

DROP TABLE table_name;

This query will drop the CUSTOMERS table from the database.

DROP TABLE CUSTOMERS;

13 of 128

SQL Syntax

SQL DELETE Statement

Without deleting the entire table from the database, you can also delete a certain part of the data by applying conditions. This is done using the DELETE FROM statement. Following is the syntax −

DELETE FROM table_name WHERE {CONDITION};

The following code has a query, which will DELETE a customer, whose ID is 6.

DELETE FROM CUSTOMERS WHERE ID = 6;

SQL DROP TABLE Statement

To delete a table entirely from a database when it is no longer needed, following syntax is used −

DROP TABLE table_name;

This query will drop the CUSTOMERS table from the database.

DROP TABLE CUSTOMERS;

14 of 128

SQL Syntax

SQL TRUNCATE TABLE Statement

The TRUNCATE TABLE statement is implemented in SQL to delete the data of the table but not the table itself. When this SQL statement is used, the table stays in the database like an empty table. Following is the syntax −

TRUNCATE TABLE table_name;

Following query delete all the records of the CUSTOMERS table −

TRUNCATE TABLE CUSTOMERS;

SQL ALTER TABLE Statement

The ALTER TABLE statement is used to alter the structure of a table. For instance, you can add, drop, and modify the data of a column using this statement. Following is the syntax −

ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_type};

Following is the example to ADD a New Column to the CUSTOMERS table using ALTER TABLE command −

ALTER TABLE CUSTOMERS ADD SEX char(1);

15 of 128

SQL Syntax

SQL WHERE Clause

The WHERE clause is used to filter rows from a table by applying a condition. Following is the syntax to retrieve filtered rows from a table −

SELECT column1, column2....columnN FROM table_name WHERE CONDITION;

The following query is an example to fetch all the records from CUSTOMERS table where the salary is greater than 2000, using the SELECT statement −

SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000;

16 of 128

SQL Operators

Operators in SQL

Operators in SQL are symbols that help us to perform specific mathematical and logical computations on operands. An operator can either be unary or binary.

The unary operator operates on one operand, and the binary operator operates on two operands.

Types of Operators in SQL

Different types of operators in SQL are:

  1. Arithmetic operator
  2. Comparison operator
  3. Logical operator
  4. Bitwise Operators
  5. Compound Operators

17 of 128

SQL Operators

Operators in SQL

Operator

Description

+

Add

-

Subtract

*

Multiply

/

Divide

%

Modulo

SQL Arithmetic Operators

18 of 128

SQL Operators

Operators in SQL

Operator

Description

&

Bitwise AND

|

Bitwise OR

^

Bitwise exclusive OR

SQL Bitwise Operators

Operator

Description

=

Equal to.

>

Greater than.

<

Less than.

>=

Greater than equal to.

<=

Less than equal to.

<>

Not equal to.

SQL Comparison Operators

Comparison Operators in SQL are used to compare one expressions value to other expressions. SQL supports different types of comparison operator, which are described below:

19 of 128

SQL Operators

Operator

Description

Logical AND compares two Booleans as expressions and returns true when both expressions are true.

Logical OR compares two Booleans as expressions and returns true when one of the expressions is true.

Not takes a single Boolean as an argument and change its value from false to true or from true to false.

SQL Logical Operators

Logical Operators in SQL are used to combine or manipulate conditions in SQL queries to retrieve or manipulate data based on specified criteria..

20 of 128

SQL Operators

Operator

Description

&

Bitwise AND operator

|

Bitwise OR operator

^

Bitwise XOR (exclusive OR) operator

~

Bitwise NOT (complement) operator

<<

Left shift operator

>>

Right shift operator

SQL Bitwise Operators

Bitwise operators in SQL are used to perform bitwise operations on binary values in SQL queries, manipulating individual bits to perform logical operations at the bit level. Some SQL Bitwise Operators are:

21 of 128

SQL Operators

SQL Compound Operators

Operator

Description

+=

Add and assign

-=

Subtract and assign

*=

Multiply and assign

/=

Divide and assign

%=

Modulo and assign

&=

Bitwise AND and assign

^=

Bitwise XOR and assign

|=

Bitwise OR and assign

22 of 128

SQL - Expressions

  • What is SQL Expression?
  • An SQL expression is a combination of one or more values, operators and SQL functions that are all evaluated to a value. These SQL EXPRESSION(s) are like formulae and they are written in query language. You can also use them to query the database for a specific set of data.
  • Expressions are used in WHERE clause of an SQL query. As you might have already known, a WHERE clause specifies a condition that needs to be satisfied for the purpose of filtering records from a database table. This condition is comprised of either single or multiple expressions. These expressions are further classified into three types −
  • Boolean Expressions
  • Numeric Expressions
  • Date and time Expressions

23 of 128

SQL - Expressions

  • SQL Boolean Expressions
  • SQL Boolean Expressions are SQL expressions that return only Boolean Datatype as a result. These expressions can be of two types −

  • Boolean Expressions that check for equality of two values using SQL comparison operators. Here, equality of these values is a condition.
  • Boolean Expressions can also contain one value paired with an SQL logical operator. In this case, the logic specified acts like a condition.

24 of 128

SQL - Expressions

  • SQL Boolean Expressions

ID

NAME

AGE

ADDRESS

SALARY

1

Ramesh

32

Ahmedabad

2000.00

2

Khilan

25

Delhi

1500.00

3

kaushik

23

Kota

2000.00

4

Chaitali

25

Mumbai

6500.00

5

Hardik

27

Bhopal

8500.00

6

Komal

22

Hyderabad

4500.00

7

Muffy

24

Indore

10000.00

ID

NAME

AGE

ADDRESS

SALARY

7

Muffy

24

Indore

10000.00

Example

Consider the CUSTOMERS table having the following records −

The following query is a simple example showing the usage of an SQL Boolean Expression −

SELECT * FROM CUSTOMERS WHERE SALARY = 10000;

25 of 128

SQL - Expressions

  • SQL Numeric Expressions
  • SQL Numeric expressions are comprised of two operands and an SQL Arithmetic Operator. These expressions are used to perform any mathematical operation in any query. Hence, the operands must always be numerals and the return value will always be a number as well.
  • Example- Following is a simple example showing the usage of SQL Numeric Expressions −
  • SELECT 15 + 6;
  • Output
  • The output table is retrieved as − 21

SELECT COUNT(*) FROM CUSTOMERS;

The output is displayed as follows − 7

ID

NAME

AGE

ADDRESS

SALARY

1

Ramesh

32

Ahmedabad

2000.00

2

Khilan

25

Delhi

1500.00

3

kaushik

23

Kota

2000.00

4

Chaitali

25

Mumbai

6500.00

5

Hardik

27

Bhopal

8500.00

6

Komal

22

Hyderabad

4500.00

7

Muffy

24

Indore

10000.00

26 of 128

SQL - Expressions

  • SQL Date Expressions
  • SQL Date Expressions are used to compare date related values with current system date and time values. For instance, in a manufacturing company, items manufactured per year can be segregated by using date expressions in a WHERE clause.
  • Counting from the first day of an year to the last day, the count of each item will be retrieved; once the required information is gathered, the company can use this information for their own purposes.

SELECT CURRENT_TIMESTAMP;

The output table is displayed as −

Current_Timestamp

2009-11-12 06:40:23

27 of 128

DDL (Data Definition Language)

  • DDL or Data Definition Language actually consists of the SQL commands that can be used to define the database schema. It simply deals with descriptions of the database schema and is used to create and modify the structure of database objects in the database.

  • DDL is a set of SQL commands used to create, modify, and delete database structures but not data. These commands are normally not used by a general user, who should be accessing the database via an application.

28 of 128

DDL (Data Definition Language)

Command

Description

Syntax

Create database or its objects (table, index, function, views, store procedure, and triggers)

CREATE TABLE table_name (column1 data_type, column2 data_type, ...);

Delete objects from the database

DROP TABLE table_name;

Alter the structure of the database

ALTER TABLE table_name ADD COLUMN column_name data_type;

Remove all records from a table, including all spaces allocated for the records are removed

TRUNCATE TABLE table_name;

Add comments to the data dictionary

COMMENT 'comment_text' ON TABLE table_name;

Rename an object existing in the database

RENAME TABLE old_table_name TO new_table_name;

29 of 128

DDL Commands

DDL (DATA DEFINITION LANGUAGE):

  • It is the first sub-language of SQL.
  • It is used to define the database objects such as table, view, synonym, index and sequence.
  • This language contains Six commands those are:
  1. CREATE
  2. ALTER
  3. DROP
  4. TRUNCATE TABLE
  5. RENAME
  6. COMMENT
  • Create objects in the database
  • Change the structure of database object
  • Deletes the database objects from the database
  • Removes all the records from the database table
  • Rename the table.
  • Add comments to the Data Dictionary

30 of 128

Create Table Command

This command is used to create a table.

Syntax:

CREATE TABLE <TABLE_NAME> (

COL_NAME1 DATATYPE(SIZE),

COL_NAME2 DATATYPE(SIZE),

COL_NAME3 DATATYPE(SIZE), … ,

COL_NAMEn Datatype (size)

);

Create table student (

SNO number (3),

SNAME varchar2 (20),

MARKS number (3)

);

31 of 128

ALTER Command

  • By using ALTER command we can perform the following task.
    1. ADDING a new column or Constraints
    2. DROPING an existing column or Constraint
    3. MODIFYING column definitions
    4. RENAMING a column

32 of 128

ADDING A NEW COLUMN

Syntax:

ALTER TABLE <TABLE_NAME> ADD (COL1_NAME DATA TYPE(SIZE),

COL2_NAME DATA TYPE(SIZE),

COLn_NAME DATA TYPE(SIZE));

  • Add City column to the Student Table

ALTER table student ADD(city varchar2(10));

  • Add State and Pincode columns to Student Table

ALTER table student ADD(state varchar2(10), pincode number(6));

Note: New column can be added only at last. The new column will have null values.

33 of 128

DROPING AN EXISTING COLUMN

Syntax:

ALTER TABLE <TABLE_NAME> DROP(COL1_NAME,COL2_NAME);

  • Delete the column state from the student table

ALTER table student drop(state);

  • Delete the columns say City and Pincode from the student table

ALTER table student drop(city, pincode);

34 of 128

MODIFYING A COLUMN

  • MODIFYING A COLUMN: (increasing/decreasing the size of columns)

Syntax:

ALTER TABLE <TABLE_NAME> MODIFY(COL1_NAME DATA TYPE(SIZE));

Ex: ALTER table student modify (Sname varchar2(10)); ALTER table student modify (Sname varchar2(8));

Note:

  • we can increase and decrease as well as the size of the column.
  • We can decrease the column size only when existing column values can fit into new size
  • By using modify keyword we can change the data type of a column.
  • Column should be empty to change it’s data type.

35 of 128

RENAMING A COLUMN

Syntax:

ALTER TABLE <TABLE_NAME>

RENAME COLUMN<OLD_COL_NAME>TO <NEW_COL_NAME>;

Ex: Rename the column SAL to WAGES in EMP table

ALTER TABLE emp RENAME COLUMN SAL TO WAGES;

36 of 128

DROP Command

This command is used to remove the table from the database.

Syntax:

DROP TABLE <TABLE_NAME>;

Ex:

DROP table student; DROP table emp;

  • It removes the table completely from the database along with Data and its

Structure

  • Once the table is dropped, we cannot get its data back, as it gets removed

permanently

37 of 128

TRUNCATE Command

It is used to remove all the rows from the table.

Syntax: TRUNCATE TABLE <TABLE_NAME>;

Ex: TRUNCATE table student;

Select * from TAB; // ALL TABLE NAME’S ARE DISPLAYED

DELETE

  • We can Roll Back the data.
  • Rows are deleting temporally.
  • Where clause can be used.
  • Delete is sub language DML.

TRUNCATE

  • We cannot Roll Back the data.
  • Rows are deleting permanently.
  • Where clause cannot be used.
  • Delete is sub language DDL.

NOTE: When we use a Truncate command the table gets dropped and re-created. As the structure is

effected is called as a DDL command.

  • All DDL command are permanent.
  • All DML command are Temporary.

38 of 128

Rename

This command is used to change the table name.

Syntax: RENAME <OLD_TABLE_NAME> TO <NEW_TABLE_NAME>;

Ex: Rename student To student1; Rename SALGRADE To GRADE;

39 of 128

DML Commands in SQL

  • DML 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

40 of 128

DML Commands in SQL

  • 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;  
  • SELECT * FROM Student;  
  • SELECT * FROM Student WHERE Stu_Marks = 80;  

41 of 128

DML Commands in SQL

  • 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 )  VALUES (value_1, value_2, value_3, .... value_N ) ;   
  • INSERT INTO Student (Stu_id, Stu_Name, Stu_Marks, Stu_Age) VALUES (104, Anmol, 89, 19);  
  •  

42 of 128

DML Commands in SQL

  • 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 CONDITION;   
  •  

Product_Id

Product_Name

Product_Price

Product_Quantity

P101

Chips

20

20

P102

Chocolates

60

40

P103

Maggi

75

5

P201

Biscuits

80

20

P203

Namkeen

40

50

  1. UPDATE Product SET Product_Price = 80 WHERE Product_Id = 'P102' ;  

43 of 128

DML Commands in SQL

  • 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;  

Product_Id

Product_Name

Product_Price

Product_Quantity

P101

Chips

20

20

P102

Chocolates

60

40

P103

Maggi

75

5

P201

Biscuits

80

20

P203

Namkeen

40

50

DELETE FROM Product WHERE Product_Id = 'P202' ;  

44 of 128

TCL Commands 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.
  • 1. COMMIT :
  • This command is used to save the data permanently.
  • Whenever we perform any of the DML command like -INSERT, DELETE or UPDATE, these can be rollback if the data is not stored permanently. So in order to be at the safer side COMMIT command is used.

Syntax:

commit;

 

45 of 128

TCL Commands in SQL

  • 2. ROLLBACK :
  • This command is used to get the data or restore the data to the last savepoint or last committed state. If due to some reasons the data inserted, deleted or updated is not correct, you can rollback the data to a particular savepoint or if savepoint is not done, then to the last committed state.

  • Syntax:
  • 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;

 

46 of 128

DCL (Data Control Language) Commands in SQL

  • DCL includes commands such as GRANT and REVOKE which mainly deal with the rights, permissions, and other controls of the database system.
  • List of DCL commands:
  • Two important DCL commands and their syntax are:

 

Command

Description

Syntax

Assigns new privileges to a user account, allowing access to specific database objects, actions, or functions.

GRANT privilege_type [(column_list)] ON [object_type] object_name TO user [WITH GRANT OPTION];

Removes previously granted privileges from a user account, taking away their access to certain database objects or actions.

REVOKE [GRANT OPTION FOR] privilege_type [(column_list)] ON [object_type] object_name FROM user [CASCADE];

47 of 128

DCL (Data Control Language) Commands in SQL

  • DCL includes commands such as GRANT and REVOKE which mainly deal with the rights, permissions, and other controls of the database system.
  • List of DCL commands:
  • Two important DCL commands and their syntax are:
  • GRANT Command
  • GRANT, as the name itself suggests, provides. This command allows the administrator to provide particular privileges or permissions over a database object, such as a table, view, or procedure. It can provide user access to perform certain database or component operations.
  • In simple language, the GRANT command allows the user to implement other SQL commands on the database or its objects. The primary function of the GRANT command in SQL is to provide administrators the ability to ensure the security and integrity of the data is maintained in the database.
  • GRANT SELECT ON student TO Aman; 
  • This command will allow Aman to implement the SELECT queries on the student table. This will enable the user to read or retrieve information from the student table.  

 

48 of 128

DCL (Data Control Language) Commands in SQL

  • DCL includes commands such as GRANT and REVOKE which mainly deal with the rights, permissions, and other controls of the database system.
  • List of DCL commands: Two important DCL commands and their syntax are:
  • REVOKE Command
  • As the name suggests, revoke is to take away. The REVOKE command enables the database administrator to remove the previously provided privileges or permissions from a user over a database or database object, such as a table, view, or procedure. The REVOKE commands prevent the user from accessing or performing a specific operation on an element in the database.
  • In simple language, the REVOKE command terminates the ability of the user to perform the mentioned SQL command in the REVOKE query on the database or its component. The primary reason for implementing the REVOKE query in the database is to ensure the data's security and integrity.
  • REVOKE SELECT ON student FROM Aman;  
  • This will stop the user Aman from implementing the SELECT query on the student table. The user may be able to implement other queries in the database.

  • .

 

49 of 128

Aggregate Functions

  • Aggregate functions are functions that take a collection (a set or multiset) of values as input and return a single value. SQL offers five built-in aggregate functions:

Average: avg

Minimum: min

Maximum: max

Total: sum

Count: count

  • Theinputtosumandavgmustbeacollectionofnumbers,buttheotheroperators
  • can operate on collections of nonnumeric data types, such as strings, as well

 

50 of 128

Aggregate Functions

  • An aggregate function is a function that performs a calculation on a set of values, and returns a single value.
  • Aggregate functions are often used with the GROUP BY clause of the SELECT statement. The GROUP BY clause splits the result-set into groups of values and the aggregate function can be used to return a single value for each group.
  • The most commonly used SQL aggregate functions are:
  • MIN() - returns the smallest value within the selected column
  • MAX() - returns the largest value within the selected column
  • COUNT() - returns the number of rows in a set
  • SUM() - returns the total sum of a numerical column
  • AVG() - returns the average value of a numerical column
  • Aggregate functions ignore null values (except for COUNT()).

 

51 of 128

Aggregate Functions

  • Demo SQL Database
  • In this tutorial on aggregate functions, we will use the following table for examples:

 

Id

Name

Salary

1

A

802

2

B

403

3

C

604

4

D

705

5

E

606

6

F

NULL

52 of 128

Aggregate Functions

  • Demo SQL Database
  • In this tutorial on aggregate functions, we will use the following table for examples:
  • Queries
  • --Count the number of employees�SELECT COUNT(*) AS Total Employees FROM Employee;�Total Employees 6�-- Calculate the total salary�SELECT SUM(Salary) AS Total Salary FROM Employee;�Total Salary 3120�-- Find the average salary�SELECT AVG(Salary) AS Average Salary FROM Employee;�Average Salary 624�-- Get the highest salary�SELECT MAX(Salary) AS Highest Salary FROM Employee;�Highest Salary 802�-- Determine the lowest salary�SELECT MIN(Salary) AS Lowest Salary FROM Employee;
  • Lowest Salary 403

 

Id

Name

Salary

1

A

802

2

B

403

3

C

604

4

D

705

5

E

606

6

F

NULL

53 of 128

Set Operations

  • The SQL operations union, intersect, and except operate on relations and correspond to the mathematical set-theory operations ∪, ∩,and−.
  • There are three primary set operators in SQL:

  • UNION
  • INTERSECT
  • EXCEPT (or MINUS)

 

54 of 128

SET OPERATIONS

Types of Set Operation

  1. Union
  2. UnionAll
  3. Intersect
  4. Minus (Set difference)

Union Operation

For R ∪ S, The union of two relations, R and S, defines a relation that contains all the tuples of R, or S, or both R and S, duplicate tuples being eliminated. R and S must be union-compatible.

55 of 128

SET OPERATIONS

Union

  • The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
  • In the union operation, all the number of datatype and columns must be same in both the tables on which UNION operation is being applied.
  • The union operation eliminates the duplicate rows from its resultset.

Syntax

SELECT column_name FROM table1

UNION

SELECT column_name FROM table2;

56 of 128

SET OPERATIONS- UNIONS

Syntax

SELECT column_name FROM table1

UNION

SELECT column_name FROM table2;

Example: The First table

ID

NAME

1

Jack

2

Harry

3

Jackson

The Second table

ID

NAME

3

Jackson

4

Stephan

5

David

Union SQL query will be:

SELECT * FROM First   

UNION  

SELECT * FROM Second;  

ID

NAME

1

Jack

2

Harry

3

Jackson

4

Stephan

5

David

57 of 128

SET OPERATIONS- UNION ALL

SQL UNION ALL

SQL UNION ALL is a powerful tool used to combine the results of two or more SELECT statements into a single result set. Unlike the UNION operator, which eliminates duplicate records, UNION ALL includes all duplicates. This makes UNION ALL it faster and more efficient when you don’t need to remove duplicates.

SELECT columns FROM table1�UNION ALL�SELECT columns FROM table2; 

Example: STUDENTS table:

 

ROLL_NO

NAME

DOB

AGE

1

DEV SHARMA

2001-08-16

17

2

AMAN VERMA

2002-01-04

16

3

KRISH VATSA

2000-11-29

18

TRIP_DETAIL Table:

ROLL_NO

NAME

DOB

AGE

1

DEV SHARMA

2001-08-16

17

2

AMAN VERMA

2002-01-04

16

3

KRISH VATSA

2000-11-29

18

4

VARUN GOYAL

2003-09-21

15

SELECT * FROM STUDENTS�UNION ALL�SELECT * FROM TRIP_DETAIL;

58 of 128

SET OPERATIONS- SQL | MINUS Operator

SQL MINUS

The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query. In simple words, we can say that MINUS operator will return only those rows which are unique in only first SELECT query and not those rows which are common to both first and second SELECT queries..

SELECT NAME, AGE , GRADE

FROM Table1

MINUS

SELECT NAME, AGE, GRADE

FROM Table2

 

59 of 128

SET OPERATIONS- INTERSECTION Operation:

SQL INTERSECTION

A ∩ S where, A and S are the relations, symbol ‘∩’ is used to denote the Intersection operator.

The result of Intersection operation, which is denoted by A ∩ S, is a relation that basically includes all the tuples that are present in both A an S.

Example: Consider a relation Student(FIRST, LAST) and Faculty(FIRSTN, LASTN) given below :

 

First

Last

Aisha

Arora

Bikash

Dutta

Makku

Singh

Raju

Chopra

FirstN

LastN

Raj

Kumar

Honey

Chand

Makku

Singh

Karan

Rao

Student INTERSECTION Faculty :

Student ∩ Faculty

First

Last

Makku

Singh

60 of 128

SET OPERATIONS- Cartesian Product

For R × S, the Cartesian product operation defines a relation that is the concatenation of every tuple of relation R with every tuple of relation S.

Example:

Consider two relations

STUDENT(SNO, FNAME, LNAME) and

DETAIL(ROLLNO, AGE)

The Second table DETAIL

The First table STUDENT

SNO

FNAME

LNAME

1

Albert

Singh

2

Nora

Fatehi

ROLLNO

AGE

5

18

9

21

On applying CROSS PRODUCT on STUDENT and DETAIL:

STUDENT ✕ DETAILS

SNO

FNAME

LNAME

ROLLNO

AGE

1

Albert

Singh

5

18

1

Albert

Singh

9

21

2

Nora

Fatehi

5

18

2

Nora

Fatehi

9

21

61 of 128

SET OPERATIONS- Set difference

Set difference

For R − S The Set difference operation defines a relation consisting of the tuples that are in relation R, but not in S. R and S must be union-compatible.

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.

Example:

∏ writer (Nobels) − ∏ writer (papers)

Syntax:

SELECT column_name FROM table1  

MINUS  

SELECT column_name FROM table2;  

SELECT * FROM First   

MINUS  

SELECT * FROM Second;   The result set table will look like:

The Second table

ID

NAME

1

Jack

2

Harry

3

Jackson

ID

NAME

3

Jackson

4

Stephan

5

David

The First table

ID

NAME

1

Jack

2

Harry

62 of 128

SQL Functions

SQL Functions are built-in programs that are used to perform different operations on the database.

There are two types of functions in SQL:

Aggregate Functions

Scalar Functions

63 of 128

SQL Functions

SQL Aggregate Functions

SQL Aggregate Functions operate on a data group and return a singular output. They are mostly used with the GROUP BY clause to summarize data.

Aggregate Function

Description

Syntax

AVG()

Calculates the average value

SELECT AVG(column_name) FROM table_name;

COUNT()

Counts the number of rows

SELECT COUNT(column_name) FROM table_name

FIRST()

Returns the first value in an ordered set of values

SELECT FIRST(column_name) FROM table_name;

LAST()

Returns the last value in an ordered set of values

SELECT LAST(column_name) FROM table_name;

MAX()

Retrieves the maximum value from a column

SELECT MAX(column_name) FROM table_name;

MIN()

Retrieves the minimum value from a column

SELECT MIN(column_name) FROM table_name;

SUM()

Calculates the total sum of values in a numeric column

SELECT SUM(column_name) FROM table_name;

64 of 128

SQL Functions

SQL Scalar functions

SQL Scalar Functions are built-in functions that operate on a single value and return a single value.

Scalar functions in SQL helps in efficient data manipulation and simplification of complex calculations in SQL queries.

Scalar function

Description

Syntax

UCASE()

Converts a string to uppercase

SELECT UCASE(column_name) FROM table_name;

LCASE()

Converts a string to lowercase

SELECT LCASE(column_name) FROM table_name;

MID()

Extracts a substring from a string

SELECT MID(column_name, start, length) FROM table_name;

LEN()

Returns the length of a string

SELECT LEN(column_name) FROM table_name;

ROUND()

Rounds a number to a specified number of decimals

SELECT ROUND(column_name, decimals) FROM table_name;

NOW()

Returns the current date and time

SELECT NOW();

FORMAT()

Formats a value with the specified format

SELECT FORMAT(column_name, format) FROM table_name;

65 of 128

SQL Functions

https://www.geeksforgeeks.org/sql-functions-aggregate-scalar-functions/

66 of 128

SQL CLAUSES

The sql clauses can help filter out the data according to the users' needs.

The main clauses are SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, INSERT, UPDATE, DELETE, and JOIN.

Each clause has a syntax and its own set of rules and options. They can also be used in combination to create complex queries.

1. WHERE CLAUSE

A WHERE clause in SQL is used with the SELECT query, which is one of the data manipulation language commands. WHERE clauses can be used to limit the number of rows to be displayed in the result set, it generally helps in filtering the records. It returns only those queries which fulfill the specific conditions of the WHERE clause.

WHERE clause is used in SELECT, UPDATE, DELETE statement, etc.

Syntax of where clause with a select query to retrieve all the column values for every record from a table:

SELECT * FROM TABLENAME WHERE CONDITION;  

SELECT * FROM employees WHERE Salary > 50000;  

67 of 128

SQL CLAUSES

2. GROUP BY CLAUSE

The Group By clause is used to arrange similar kinds of records into the groups in the Structured Query Language.

The Group by clause in the Structured Query Language is used with Select Statement. Group by clause is placed after the where clause in the SQL statement.

The Group By clause is specially used with the aggregate function, i.e., max (), min (), avg (), sum (), count () to group the result based on one or more than one column.

The syntax of Group By clause:

SELECT * FROM TABLENAME GROUP BY COLUMNNAME;   

The above syntax will select all the data or records from the table, but it will arrange all those data or records in the groups based on the column name given in the query.

The syntax of Group By clause with Aggregate Functions:

SELECT COLUMNNAME1, Aggregate_FUNCTION (COLUMNNAME) FROM TABLENAME GROUP BY COLUMNNAME;  

68 of 128

SQL CLAUSES

  

E_ID

Name

Salary

City

Designation

Date_of_Joining

Age

1

Sakshi Kumari

50000

Mumbai

Project Manager

2021-06-20

24

2

Tejaswini Naik

75000

Delhi

System Engineer

2019-12-24

23

3

Anuja Sharma

40000

Jaipur

Manager

2021-08-15

26

4

Anushka Tripathi

90000

Mumbai

Software Tester

2021-06-13

24

5

Rucha Jagtap

45000

Bangalore

Project Manager

2020-08-09

23

6

Rutuja Deshmukh

60000

Bangalore

Manager

2019-07-17

26

7

Swara Baviskar

55000

Jaipur

System Engineer

2021-10-10

24

8

Sana Sheik

45000

Pune

Software Engineer

2020-09-10

26

9

Swati Kumari

50000

Pune

Software Tester

2021-01-01

25

10

Mayuri Patel

60000

Mumbai

Project Manager

2020-10-02

24

11

Simran Khanna

45500

Kolhapur

HR

2019-01-02

26

12

Shivani Wagh

50500

Delhi

Software Developer

2016-09-10

25

13

Kiran Maheshwari

50000

Nashik

HR

2013-12-12

23

14

Tejal Jain

40000

Delhi

Project Manager

2017-11-10

25

15

Mohini Shah

38000

Pune

Software Developer

2019-03-05

20

69 of 128

SQL CLAUSES

  

E_ID

Name

Salary

City

Designation

Date_of_Joining

Age

1

Sakshi Kumari

50000

Mumbai

Project Manager

2021-06-20

24

2

Tejaswini Naik

75000

Delhi

System Engineer

2019-12-24

23

3

Anuja Sharma

40000

Jaipur

Manager

2021-08-15

26

4

Anushka Tripathi

90000

Mumbai

Software Tester

2021-06-13

24

5

Rucha Jagtap

45000

Bangalore

Project Manager

2020-08-09

23

6

Rutuja Deshmukh

60000

Bangalore

Manager

2019-07-17

26

7

Swara Baviskar

55000

Jaipur

System Engineer

2021-10-10

24

8

Sana Sheik

45000

Pune

Software Engineer

2020-09-10

26

9

Swati Kumari

50000

Pune

Software Tester

2021-01-01

25

10

Mayuri Patel

60000

Mumbai

Project Manager

2020-10-02

24

11

Simran Khanna

45500

Kolhapur

HR

2019-01-02

26

12

Shivani Wagh

50500

Delhi

Software Developer

2016-09-10

25

13

Kiran Maheshwari

50000

Nashik

HR

2013-12-12

23

14

Tejal Jain

40000

Delhi

Project Manager

2017-11-10

25

15

Mohini Shah

38000

Pune

Software Developer

2019-03-05

20

Example 1:

Write a query to display all the records of the employees table but group the results based on the age column.

Query:

mysql> 

SELECT * FROM employees GROUP BY Age;  

70 of 128

SQL CLAUSES

3. HAVING CLAUSE:

When we need to place any conditions on the table's column, we use the WHERE clause in SQL. But if we want to use any condition on a column in Group By clause at that time, we will use the HAVING clause with the Group By clause for column conditions.

Syntax:

TABLENAME GROUP BY COLUMN NAME HAVING CONDITION;

71 of 128

SQL CLAUSES

E_ID

Name

Salary

City

Designation

Date_of_Joining

Age

1

Sakshi Kumari

50000

Mumbai

Project Manager

2021-06-20

24

2

Tejaswini Naik

75000

Delhi

System Engineer

2019-12-24

23

3

Anuja Sharma

40000

Jaipur

Manager

2021-08-15

26

4

Anushka Tripathi

90000

Mumbai

Software Tester

2021-06-13

24

5

Rucha Jagtap

45000

Bangalore

Project Manager

2020-08-09

23

6

Rutuja Deshmukh

60000

Bangalore

Manager

2019-07-17

26

7

Swara Baviskar

55000

Jaipur

System Engineer

2021-10-10

24

8

Sana Sheik

45000

Pune

Software Engineer

2020-09-10

26

9

Swati Kumari

50000

Pune

Software Tester

2021-01-01

25

10

Mayuri Patel

60000

Mumbai

Project Manager

2020-10-02

24

11

Simran Khanna

45500

Kolhapur

HR

2019-01-02

26

12

Shivani Wagh

50500

Delhi

Software Developer

2016-09-10

25

13

Kiran Maheshwari

50000

Nashik

HR

2013-12-12

23

14

Tejal Jain

40000

Delhi

Project Manager

2017-11-10

25

15

Mohini Shah

38000

Pune

Software Developer

2019-03-05

20

Example 1:

Write a query to display the name of employees, salary, and city where the employee's maximum salary is greater than 40000 and group the results by designation.

Query:

 SELECT Name, City, MAX (Salary) AS Salary FROM employees GROUP BY Designation HAVING MAX (Salary) > 40000;  

72 of 128

SQL Queries

Basic Structure of SQL Queries

The basic structure of an SQL query consists of three clauses:

select, from, and where.

The query takes as its input the relations listed in the from clause, operates

on them as specified in the where and select clauses, and then produces a relation

as the result

Queries on a Single Relation

Let us consider a simple query using our university example, “Find the names

of all instructors.” Instructor names are found in the instructor relation, so we

put that relation in the from clause.

The instructor’s name appears in the name attribute, so we put that in the select clause.

select name from instructor;

73 of 128

SQL Queries

Basic Structure of SQL Queries

Example

Select all records from the Customers table:

SELECT * FROM Customers;

74 of 128

SQL Queries

Some of The Most Important SQL Commands

SELECT - extracts data from a database

UPDATE - updates data in a database

DELETE - deletes data from a database

INSERT INTO - inserts new data into a database

CREATE DATABASE - creates a new database

ALTER DATABASE - modifies a database

CREATE TABLE - creates a new table

ALTER TABLE - modifies a table

DROP TABLE - deletes a table

CREATE INDEX - creates an index (search key)

DROP INDEX - deletes an index

75 of 128

SQL Queries

-- select first_name and last_name columns from Customers table

SELECT first_name, last_name FROM Customers;

76 of 128

SQL Queries

SQL SELECT ALL

To select all columns from a database table, we use the * character. For example,

-- select all columns from Customers table

SELECT * FROM Customers;

77 of 128

SQL Queries

SQL SELECT WHERE Clause

A SELECT statement can have an optional WHERE clause. The WHERE clause allows us to fetch records from a database table that matches specified condition(s).

For example,

-- select all columns from the customers table with last_name 'Doe'

SELECT * FROM Customers WHERE last_name = 'Doe';

78 of 128

SQL Queries

SQL SELECT WHERE Clause

- select age and country columns from customers table where the country is 'USA'

SELECT age, country FROM Customers WHERE country = 'USA';

79 of 128

SQL Queries

SQL Operators

The WHERE clause uses operators to construct conditions. Some of the commonly used operators are:

1. Equal to Operator (=)

-- select all columns from Customers table with first name 'John'

SELECT * FROM Customers WHERE first_name = 'John';

80 of 128

SQL Queries

SQL Operators

2. Greater than (>)

-- select all columns from Customers table with age greater than 25

SELECT * FROM Customers WHERE age > 25;

The above SQL command selects all the customers from the Customers table whose age is greater than 25.

3. AND Operator (AND)

-- select all columns from Customers table with last_name 'Doe' and country 'USA'

SELECT * FROM Customers WHERE last_name = 'Doe' AND country = 'USA';

The above SQL command selects all the customers from the Customers table having last_name Doe and country USA.

81 of 128

SQL query

  • SELECT Statement with HAVING Clause
  • Consider the following database for HAVING Clause:
  • Query:
  • SELECT Department, sum(Salary) as Salary�FROM employee�GROUP BY department�HAVING SUM(Salary) >= 50000;
  • Output:

82 of 128

SQL query

  • SELECT Statement with ORDER BY clause in SQL
  • In this example, we will use SELECT Statement with ORDER BY clause
  • Query:
  • SELECT * FROM Customer ORDER BY Age DESC;

Output:

83 of 128

SQL query

  • SELECT Statement

Output:

s_id

name

age

address

101

Adam

15

Chennai

102

Alex

18

Delhi

103

Abhi

17

Banglore

104

Ankit

22

Mumbai

SELECT s_id, name, age FROM student;

s_id

name

age

101

Adam

15

102

Alex

18

103

Abhi

17

104

Ankit

22

84 of 128

SQL query

  • SELECT Statement

Output:

s_id

name

age

address

101

Adam

15

Chennai

102

Alex

18

Delhi

103

Abhi

17

Banglore

104

Ankit

22

Mumbai

Select a particular record based on a condition

We can use the WHERE clause to set a condition,

SELECT * FROM student WHERE name = 'Abhi';

103

Abhi

17

Rohtak

85 of 128

SQL query

  • SELECT Statement

Output:

Let's write a simple SQL query to display the record for student with s_id as 101.

SELECT s_id,

name,

age,

address

FROM student WHERE s_id = 101;

s_id

name

age

address

101

Adam

15

Chennai

102

Alex

18

Delhi

103

Abhi

17

Banglore

104

Ankit

22

Mumbai

s_id

name

age

address

101

Adam

15

Noida

86 of 128

SQL query

  • SELECT Statement

Output:

SELECT s_id,

name,

age,

address

FROM student WHERE name = 'Adam';

s_id

name

age

address

101

Adam

15

Chennai

102

Alex

18

Delhi

103

Abhi

17

Banglore

104

Ankit

22

Mumbai

_id

name

age

address

101

Adam

15

Noida

87 of 128

SQL query

  • SELECT Statement

Output:

SELECT * FROM Emp ORDER BY salary;

eid

name

age

salary

401

Anu

22

9000

402

Shane

29

8000

403

Rohan

34

6000

404

Scott

44

10000

405

Tiger

35

8000

eid

name

age

salary

403

Rohan

34

6000

402

Shane

29

8000

405

Tiger

35

8000

401

Anu

22

9000

404

Scott

44

10000

SELECT * FROM Emp ORDER BY salary DESC;

eid

name

age

salary

404

Scott

44

10000

401

Anu

22

9000

405

Tiger

35

8000

402

Shane

29

8000

403

Rohan

34

6000

Output:

88 of 128

SQL Subquery�

  • SQL | Subquery
  • In SQL a Subquery can be simply defined as a query within another query. In other words we can say that a Subquery is a query that is embedded in WHERE clause of another SQL query. Important rules for Subqueries:
  • You can place the Subquery in a number of SQL clauses: WHERE clause, HAVING clause, FROM clause. Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with expression operator. It could be equality operator or comparison operator such as =, >, =, <= and Like operator.
  • A subquery is a query within another query. The outer query is called as main query and inner query is called as subquery.

 

89 of 128

SQL Subquery�

  • SQL | Subquery

 

Sample Queries:

  • To display NAME, LOCATION, PHONE_NUMBER of the students from DATABASE table whose section is A

SELECT NAME, LOCATION, PHONE_NUMBER �FROM DATABASE �WHERE ROLL_NO IN (SELECT ROLL_NO �FROM STUDENT �WHERE SECTION='A');

Explanation : First subquery executes “ SELECT ROLL_NO from STUDENT where SECTION=’A’ ” returns ROLL_NO from STUDENT table whose SECTION is ‘A’.Then outer-query executes it and return the NAME, LOCATION, PHONE_NUMBER from the DATABASE table of the student whose ROLL_NO is returned from inner subquery. Output:

90 of 128

SQL Subquery�

 

In a subquery, the outer query's result depends on the result set of the inner subquery. That's why subqueries are also called nested queries.

Here is how this code works:

executes the subquery first (inner query), and returns the minimum age 22

executes the outer query, and selects customers with age 22

91 of 128

SQL Subquery�

 

Example 1: This example uses the Greater than comparison operator with the Subquery.

Student_RollNo.

Stu_Name

Stu_Marks

Stu_City

1001

Akhil

85

Agra

1002

Balram

78

Delhi

1003

Bheem

87

Gurgaon

1004

Chetan

95

Noida

1005

Diksha

99

Agra

1006

Raman

90

Ghaziabad

1007

Sheetal

68

Delhi

SELECT * FROM Student_Details WHERE Stu_Marks> ( SELECT AVG(Stu_Marks ) FROM Student_Details);  

Student_RollNo.

Stu_Name

Stu_Marks

Stu_City

1003

Bheem

87

Gurgaon

1004

Chetan

95

Noida

1005

Diksha

99

Agra

1006

Raman

90

Ghaziabad

92 of 128

Joins

Types of Joins

• Inner Join

o Theta Join

o EQUI join:

o Natural Join (⋈)

• Outer Join

o Left Outer Join (A B)

o Right Outer Join (A B)

o Full Outer Join (A B)

Conditional Join

93 of 128

Joins

INNER JOIN is used to return rows from both tables which satisfy the given condition. It is the most widely used join operation and can be considered as a default join-type

An Inner join or equijoin is a comparator-based join which uses equality comparisons in the join-predicate. However, if you use other comparison operators like ">" it can't be called equijoin.

Inner Join further divided into three subtypes:

• Theta join

• Natural join

• EQUI join

94 of 128

Joins

SQL INNER JOIN combines two or more tables based on specified columns and retrieves records with matching values in the common columns.

Explanation

Let us look at an example scenario to have a better understanding.

Suppose we have the information of employees in a company divided between two tables namely EmpDetails and Marital status. Where,

EmpDetails table holds details like Employee ID, Name and Salary.

MaritalStatus table holds the details Employee ID, Age, and Marital Status.

When we perform the Inner Join operation on these two tables based on the join-predicate 

EmpDetails.EmpID = MaritalStatus.EmpID,

the resultant records hold the following info:

ID, Name, Salary, Age and, Status of the matched records.

95 of 128

Joins

SQL INNER JOIN 

ID

NAME

AGE

ADDRESS

SALARY

1

Ramesh

32

Ahmedabad

2000.00

2

Khilan

25

Delhi

1500.00

3

Kaushik

23

Kota

2000.00

4

Chaitali

25

Mumbai

6500.00

5

Hardik

27

Bhopal

8500.00

6

Komal

22

Hyderabad

4500.00

7

Muffy

24

Indore

10000.00

table ORDERS

 table named CUSTOMERS

OID

DATE

CUSTOMER_ID

AMOUNT

102

2009-10-08 00:00:00

3

3000.00

100

2009-10-08 00:00:00

3

1500.00

101

2009-11-20 00:00:00

2

1560.00

103

2008-05-20 00:00:00

4

2060.00

SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS INNER JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

ID

NAME

AMOUNT

DATE

3

Kaushik

3000.00

2009-10-08 00:00:00

3

Kaushik

1500.00

2009-10-08 00:00:00

2

Khilan

1560.00

2009-11-20 00:00:00

4

Chaitali

2060.00

2008-05-20 00:00:00

96 of 128

Joins

SQL LEFT JOIN

LEFT 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.

Syntax

The syntax of LEFT JOIN in SQL is:

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1

LEFT JOIN table2

ON table1.matching_column = table2.matching_column;

Here,

table1: First table.

table2: Second table

matching_column: Column common to both the tables.

 

97 of 128

Joins

SELECT Student.NAME,StudentCourse.COURSE_ID

FROM Student

LEFT JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO; 

STUDENTS TABLE StudentCourse :

Output:

98 of 128

Joins

SQL RIGHT JOIN

RIGHT 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. It is very similar to LEFT 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.

Syntax:

The syntax of RIGHT JOIN in SQL is:

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1

RIGHT JOIN table2

ON table1.matching_column = table2.matching_column;

STUDENTS TABLE StudentCourse :

99 of 128

Joins

SELECT Student.NAME,StudentCourse.COURSE_ID

FROM Student

RIGHT JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO;

STUDENTS TABLE StudentCourse :

Output:

100 of 128

Joins

SQL 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.

STUDENTS TABLE StudentCourse :

101 of 128

Joins

SQL FULL JOIN

Syntax

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1

FULL JOIN table2

ON table1.matching_column = table2.matching_column;STUDENTS TABLE StudentCourse :

102 of 128

Joins

SQL FULL JOIN

SELECT Student.NAME,StudentCourse.COURSE_ID

FROM Student

FULL JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO;

NAME

COURSE_ID

HARSH

1

PRATIK

2

RIYANKA

2

DEEP

3

SAPTARHI

1

DHANRAJ

NULL

ROHIT

NULL

NIRAJ

NULL

NULL

4

NULL

5

NULL

4

103 of 128

Joins

SQL Natural join (?)

Natural join can join tables based on the common columns in the tables being joined. A natural join returns all rows by matching values in common columns having same name and data type of columns and that column should be present in both tables.

Both table must have at least one common column with same column name and same data type.

The two table are joined using Cross join.

DBMS will look for a common column with same name and data type Tuples having exactly same values in common columns are kept in result.

Natural join Example:

Look at the two tables below- Employee and Department

Employee 

Emp_id

Emp_name

Dept_id

1

Ram 

10

2

Jon 

30

3

Bob

50

Department 

Dept_id

Dept_name

10

IT

30

HR

40

TIS

104 of 128

Joins

SQL Natural join (?)

Natural join can join tables based on the common columns in the tables being joined. A natural join returns all rows by matching values in common columns having same name and data type of columns and that column should be present in both tables.

Problem: Find all Employees and their respective departments.

Solution Query: (Employee) ? (Department)

Employee 

Emp_id

Emp_name

Dept_id

1

Ram 

10

2

Jon 

30

3

Bob

50

Department 

Dept_id

Dept_name

10

IT

30

HR

40

TIS

Emp_id

Emp_name

Dept_id

Dept_id

Dept_name

1

Ram 

10

10

IT 

2

Jon

30

30

HR

Employee data 

Department data 

105 of 128

Joins

• Theta join

THETA JOIN allows you to merge two tables based on the condition represented by theta. Theta joins work for all comparison operators. It is denoted by symbol θ. The general case of JOIN operation is called a Theta join.

Table A

Table B

column 1

column 2

column 1

column 2

1

1

1

1

1

2

1

3

A ⋈ A.column 2 > B.column 2 (B)

For example:

A ⋈ A.column 2 > B.column 2 (B)

column 1

column 2

1

2

106 of 128

Joins

Types of Joins

• Inner Join

  1. o Theta Join
  2. o EQUI join:
  3. o Natural Join (⋈)

• Outer Join

  1. o Left Outer Join (A B)
  2. o Right Outer Join (A B)
  3. o Full Outer Join (A B)

Conditional Join

107 of 128

Joins

Inner Join

INNER JOIN is used to return rows from both tables which satisfy the given condition. It is the most widely used join operation and can be considered as a default join-type

An Inner join or equijoin is a comparator-based join which uses equality comparisons in the join-predicate. However, if you use other comparison operators like ">" it can't be called equijoin.

Inner Join further divided into three subtypes:

• Theta join

• Natural join

• EQUI join

108 of 128

Joins

Inner Join

INNER JOIN is used to return rows from both tables which satisfy the given condition. It is the most widely used join operation and can be considered as a default join-type

An Inner join or equijoin is a comparator-based join which uses equality comparisons in the join-predicate. However, if you use other comparison operators like ">" it can't be called equijoin.

Inner Join further divided into three subtypes:

• Theta join

• Natural join

• EQUI join

109 of 128

Joins

• Theta join

THETA JOIN allows you to merge two tables based on the condition represented by theta. Theta joins work for all comparison operators. It is denoted by symbol θ. The general case of JOIN operation is called a Theta join.

Table A

Table B

column 1

column 2

column 1

column 2

1

1

1

1

1

2

1

3

A ⋈ A.column 2 > B.column 2 (B)

For example:

A ⋈ A.column 2 > B.column 2 (B)

column 1

column 2

1

2

110 of 128

Joins

• EQUI Join

EQUI JOIN is done when a Theta join uses only the equivalence condition. EQUI join is the most difficult operation to implement efficiently in an RDBMS, and one reason why RDBMS have essential performance problems.

For example:

A ⋈A.column 2 = B.column 2 (B)

A ⋈A.column 2 = B.column 2 (B)

column 1

column 2

1

1

111 of 128

Joins

  • Natural Join (⋈)
  • NATURAL JOIN does not utilize any of the comparison operators. In this type of join, the attributes should have the same name and domain. In Natural Join, there should be at least one common attribute between two relations.
  • It performs selection forming equality on those attributes which appear in both relations and eliminates the duplicate attributes.
  • Example:
  • Consider the following two tables

112 of 128

Joins

  • Natural Join (⋈)

C

Num

Square

2

4

3

9

D

Num

Cube

2

8

3

18

C ⋈ D

Num

Square

Cube

2

4

8

3

9

18

113 of 128

Outer Join�

  • An OUTER JOIN doesn't require each record in the two join tables to have a matching record. In this type of join, the table retains each record even if no other matching record exists.
  • Three types of Outer Joins are:
  • • Left Outer Join
  • • Right Outer Join
  • • Full Outer Join

114 of 128

Outer Join�

  • Left Outer Join (A B)
  • LEFT JOIN returns all the rows from the table on the left even if no matching rows have been found in the table on the right. When no matching record found in the table on the right, NULL is returned.

A

Num

Square

2

4

3

9

4

16

B

Num

Cube

2

8

3

18

5

75

A ⋈ B

Num

Square

Cube

2

4

8

3

9

18

4

16

-

115 of 128

Outer Join�

  • RIGHT JOIN returns all the columns from the table on the right even if no matching rows have been found in the table on the left. Where no matches have been found in the table on the left, NULL is returned. RIGHT outer JOIN is the opposite of LEFT JOIN
  • In our example, let's assume that you need to get the names of members and movies rented by them. Now we have a new member who has not rented any movie yet.

A

Num

Square

2

4

3

9

4

16

B

Num

Cube

2

8

3

18

5

75

A ⋈ B

Num

Cube

Square

2

8

4

3

18

9

5

75

-

116 of 128

SQL Views

  • In SQL, a view is a virtual table based on the result-set of an SQL statement.
  • A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
  • You can add SQL statements and functions to a view and present the data as if the data were coming from one single table.
  • A view is created with the CREATE VIEW statement.
  • Views in SQL are a kind of virtual table. A view also has rows and columns like tables, but a view doesn’t store data on the disk like a table. View defines a customized query that retrieves data from one or more tables, and represents the data as if it was coming from a single source.
  • 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 conditions.

117 of 128

SQL Views

118 of 128

SQL Views

Example 1: Creating View from a single table In this example, we will create a View named DetailsView from the table StudentDetails. Query:

CREATE VIEW DetailsView AS

SELECT NAME, ADDRESS

FROM StudentDetails

WHERE S_ID < 5;

SELECT * FROM DetailsView;

119 of 128

SQL Views

Example 2: Create View From Table

In this example, we will create a view named StudentNames from the table StudentDetails. Query:

CREATE VIEW StudentNames AS

SELECT S_ID, NAME

FROM StudentDetails

ORDER BY NAME;

If we now query the view as,

SELECT * FROM StudentNames;

120 of 128

SQL INDEX

  • The Index in SQL is a special table used to speed up the searching of the data in the database tables. It also retrieves a vast amount of data from the tables frequently. The INDEX requires its own space in the hard disk.
  • The index concept in SQL is same as the index concept in the novel or a book.
  • It is the best SQL technique for improving the performance of queries. The drawback of using indexes is that they slow down the execution time of UPDATE and INSERT statements. But they have one advantage also as they speed up the execution time of SELECT and WHERE statements.

  • In SQL, an Index is created on the fields of the tables. We can easily build one or more indexes on a table. The creation and deletion of the Index do not affect the data of the database.

121 of 128

SQL INDEX

  • Why SQL Index?
  • The following reasons tell why Index is necessary in SQL:
  • SQL Indexes can search the information of the large database quickly.
  • This concept is a quick process for those columns, including different values.
  • This data structure sorts the data values of columns (fields) either in ascending or descending order. And then, it assigns the entry for each value.
  • Each Index table contains only two columns. The first column is row_id, and the other is indexed-column.
  • When indexes are used with smaller tables, the performance of the index may not be recognized.
  • Create an INDEX
  • In SQL, we can easily create the Index using the following CREATE Statement:
  • CREATE INDEX Index_Name ON Table_Name ( Column_Name);  

122 of 128

SQL 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.
  • Because a trigger cannot be called directly, unlike a stored procedure, it is referred to as a special procedure. A trigger is automatically called whenever a data modification event against a table takes place, which is the main distinction between a trigger and a procedure. On the other hand, a stored procedure must be called directly.
  • The following are the key differences between triggers and stored procedures:
  • Triggers cannot be manually invoked or executed.
  • There is no chance that triggers will receive parameters.
  • A transaction cannot be committed or rolled back inside a trigger.

123 of 128

SQL Trigger

  • SQL triggers are generally associated with a particular table. This means that when the table is deleted, all its associated triggers are deleted accordingly. Given a table, an SQL trigger can be invoked before or after the following events:

  • INSERT: a new row is inserted in the table.
  • UPDATE: an existing row of the table gets updated.
  • DELETE: a row in the table gets deleted.
  • Thus, when an INSERT, UPDATE, or DELETE SQL query is performed, the RDBMS takes care of automatically firing the corresponding trigger.

124 of 128

SQL Trigger

  • 1. Write a trigger to ensure that no employee of age less than 25 can be inserted in the database.

  • delimiter $$
  • CREATE TRIGGER Check_age BEFORE INSERT ON employee
  • FOR EACH ROW
  • BEGIN
  • IF NEW.age < 25 THEN
  • SIGNAL SQLSTATE '45000'
  • SET MESSAGE_TEXT = 'ERROR:
  • AGE MUST BE ATLEAST 25 YEARS!';
  • END IF;
  • END; $$
  • delimiter;

125 of 128

SQL Stored Procedures

  • A stored procedure in SQL is a group of SQL queries that can be saved and reused multiple times. It is very useful as it reduces the need for rewriting SQL queries. It enhances efficiency, reusability, and security in database management.
  • Users can also pass parameters to stored procedures so that the stored procedure can act on the passed parameter values.
  • Stored Procedures are created to perform one or more DML operations on the Database. It is nothing but a group of SQL statements that accepts some input in the form of parameters, performs some task, and may or may not return a value.
  • Syntax-Two important syntaxes for using stored procedures in SQL are:
  • Syntax to Create a Stored Procedure
  • CREATE PROCEDURE procedure_name
  • (parameter1 data_type, parameter2 data_type, …)
  • AS
  • BEGIN
  • — SQL statements to be executed
  • END

126 of 128

SQL Stored Procedures

  • Creating a Procedure
  • We can create a stored procedure using the CREATE PROCEDURE statement in SQL. Following are the simple steps for creating a stored procedure −
  • Choose a name for the procedure.
  • Write the SQL code for the procedure.
  • We can then test the stored procedure by executing it with different input parameters.
  • Example
  • To understand it better let us consider the CUSTOMERS table which contains the personal details of customers including their name, age, address and salary etc. as shown below −
  • 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)
  • );

127 of 128

SQL Stored Procedures

  • Now, insert values into this table using the INSERT statement as follows −
  • INSERT INTO CUSTOMERS VALUES
  • (1, 'Ramesh', 32, 'Ahmedabad', 2000.00),
  • (2, 'Khilan', 25, 'Delhi', 1500.00),
  • (3, 'Kaushik', 23, 'Kota', 2000.00),
  • (4, 'Chaitali', 25, 'Mumbai', 6500.00),
  • (5, 'Hardik', 27, 'Bhopal', 8500.00),
  • (6, 'Komal', 22, 'Hyderabad', 4500.00),
  • (7, 'Muffy', 24, 'Indore', 10000.00);

ID

NAME

AGE

ADDRESS

SALARY

1

Ramesh

32

Ahmedabad

2000.00

2

Khilan

25

Delhi

1500.00

3

Kaushik

23

Kota

2000.00

4

Chaitali

25

Mumbai

6500.00

5

Hardik

27

Bhopal

8500.00

6

Komal

22

Hyderabad

4500.00

7

Muffy

24

Indore

10000.00

In the following query, we are creating the stored procedure with the name GetCustomerInfo. then we provide it with a single input parameter called @CutomerAge. The stored procedure then selects all records from the CUSTOMERS table where the value of the CutomerAge matches the input parameter.

DELIMITER //

CREATE PROCEDURE GetCustomerInfo(IN CustomerAge INT) BEGIN SELECT * FROM CUSTOMERS WHERE AGE = CustomerAge; END //

DELIMITER ;

128 of 128

SQL Stored Procedures

ID

NAME

AGE

ADDRESS

SALARY

2

Khilan

25

Delhi

1500.00

4

Chaitali

25

Mumbai

6500.00

ID

NAME

AGE

ADDRESS

SALARY

1

Ramesh

32

Ahmedabad

2000.00

2

Khilan

25

Delhi

1500.00

3

Kaushik

23

Kota

2000.00

4

Chaitali

25

Mumbai

6500.00

5

Hardik

27

Bhopal

8500.00

6

Komal

22

Hyderabad

4500.00

7

Muffy

24

Indore

10000.00

CALL GetCustomerInfo(25);

This will return all columns from the CUSTOMERS table where the customers age is 25.

CALL GetCustomerInfo(25);

This will return all columns from the CUSTOMERS table where the customers age is 25.