0% found this document useful (0 votes)
6 views

DBMS

Uploaded by

jaswanthm206
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

DBMS

Uploaded by

jaswanthm206
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Database Management System Lab

By
By
Dr. Manomita Chakraborty
Assistant Professor
VIT-AP, Amaravati, AP, India

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 1


Objective of the Lab
✓ Understand the practical applicability of database management system concepts.
✓ Working on existing database systems, designing of database, creating relational database, analysis of table design.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 2


SQL

• SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in relational database.

• SQL is the standard language for Relation Database System.

• SQL is a non-procedural language unlike relational algebra.

• All relational database management systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL Server use SQL as
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.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 3


Why SQL

• Allows users to access data in relational database management systems.

• Allows users to describe the data.

• Allows users to define the data in database and manipulate that data.

• Allows to embed within other languages using SQL modules, libraries & pre-compilers.

• Allows users to create and drop databases and tables.

• Allows users to create view, stored procedure, functions in a database.

• Allows users to set permissions on tables, procedures and views.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 4


History of SQL

• 1970 -- Dr. E. F. "Ted" of IBM is known as the father of relational databases. He described a relational model for databases.
• 1974 -- Structured Query Language appeared.
• 1978 -- IBM worked to develop Codd's ideas and released a product named System/R.
• 1986 -- IBM developed the first prototype of relational database and standardized by ANSI. The first relational database was
released by Relational Software and its later becoming Oracle.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 5


SQL Data type
Data types mainly classified into three categories for every database.
• String Data types
• Numeric Data types
• Date and time Data types
String Data Type
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.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 6


SQL Data type(contd..)
Numeric Data Type
BIT(Size) It is used for a bit-value type. The number of bits per value is specified in size. Its size can be 1 to 64. The default
value is 1.
INT(size) It is used for the integer value. Its signed range varies from -2147483648 to 2147483647 and unsigned range varies
from 0 to 4294967295. The size parameter specifies the max display width that is 255.

INTEGER(size) It is equal to INT(size).


FLOAT(size, d) It is used to specify a floating point number. Its size parameter specifies the total number of digits. The number of
digits after the decimal point is specified by d parameter.

FLOAT(p) It is used to specify a floating point number. MySQL used p parameter to determine whether to use FLOAT or
DOUBLE. If p is between 0 to24, the data type becomes FLOAT (). If p is from 25 to 53, the data type becomes
DOUBLE().

DOUBLE(size, d) It is a normal size floating point number. Its size parameter specifies the total number of digits. The number of digits
after the decimal is specified by d parameter.

DECIMAL(size, d) It is used to specify a fixed point number. Its size parameter specifies the total number of digits. The number of digits
after the decimal parameter is specified by d parameter. The maximum value for the size is 65, and the default value
is 10. The maximum value for d is 30, and the default value is 0.

DEC(size, d) It is equal to DECIMAL(size, d).


BOOL It is used to specify Boolean values true and false. Zero is considered as false, and nonzero values are considered as
true.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 7


SQL Data type(contd..)
Date and Time Data Types
DATE It is used to specify date format YYYY-MM-DD. Its supported range is from '1000-01-01' to
'9999-12-31'.

DATETIME(fsp) It is used to specify date and time combination. Its format is YYYY-MM-DD hh:mm:ss. Its
supported range is from '1000-01-01 00:00:00' to 9999-12-31 23:59:59'.

TIMESTAMP(fsp) It is used to specify the timestamp. Its value is stored as the number of seconds since the Unix
epoch('1970-01-01 00:00:00' UTC). Its format is YYYY-MM-DD hh:mm:ss. Its supported
range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC.

TIME(fsp) It is used to specify the time format. Its format is hh:mm:ss. Its supported range is from '-
838:59:59' to '838:59:59'

YEAR It is used to specify a year in four-digit format. Values allowed in four digit format from 1901
to 2155, and 0000.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 8


DDL commands
✓ CREATE – is used to create the database or its objects (like table, index, function, views, store procedure and triggers).
Syntax:
CREATE TABLE table_name (column1 datatype, column2 datatype, column3 datatype, ....);

Example:
CREATE TABLE Persons (PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255));

✓ DROP – is used to delete objects from the database.


Syntax:
DROP table;
For example:
DROP TABLE Shippers;

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 9


DDL commands
✓ ALTER-is used to alter the structure of the database.
ALTER TABLE table_name
ADD column_name datatype;
Example:
ALTER TABLE Customers
ADD Email varchar(255);

✓ TRUNCATE–is used to remove all records from a table, including all spaces allocated for the records are removed.
Syntax: TRUNCATE TABLE table_name;
Example: TRUNCATE TABLE Categories;

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 10


DDL commands

✓ COMMENT –is used to add comments to the data dictionary.


Single line comments start with --.
Example: SELECT * FROM Customers -- WHERE City='Berlin’;

✓ RENAME –is used to rename an object existing in the database.


Syntax: RENAME COLUMN old_name TO new_name;
RENAME old_table _name To new_table_name ;
Example: RENAME Cars To Car_2021_Details ;

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 11


DML commands
✓ INSERT: Command to add new or fresh value to the database.
Syntax:
INSERT INTO TABLE_NAME (column1, column2, column3,…columnN) VALUES (value1, value2, value3 ,…, valueN);

If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query.

INSERT INTO table_name VALUES (value1, value2, value3, ...);

Example:
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

✓ UPDATE: Command to change or update the present/existing data to a newer value inside the database.
UPDATE table_name SET column1 = value1, column2 = value2…., columnN = valueN WHERE [condition];

Example:
UPDATE Customers SET ContactName = 'Alfred Schmidt', City= 'Frankfurt’ WHERE CustomerID = 1;

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 12


DML commands

✓ DELETE: Command to remove or delete the values or data information from the database’s current table.
DELETE FROM table_name WHERE condition;

Example:
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

✓ MERGE: Command to merge two or more data tables inside a database.


MERGE [AS TARGET]
USING [AS SOURCE]
ON
[WHEN MATCHED
THEN ]
[WHEN NOT MATCHED [BY TARGET]
THEN ]
[WHEN NOT MATCHED BY SOURCE
THEN ];

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 13


DCL commands
✓ Grant: It is used to give user access privileges to a database.

Syntax:

grant privilege_name on object_name to {user_name | public | role_name};

✓ Revoke: It is used to take back permissions from the user.

Syntax:

revoke privilege_name on object_name from {user_name | public | role_name};

Example:
grant insert, select on accounts to Ram
By the above command user ram has granted permissions on accounts database object like he can query or insert into accounts.
revoke insert, select on accounts from Ram
By the above command user ram’s permissions like query or insert on accounts database object has been removed.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 14


TCL commands

✓ Commit: Commit command is used to save all the transactions to the database.

Syntax: COMMIT;
Example:
DELETE FROM CUSTOMERS WHERE AGE = 25;
COMMIT;
✓ Rollback: Rollback command is used to undo transactions that have not already been saved to the database.

Syntax: ROLLBACK;
Example:
DELETE FROM CUSTOMERS WHERE AGE = 25;
ROLLBACK;
✓ SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire transaction.

Syntax:
SAVEPOINT SAVEPOINT_NAME;

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 15


DQL commands

✓ SELECT: This is the same as the projection operation of relational algebra. It is used to select the attribute based on the condition
described by WHERE clause.

Syntax:
SELECT expressions
FROM TABLES
WHERE conditions;

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 16


SQL Logical Operators

Operator Description
ALL It compares a value to all values in another value set.

AND It allows the existence of multiple conditions in an SQL statement.

ANY It compares the values in the list according to the condition.

BETWEEN It is used to search for values that are within a set of values.

IN It compares a value to that specified list value.

NOT It reverses the meaning of any logical operator.

OR It combines multiple conditions in SQL statements.

EXISTS It is used to search for the presence of a row in a specified table.

LIKE It compares a value to similar values using wildcard operator.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 17


ORACLE
1. Installation in windows :Oracle Database 19c

Step 1: Install Oracle Database 19c on Windows

✓ Download the software from the below link.


✓ https://www.oracle.com/database/technologies/oracle19c-windows-downloads.html
✓ Unzip the files in a folder named db_home in c drive and perform all the steps mentioned in the below link to
install the software.
✓ https://alekciss.com/install-oracle-database-19c-on-windows/

Step 2: Create a Database in Oracle 19c on Windows

✓ Perform the steps mentioned in the below link to create a database.


✓ https://alekciss.com/create-an-oracle-database-19c-on-windows/

Step 3: Download Sqldeveloper

✓ https://www.oracle.com/tools/downloads/sqldev-downloads.html
✓ Unzip the files in a folder named Sqldeveloper in c drive.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 18


ORACLE
1. Installation in windows :Oracle Database 19c

1. Check whether your database is working or not


✓ (Open SQL Plus from start menu) or (open cmd and type sqlplus)

or

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 19


ORACLE
1. Installation in windows :Oracle Database 19c

1. Check whether your database is working or not


✓ You will be asked for username, since you have not created any username type the default user name:
‘/’ as sysdba

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 20


ORACLE
1. Installation in windows :Oracle Database 19c

1. Check whether your database is working or not


✓ Type the following query to check whether the database is working or not:
select * from tab;

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 21


ORACLE
1. Installation in windows :Oracle Database 19c

1. Check whether your database is working or not


✓ Insert values in the table trial:
✓ Create a table and check:
create table trial(message varchar2(10)); insert into trial values('hi');

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 22


ORACLE
1. Installation in windows :Oracle Database 19c

1. Check whether your database is working or not

✓ Display the table:


select * from trial;

If all the steps are done your database is working correctly, installation done properly
3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 23
ORACLE
2. Checking with the default databases present:

Open Sqldeveloper: (here we will be performing all our queries)

✓ Open sqldeveloper:

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 24


ORACLE
2. Checking with the default databases present:

Open Sqldeveloper: (here we will be performing all our queries)

✓ Under the databases detected tab, press load TNS files, it will show all the default databases
✓ Right click on any of the databases under the TNS FILE and click on properties.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 25


ORACLE
2. Checking with the default databases present:

Open Sqldeveloper: (here we will be performing all our queries)

✓ Change the username and password ✓ Press test.


✓ Username: system. ✓ Password: as given by you during installation.
✓ Password: as given by you during installation.
✓ Press test.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 26


ORACLE
2. Checking with the default databases present:
Open Sqldeveloper: (here we will be performing all our queries)
✓ After successful connection to a database you will see all the tables under it, you can access them , write queries .

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 27


ORACLE
2. Checking with the default databases present:
Open Sqldeveloper: (here we will be performing all our queries)
✓ After successful connection to a database you will see all the tables under it, you can access them , write queries .

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 28


ORACLE
2. Checking with the default databases present:
Open Sqldeveloper: (here we will be performing all our queries)
✓ You can create new tables under this database. Write queries in the query builder workspace. To save the result of any query in the database
you have to press the commit option or type commit.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 29


ORACLE
2. Checking with the default databases present:
Open Sqldeveloper: (here we will be performing all our queries)
✓ You can create new tables under this database. Write queries in the query builder workspace. To save the result of any query in the database
you have to press the commit option or type commit.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 30


ORACLE
2. Checking with the default databases present:
Open Sqldeveloper: (here we will be performing all our queries)
✓ After completion of your task you have to disconnect the connection. Right click on the database and disconnect.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 31


ORACLE
3. ***Creating a new connection(database) : recommended before doing any experiments

Open Sqldeveloper:

✓ Click on oracle connections and click on the + symbol .


1. Give a database name.
2. Type ‘system’ as username and the password (which you have given during installation)
3. Give the port number as given during installation. Default is 1521, you can change it during installation.
4. Give the SID number as given during installation. Default is ocrl, you can change during installation.
5. Press test.
6. After successful test, press connect and type the password given in step 2.
7. Every time you have to use this username and password while creating a connection to the database created above.
8. Also you can create a new user and grant access to the user to access this database.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 32


ORACLE
3. ***Creating a new connection(database) : recommended for storing your tables

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 33


ORACLE
3.***Creating a new connection(database) : recommended for storing your tables

✓ You can also create a database with an user which you have created .
How to create user:
1. Open sqlplus
2. Log in by default id : ‘/’ as sysdba.
3. create an user:
• Syntax: create user username identified by password.
4. Grant access to the user
• Syntax: grant all privileges to username;
5. Example:

SQL> create user abc identified by abc;

User created.

SQL> grant all privileges to abc;

Grant succeeded.

3/29/2022 By Dr. Manomita Chakraborty, SCOPE, VIT-AP UNIVERSITY 34


SQL CONSTRAINTS
NOT NULL CONSTRAINT

✓ The NOT NULL constraint specifies that the column does not accept NULL values.

✓ The following SQL statement creates a table named persons with four columns, out of which three columns,
id, name and phone do not accept NULL values.

CREATE TABLE persons (


id INT NOT NULL,
name VARCHAR(30) NOT NULL,
birth_date DATE,
phone VARCHAR(15) NOT NULL
);

**A null value or NULL is different from zero (0), blank, or a zero-length character string such as ''. NULL means that no entry
has been made.

3/29/2022 35
SQL CONSTRAINTS
PRIMARY KEY Constraint
✓ The PRIMARY KEY constraint identify the column or set of columns that have values that uniquely identify a row
in a table.

✓ No two rows in a table can have the same primary key value. Also, you cannot enter NULL value in a primary key
column.

✓ The following SQL statement creates a table named persons and specifies the id column as the primary key.
That means this field does not allow NULL or duplicate values..

CREATE TABLE persons (


id INT NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL,
birth_date DATE,
phone VARCHAR(15) NOT NULL
);

3/29/2022 36
SQL CONSTRAINTS
UNIQUE Constraint
✓ The UNIQUE constraint restricts one or more columns to contain unique values within a table..

✓ Although both a UNIQUE constraint and a PRIMARY KEY constraint enforce uniqueness, use a UNIQUE constraint
instead of a PRIMARY KEY constraint when you want to enforce the uniqueness of a column, or combination of
columns, that is not the primary key..

✓ The following SQL statement creates a table named persons and specifies the phone column as unique.
That means this field does not allow duplicate values.

CREATE TABLE persons (


id INT NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL,
birth_date DATE,
phone VARCHAR(15) NOT NULL
UNIQUE
);

*** Multiple UNIQUE constraints can be defined on a table, whereas only one PRIMARY KEY constraint can be defined on a table. Also, unlike PRIMARY KEY
constraints, the UNIQUE constraints allow NULL values.
3/29/2022 37
SQL CONSTRAINTS
DEFAULT Constraint
✓ The DEFAULT constraint specifies the default value for the columns.

✓ A column default is some value that will be inserted in the column by the database engine when an INSERT statement
doesn't explicitly assign a particular value.

✓ The following SQL statement creates a default for the country column..

CREATE TABLE persons (


id INT NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL,
birth_date DATE,
phone VARCHAR(15) NOT NULL
UNIQUE,
country VARCHAR(30) NOT NULL
DEFAULT 'Australia'
);

3/29/2022 38
SQL CONSTRAINTS
FOREIGN KEY Constraint
✓ A foreign key (FK) is a column or combination of columns that is used to establish and enforce a relationship between
the data in two tables.

✓ The following statement establishes a foreign key on the dept_id column of the employees table that references the dept_id
column of the departments table.
CREATE TABLE employees (
emp_id INT NOT NULL PRIMARY KEY,
emp_name VARCHAR(55) NOT NULL,
hire_date DATE NOT NULL,
salary INT,
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES
departments(dept_id)
);
3/29/2022 39
SQL CONSTRAINTS
CHECK Constraint
✓ The CHECK constraint is used to restrict the values that can be placed in a column.

✓ For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows values
only from 3,000 to 10,000.

CREATE TABLE employees (


emp_id INT NOT NULL PRIMARY KEY,
emp_name VARCHAR(55) NOT NULL,
hire_date DATE NOT NULL,
salary INT NOT NULL CHECK (salary >= 3000 AND salary
<= 10000),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES
departments(dept_id)
);

3/29/2022 40
Behavior of foreign key
✓ The foreign key is defined in the child table and the parent table contains the reference column. However because of this
link we cannot update or delete the rows of the parent table.

✓ When you define a simple foreign key, the Oracle engine is by default set to ON DELETE NO ACTION clause. This
means that you are allowed to update the rows in the parent table however you cannot delete rows from the parent table.
This default behavior is called Restrict rule.

✓ In Oracle Database you get two referential actions to override the restrict rule and change the default behavior of
foreign key. These two referential actions are –

1. ON DELETE SET NULL


2. ON DELETE CASCADE

3/29/2022 41
FOREIGN KEY WITH CASCADE DELETE
✓ Because of the cascade delete, when a record in the supplier table is deleted, all records in the products table will also be
deleted that have the same supplier_id value..

CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE
);

**

3/29/2022 42
FOREIGN KEY WITH ON DELETE SET NULL
✓ On Delete Set Null clause sets all the records of the column which is defined as a foreign key in the child table to Null if
the corresponding record in the parent table is deleted..

✓ Because of ON DELETE SET NULL, when a record in the supplier table is deleted, all records in the products table will
be set to NULL that have the same supplier_id value.

CREATE TABLE supplier


( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE SET NULL
);
3/29/2022 43
SQL FUNCTIONS
SQL Scalar functions
SQL Aggregate Functions
SQL scalar functions return a single value, based on the input
SQL aggregate functions return a single value, calculated from
value.
values in a column.
Useful scalar functions:
Useful aggregate functions:
UCASE() - Converts a field to upper case
AVG() - Returns the average value
LCASE() - Converts a field to lower case
COUNT() - Returns the number of rows
MID() - Extract characters from a text field
FIRST() - Returns the first value
LEN() - Returns the length of a text field
LAST() - Returns the last value
ROUND() - Rounds a numeric field to the number of decimals
MAX() - Returns the largest value
specified
MIN() - Returns the smallest value
NOW() - Returns the current system date and time
SUM() - Returns the sum
FORMAT() - Formats how a field is to be displayed

Check the below link for examples:


http://www-db.deis.unibo.it/courses/TW/DOCS/w3schools/sql/sql_func_avg.asp.html

3/29/2022 44
SQL GROUP BY
✓ The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each
country".

✓ The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-
set by one or more columns.

TABLE CUSTOMERS
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s);

This would produce the following result:

EXAMPLE:
SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;

3/29/2022 45
SQL ORDER BY
✓ The ORDER BY keyword is used to sort the result-set in ascending or descending order.

✓ The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC
keyword..

SELECT column1, column2, ...


SELECT * FROM Student ORDER BY
FROM table_name
ROLL_NO DESC;
ORDER BY column1, column2, ... ASC|DESC;

TABLE STUDENT This would produce the following result:

ROLL_NO NAME ADDRESS PHONE Age


8 NIRAJ ALIPUR XXXXXXXXXX 19
7 ROHIT BALURGHAT XXXXXXXXXX 18
6 DHANRAJ BARABAJAR XXXXXXXXXX 20
5 SAPTARHI KOLKATA XXXXXXXXXX 19
4 DEEP RAMNAGAR XXXXXXXXXX 18
3 RIYANKA SILIGURI XXXXXXXXXX 20
2 PRATIK BIHAR XXXXXXXXXX 19
1 HARSH DELHI XXXXXXXXXX 18
3/29/2022 46
SQL ORDER BY
SELECT * FROM Student ORDER BY Age ASC , ROLL_NO DESC;

TABLE STUDENT This would produce the following result:

ROLL_NO NAME ADDRESS PHONE Age

7 ROHIT BALURGHAT XXXXXXXXXX 18

4 DEEP RAMNAGAR XXXXXXXXXX 18

1 HARSH DELHI XXXXXXXXXX 18

8 NIRAJ ALIPUR XXXXXXXXXX 19

5 SAPTARHI KOLKATA XXXXXXXXXX 19

2 PRATIK BIHAR XXXXXXXXXX 19

6 DHANRAJ BARABAJAR XXXXXXXXXX 20

3 RIYANKA SILIGURI XXXXXXXXXX 20

3/29/2022 47
SQL HAVING
The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions;

Following is an example, display the state and number of customers in each state where the salary is greater than 10000 and the
number of customers are more than or equal to 2.
SELECT state, COUNT(*) AS "Number of customers"
FROM customers
WHERE salary > 10000
TABLE customers GROUP BY state
HAVING COUNT(*) >= 2;

This would produce the following result:

3/29/2022 48

You might also like