kensri school and college, bengaluru structured query ...sep 05, 2019  · kensri school and...

22
Kensri School and College, Bengaluru Computer Science 1 Class 12/PU-II Structured Query Language (SQL) Structured Query Language and it helps to make practice on SQL commands which provides immediate results. 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. All relational database management systems like MySQL, MS Access, and Oracle, Sybase, Informix, and SQL Server use SQL as standard database language. SQL is the set of commands that is recognized by all RDBMS. The Structured Query Language (SQL) is a language that enables you to create and operate on relational database, which are sets of related information stored in tables. The SQL (Structured Query Language) has proved to be a standard language as it allows users to learn one set of command and use it to create, retrieve, alter, and transfer information regardless of whether they are working on a PC, a workstation, a mini, or a mainframe. MySQL Database System is a combination of a MySQL server instance and a MySQL database. MySQL database system operates using client/server architecture, in which the server runs on the machine containing the databases and clients connect to the server over a network. Why SQL? Allows users to create and drop databases and tables. Allows users to describe the data. Allows users to define the data in database and manipulate that data. Allows users to access data in relational database management systems. Allows embedding within other languages using SQL modules, libraries & pre-compilers. Allows users to set permissions on tables, procedures, and views. History 1970: Dr. E. F. “Codd” 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. Features of MySQL: Speed: If the server hardware is optimal, MySQL runs very fast. Ease to use: MySQL is a high-performance, relatively simple database system. Cost: Available free of cost. Query Language Support: Understands standard based SQL. Portability: Provides portability as it has been tested with a broad range of different compiler and can work on many different platforms.

Upload: others

Post on 20-Mar-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Kensri School and College, Bengaluru

Computer Science 1 Class 12/PU-II

Structured Query Language (SQL)

Structured Query Language and it helps to make practice on SQL commands which provides

immediate results.

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.

All relational database management systems like MySQL, MS Access, and Oracle, Sybase,

Informix, and SQL Server use SQL as standard database language.

SQL is the set of commands that is recognized by all RDBMS.

The Structured Query Language (SQL) is a language that enables you to create and operate

on relational database, which are sets of related information stored in tables.

The SQL (Structured Query Language) has proved to be a standard language as it allows

users to learn one set of command and use it to create, retrieve, alter, and transfer information

regardless of whether they are working on a PC, a workstation, a mini, or a mainframe.

MySQL Database System is a combination of a MySQL server instance and a MySQL

database.

MySQL database system operates using client/server architecture, in which the server runs

on the machine containing the databases and clients connect to the server over a network.

Why SQL?

Allows users to create and drop databases and tables.

Allows users to describe the data.

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

Allows users to access data in relational database management systems.

Allows embedding within other languages using SQL modules, libraries & pre-compilers.

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

History

1970: Dr. E. F. “Codd” 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.

Features of MySQL:

Speed: If the server hardware is optimal, MySQL runs very fast.

Ease to use: MySQL is a high-performance, relatively simple database system.

Cost: Available free of cost.

Query Language Support: Understands standard based SQL.

Portability: Provides portability as it has been tested with a broad range of different

compiler and can work on many different platforms.

Kensri School and College, Bengaluru

Computer Science 2 Class 12/PU-II

Data Types: Provide many data types to support different types of data.

Security: Offers a privilege and password system that is very flexible and secure.

Localization: The server can provide error messages to clients in many languages.

Connectivity: Clients can connect to MySQL Server using several protocols.

Client and Tools: Provides command-line programs such as mysqldump and

mysqladmin, and graphical programs such as MySQL Administrator and

MySQL Query Browser.

SQL Server and Clients

MySQL Server :

o Listens for client request coming in over the network

o Accesses database contents according to those requests

o Provides contents to the clients

MySQL Clients:

o MySQL clients are programs that connect to the MySQL server

and issue queries in a pre-specified format.

o MySQL is compatible with the standards based SQL. The client

program may contact the server programmatically or manually.

SQL Architecture:

When you are executing an SQL command for

any RDBMS, the system determines the best way

to carry out your request and SQL engine figures

out how to interpret the task.

There are various components included in the

process.

These components are:

o Query Dispatcher

o Optimization Engines

o Classic Query Engine

o SQL Query Engine, etc.

Classic query engine handles all non-SQL queries

but SQL query engine won't handle logical files.

Advantages of MySQL:

Reliability and performance: MySQL is very reliable and high performance

relational database management system.

Availability of source: MySQL source code is available that is why now we can recompile

the source code.

Cross-Platform support: MySQL supports more than twenty different

platforms including the major Linux distribution. Mac OS X, Unix and

Microsoft Windows.

Powerful uncomplicated software: The MySQL has most capabilities to

handle most corporate database applications and is very easy and fast.

Integrity: MySQL provides forms of integrity checking.

Kensri School and College, Bengaluru

Computer Science 3 Class 12/PU-II

Authorization: MySQL DDL includes commands for specifying access rights to relations

and views.

Processing capabilities of SQL

Data Definition Language (DDL): The SQL DDL provides commands for defining relation

schemas, deleting relations, creating indexes, and modifying relation schemas.

Interactive Data Manipulation Language (DML): The SQL DML includes a query

language based on both the relational algebra and the tuple relational calculus. It also

includes commands to insert, delete, and modify tuples in the database.

Embedded Data Manipulation Language: The embedded form of SQL is designed for use

within general- purpose programming language such as PL/1, Cobol, Fortran, Pascal, and C.

View Definition: The SQL DDL also includes commands for defining views.

Authorization: The SQL DDL includes commands for specifying access rights to relations

and views.

Integrity: The SQL provides forms of integrity checking. Further products and standards of

SQL are likely to include enhanced features for integrity checking.

Transaction control: SQL includes commands for specifying the beginning and ending of

transaction along with commands to have a control over transaction processing.

Classification of SQL Statements

SQL provides many different types of commands used for different purposes. These

commands can be divided into following categories:

1. Data Definition Language (DDL) commands

2. Data Manipulation Language (DML) commands

3. Transaction Control Language (TCL) commands

1. Data Definition Language (DDL) commands

o A database scheme is specified by a set of definitions which are expressed by a special

language called a data definition language (DDL).

o DDL defines the conceptual schema providing a link between the logical and the physical

structure of the database.

o The result of DDL statements is a set of tables which are stored in a special file called

data dictionary.

o A Data Dictionary is a file that contains “metadata” i.e., “data about data”.

o The DDL provides a set of definitions to specify the storage structure and access methods

used by the database system.

DDL functions

o It should identify the types of data division such as data item, segment, record, and data-

base file.

o It should give a unique name to each data-item-type, record-type, file-type, database, and

other data subdivision

o It should specify the proper data types.

o It should specify how the record types are related to each other.

o It describes the schema and subschema.

o It indicate the keys of records.

Kensri School and College, Bengaluru

Computer Science 4 Class 12/PU-II

o It provides data security measures.

o It provides for the logical and physical data independence.

DDL commands

o CREATE :Creates a new table, a view of a table, or other object in database

o ALTER :Modifies an existing database object, such as a table.

o DROP :Deletes an entire table, a view of a table or other object in the database

2. DML - Data Manipulation Language

o Data manipulation means:

Retrieval of information stored in database

Insertion of new information into database

Deletion of information from database

Modification of data stored in database

o A Data Manipulation Language (DML) is a language that enables user to access or

manipulate data as organized by the appropriate data model.

o DML facilitates use of relationship between the records.

o DML provides for independence of programming languages by supporting several high-

level programming languages like COBOL, PL/1 and C++.

DML commands

DML commands query and manipulate data in existing schema objects.

o SELECT : Retrieves certain records from one or more tables

o INSERT INTO: Used to insert a tuple in a table.

o UPDATE : Used to modify a tuple in a table.

o DELETE : Used to delete a tuple in a table.

3. DCL - Data Control Language

o These SQL commands are used for providing security to database objects.

o The different DCL commands are: Command Description GRANT Gives a privilege to

user REVOKE Takes back privileges granted from user.

DCL commands

o GRANT : Gives a privilege to user

o REVOKE :Takes back privileges granted from user.

4. TCL – Transaction Control Language

o It includes commands to control the transactions in a database system.

o To manage and control the transactions, the transaction control commands are used.

These commands manage changes made by DML commands.

TCL commands

o COMMIT :Make all the changes made by the statements issued permanent.

o ROLLBACK :Undoes all changes since the beginning of transaction or since a save

point.

Kensri School and College, Bengaluru

Computer Science 5 Class 12/PU-II

Data Types in SQL.

Data Type Syntax Explanation

INTEGER INTEGER It represent a number without a decimal point.

The range of integer is from -2,147,483,648 to 2,147,483,647.

Width of integer is up to 11 digits.

SMALLINT SMALLINT A 16-bit signed integer value.

The range of SMALLINT is from -32768 to 32767.

Width of SMALLINT is up to 5 digits.

NUMERIC NUMERIC(P,S) For example, numeric(6,2) is a number that has 4 digits before

the decimal and 2 digits after the decimal.

DECIMAL DECIMAL(P,S) For example, decimal(6,2) is a number that has 4 digits before

the decimal and 2 digits after the decimal.

CHARACTER CHAR(X) Where x is the number of characters to store. This data type is

space padded to fill the number of characters specified.

CHARACTER

VARYING

VARCHAR2(X) Where x is the number of characters to store. This data type

does NOT space pad.

DATE DATE Stores year, month, and day values.

TIME TIME Stores the hour, minute, and second values.

TIMESTAMP TIMESTAMP Stores year, month, day, hour, minute, and second values.

BLOB BLOB A field with a maximum length of 65535 characters. BLOBs

are “Binary Large Object” and used to store large amount of

data, such as images or other types of files.

Difference between CHAR and VARCHAR data types

CHAR VARCHAR

The CHAR datatype specifies a fixed length

character string.

VARCHAR specifies a variable length string.

The length should be a number from 0 to 255 The maximum length can be a number up to

65,535.

CHAR(n) will take n characters of storage even if

you enter less than n characters to that column.

VARCHAR(n) will take only the required

storage for the actual number of characters

entered to that column.

If a value is shorter than this length n then blanks

are added.

No blanks are added if the length is shorter

than maximum length n.

With CHAR data type column, search seems

working faster than VARCHAR data type

column

With VARCHAR data type column, search

seems working slower than CHAR data type

column.

SQL Command Syntax

Any SQL command is a combination of keywords, identifiers and clauses.

Every SQL command begins with a keyword (CREATE, SELECT, DELETE and so on)

which as a specific meaning to the language.

Kensri School and College, Bengaluru

Computer Science 6 Class 12/PU-II

Keywords: Keywords are words that have a special meaning and printed in capital letters.

They are understood to be instruction.

Commands or Statements: Commands are instruction given by us to a SQL database.

Commands consist of one or more logically distinct parts called clauses.

Commands in SQL are not case-sensitive but text literals or character literals that we specify

in quotation marks are case- sensitive

Clauses: Clauses begin with a keyword for which they are generally named, and consist of

keywords and arguments.

Arguments: Argument complete or modify the meaning of a clause.

A statement in MYSQL SQL is completed with a semicolon(;).

Symbols used in Syntax Statements:

o | Symbolic way of saying “or”

o {} Everything enclosed in it, is treated as a unit for the purpose of evaluating .

o [] Everything enclosed in it is optional.

o … This means whatever precedes it may be repeated any number of times.

o .,.. Whatever precedes this, may be repeated any number of times with the individual

occurrence separated by commas.

o <> SQL and other special terms are in angle brackets.

Operators in SQL

An operator is a reserved word or a character used primarily in an SQL statement's WHERE

clause to perform operation(s), such as comparisons and arithmetic operations.

Operators are used to specify conditions in an SQL statement and to serve as conjunctions

for multiple conditions in a statement.

o Arithmetic operators (+, -, *, / %)

o Comparison operators (>, <, >=, <=, =, !=, <>, !<, !>)

o Logical operators (AND, OR, NOT, IN, BETWEEN, EXISTS,

ALL, ANY, LIKE, UNIQUE).

o SQL Arithmetic Operators

(Assume a =10 and b = 20)

+ Addition Adds values on either side of the operator

a + b will give 30.

- Subtraction Subtracts right hand operand from left hand operand

a - b will give -10

* Multiplication Multiplies values on either side of the operator

a * b will give 200

/ Division Divides left hand operand by right hand operand

b / a will give 2

Kensri School and College, Bengaluru

Computer Science 7 Class 12/PU-II

% Modulus Divides left hand operand by right hand operand and returns remainder

b % a will give 0

o SQL Comparison Operators:

(Assume a =10 and b = 20)

= Checks if the values of two operands are equal or not, if yes then condition

becomes true.

(a = b) is not true.

!= Checks if the values of two operands are equal or not, if values are not equal

then condition becomes true.

(a != b) is true.

<> Checks if the values of two operands are equal or not, if values are not equal

then condition becomes true.

(a <> b) is true.

> Checks if the value of left operand is greater than the value of right operand, if

yes then condition becomes true.

(a > b) is not true.

< Checks if the value of left operand is less than the value of right operand, if yes

then condition becomes true.

(a < b) is true.

>= Checks if the value of left operand is greater than or equal to the value of right

operand, if yes then condition becomes true.

(a >= b) is not true.

<= Checks if the value of left operand is less than or equal to the value of right

operand, if yes then condition becomes true.

(a <= b) is true.

!< Checks if the value of left operand is not less than the value of right operand, if

yes then condition becomes true.

(a !< b) is false.

!> Checks if the value of left operand is not greater than the value of right operand,

if yes then condition becomes true.

(a !> b) is true.

o SQL Logical Operators:

ALL The ALL operator is used to compare a value to all values in another value

set.

AND The AND operator allows the existence of multiple conditions in an SQL

statement's WHERE clause.

ANY The ANY operator is used to compare a value to any applicable value in the

list according to the condition.

BETWEEN The BETWEEN operator is used to search for values that are within a set of

values, given the minimum value and the maximum value.

EXISTS The EXISTS operator is used to search for the presence of a row in a specified

table that meets certain criteria.

IN The IN operator is used to compare a value to a list of literal values that have

been specified.

Kensri School and College, Bengaluru

Computer Science 8 Class 12/PU-II

LIKE The LIKE operator is used to compare a value to similar values using

wildcard operators.

NOT The NOT operator reverses the meaning of the logical operator with which it

is used.

Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.

OR The OR operator is used to combine multiple conditions in an SQL

statement's WHERE clause.

IS NULL The NULL operator is used to compare a value with a NULL value.

UNIQUE The UNIQUE operator searches every row of a specified table for uniqueness

(no duplicates).

SQL Commands.

CREATE TABLE

o The SQL CREATE TABLE statement is used to create a new table.

o Creating a basic table involves naming the table and defining its columns and each

column's data type.

o Syntax: CREATE TABLE <table-name> ( <column name> <data type> (size)

<column name> <data type> (size)…. );

o Example: CREATE TABLE STUDENT (RegNo NUMBER (6),

Name VARCHAR2 (15),

Combination CHAR (4),

DOB DATE,

Fees NUMBER (9, 2),

PRIMARY KEY ( RegNo ) );

o It creates an empty STUDENT table which looks like bellow:

RegNo Name Combination DOB Fees

o To View the table information:

o The DESCRIBE or DESC

command displays name of the

columns, their data type and size

along with the constraints.

o Syntax: DESC <table-name>

o Example: DESC STUDENT

SQL Constraints

Constraints are the rules enforced on data columns on table.

These are limiting the type of data that can go into a table.

This ensures the accuracy and reliability of the data into the database.

SQL allows two types of constraints.

o Column level constraints: These constraints are defined along with the column definition

when creating or altering a table structure. These constraints apply only to individual

columns.

o Table level constraints: These constraints are defined after all the table columns when

creating or altering a table structure. These constraints apply to groups of one or more

columns.

Kensri School and College, Bengaluru

Computer Science 9 Class 12/PU-II

1. NOT NULL Constraint

By default column can hold NULL values.

When a column is defined as NOT NULL then the column becomes a mandatory column.

It implies that a value must be entered into the column if the row is to be inserted for storage

in the table.

The NOT NULL constraint enforces a column to NOT accept NULL values.

Example: CREATE TABLE emp ( Eno integer NOT NULL,

Ename char(20) NOT NULL,

Job char(20) NOT NULL,

Salary decimal);

The above table enforces the Eno column and the Ename column to not accept NULL

values.

2. UNIQUE Constraint

This constraint ensure that no two rows have the same value in the specified columns. A

table must have many unique keys.

When applied to the columns ensure that there cannot exist more than one NULL value in

the column.

Example: CREATE TABLE emp ( Eno integer NOT NULL UNIQUE,

Ename char(20) NOT NULL,

Job char(20) NOT NULL,

Salary decimal );

3. Primary Key Constraint

This constraint declares a column as primary key of the table.

Only one column or one combination can be applied in this constraint.

A primary key is a field which uniquely identifies each row in a database table. A primary

key in a table has special attributes.

The primary key cannot allow NULL values, thus this constraints must be applied to

columns declared as NOT NULL.

Example : CREATE TABLE emp ( Eno integer NOT NULL PRIMARY KEY,

Ename char(20) NOT NULL,

Job char(20) NOT NULL,

Salary decimal );

4. Default Constraint:

A default value can be specified for a column using the DEFAULT clause.

When a user does not enter a value for the column, automatically the defined default value is

inserted in field.

A column can have only one default value.

Kensri School and College, Bengaluru

Computer Science 10 Class 12/PU-II

A default value can be specified for a column using the DEFAULT clause.

The DEFAULT constraint provides a default value to a column when the INSERT INTO

command does not provide a specific value.

Example: CREATE TABLE EMP ( ENO INTEGER NOT NULL PRIMARY KEY,

ENAME CHAR(20) NOT NULL,

JOB CHAR(20) DEFAULT = „CLERK‟,

SALARY DECIMAL );

Here, if no value is provided for job, the default value of ‟CLERK‟, will be entered.

5. Check Constraint:

This constraint limits values that can inserted into a column of table. Check constraint will

not work because The CHECK clause is parsed but ignored by all storage engines.

The CHECK Constraint is used to establish a TRUE/FALSE condition that is applied to the

data placed in a column.

If a value does not meet the condition, it cannot be placed in the column.

Example: CREATE TABLE emp (ENO INTEGER NOT NULL PRIMARY KEY ,

ENAME CHAR(20) NOT NULL,

JOB CHAR(20) NOT NULL,

SALARY DECIMAL CHECK > 2000 );

This statement ensure that the value inserted for salary must be greater than 2000.

When a check constraint involves more than one column from the same table, it is specified

after all the column have been defined.

6. FOREIGN KEY Constraint

A FOREIGN KEY is used to link two tables together.

A foreign key is a column whose values are derived from the PRIMARY KEY of some other

table.

Tables references one another through common fields and to ensure validity of references,

referential integrity is enforced.

Referential integrity is ensured through FOREIGN KEY constraint.

Example: CREATE TABLE Persons(P_Id integer(10) NOT NULL PRIMARY KEY

Name char(10), Address char(20), City char(20) );

CREATE TABLE Orders(O_Id integer(10), Ono integer(10),

P_Id integer(10) REFERENCES Persons(P_Id));

NOTE: The foreign key constraint can also be applied through FOREIGN FEY table

constraint, which we will see in letter slides.

Kensri School and College, Bengaluru

Computer Science 11 Class 12/PU-II

7. TABLE Constraints

When a constraint is applied to a group of columns of the table, it is called a table constraint.

Column constraint is defined along with the end of the column.

Table constraints are defined at the end of the table.

Example: CREATE TABLE items(icode char(5) NOT NULL ,

descp char(20) NOT NULL,

ROL integer,

QOH integer,

CHECK (ROL < QOH),

PRIMARY KEY (icode, descp) );

The above statement define a primary key that have two columns namely icode and descp. It

also ensures that the ROL must be less than QOH in each row.

SQL Commands.

Creating Databases:

The CREATE DATABASE command is used to create a database.

Syntax: CREATE DATABASE [IF NOT EXISTS] <database name>;

The IF NOT EXISTS clause, if used, will first test whether a database by mentioned name

already exists or not. If exists, then create database command is simply ignored, otherwise a

database with the mentioned name is created.

Example: CREATE DATABASE SampleDB;

The above quary Creates database having name as SampleDB

CREATE DATABASE IF NOT EXISTS SampleDB;

The above quary Creates database having name as SampleDB,

If there is no database by the name SampleDb already existing.

Opening Databases:

To perform operation on database we first need to open database.

Syntax: USE <database name>;

Example: USE SampleDB;

Before opening a database we need to ensure that it must already exist. To check the names of

existing database, following command is used:

SHOW DATABASES;

Removing Databases:

When we drop a database, all its tables also get removed along with the database.

Syntax: DROP DATABASE <database name>;

Example: DROP DATABASE SampleDB;

Kensri School and College, Bengaluru

Computer Science 12 Class 12/PU-II

CREATE TABLE Command.

The CREATE TABLE statement is used to create a table in a database.

Each table must have at least one column.

Syntax: CREATE TABLE <table-name> ( <column name> <data type> [ (size)],

<column name> <data type> [ (size) …] );

Example: CREATE TABLE emp ( Eno integer,

Ename char(20),

Job char(20),

Mgr integer(10),

Hiredate date,

Sal decimal,

Comm decimal,

Dno integer );

NOTE: When create a table, we can place constraint on the values that can be entered into its

fields, which we have seen in previous slides.

emp Table

Eno Ename Job Mgr Hiredate Sal Comm Dno

Creating Table from Existing Table:

By using SELECT statement with CREATE TABLE we can define table and put data into it

without going through the usual data definition process..

The new table stores the result produced by the SELECT statement.

The name of the new table must be unique..

Example: CREATE TABLE emp_info AS ( SELECT eno,

ename FROM emp WHERE eno > 122 );

Above statement create a new table called emp_info that stores two columns: eno and ename

for the employees that have eno grater than 122 in relation emp.

Viewing a Table Structure:

To view the structure of an already created/existing table, we may use DESCRIBE or DESC

command is used.

Syntax: DESCRIBE | DESC <tablename> ;

Example: DESC emp; or DESCRIBE emp;

Inserting Data Into Table

1. INSERT INTO Command:

INSERT INTO command is used to add rows to relations.

Syntax: INSERT INTO <tablename> [ <column list> ]

VALUES ( <value>, <value> …. );

Example: INSERT INTO emp

VALUES (142, „SAMIR‟, „CLERK‟, 125, 21-MAY-81, 5000, 500, 20);

Kensri School and College, Bengaluru

Computer Science 13 Class 12/PU-II

Example: INSERT INTO emp (eno, ename, job, mgr, hiredate, sal, comm, dno)

VALUES (142, „SAMIR‟, „CLERK‟, 125, 21-MAY-81, 5000, 500, 20);

Note that the data values are in the same order as the column names in the table.

Data can be added only to some columns in a row by specifying the columns.

Example: INSERT INTO emp (eno, ename, job)

VALUES (199, „TEENA‟, „MANAGER‟, );

In an INSERT statement, only those columns can be skipped that columns have either default

value defined or they allow NULL values.

emp Table

Eno Ename Job Mgr Hiredate Sal Comm Dno

142 SAMIR CLERK 125 21-MAY-81 5000 500 20

199 TEENA MANAGER

2. Inserting NULL values

NULL value can be inserted in to a column by typing NULL without quotes.

Example: INSERT INTO emp (eno, ename, job, mgr, hiredate, sal, comm, dno)

VALUES (242, „RAVI‟, NULL, 135, 21-JUNE-19, 4000, NULL, 20);

Here, for Mgr and Comm columns, NULL values have been inserted.

emp Table

Eno Ename Job Mgr Hiredate Sal Comm Dno

142 SAMIR CLERK 125 21-MAY-81 5000 500 20

199 TEENA MANAGER

242 RAVI NULL 135 21-JUNE-19 4000 NULL 20

3. Inserting Data from Another Table:

INSERT INTO can also be used to take values from one table and place them in another table.

Example: INSERT INTO emp (eno, ename, sal) SELECT emp_no, ename, sal

FROM Temp WHERE Months > 24 ;

It will extract all those rows from Temp that have months more than 24 and insert this

produced results into the table emp.

To insert using a query, the following conditions must be true:

o Both the tables must be already created.

o The columns of the tables being inserted into, must match the columns output by the

subquery.

Modifying Data with UPDATE Command:

UPDATE command is used for change some or all of the values in exciting row.

The UPDATE command specifies the rows to be changed using the WHERE clause, and the

new data using the SET keyword.

Example: UPDATE emp SET sal = 1500 WHERE sal = 5000 ;

Above statement change sal to 1500 only for that employees that have sal as 5000.

Kensri School and College, Bengaluru

Computer Science 14 Class 12/PU-II

1. Updating Multiple Columns:

To update multiple columns, multiple column assignment can be specified with SET clause,

separated by commas.

Example: UPDATE emp SET sal = 5500, comm = 200 WHERE eno > 200 ;

Above statement change sal to 5500 and comm to 200 for employees having eno greater than

200.

2. Updating to NULL Values:

The NULL values can also be entered just as other values by using UPDATE command.

Example: UPDATE emp SET job = NULL WHERE eno = 199 ;

Above statement insert a NULL values to column comm for employees that have eno as 199.

emp Table

Eno Ename Job Mgr Hiredate Sal Comm Dno

142 SAMIR CLERK 125 21-MAY-81 1500 500 20

199 TEENA NULL

242 RAVI NULL 135 21-JUNE-19 5500 200 20

3. Using Expression in Update:

Scalar expression can be used in the SET clause of the UPDATE command.

Example: UPDATE emp SET sal = sal * 2 WHERE ( eno = 142 OR eno = 126 ) ;

Above statement double the salary of employees having eno 142 or 126.

Eno Ename Job Mgr Hiredate Sal Comm Dno

142 SAMIR CLERK 125 21-MAY-81 3000 500 20

199 TEENA NULL

242 RAVI NULL 135 21-JUNE-19 5500 200 20

Deleting Data with DELETE Command:

The DELETE command removes rows from a table.

Removes the entire rows, not individual field values.

No field argument is needed or accepted.

Syntax: DELETE FROM <tablename> [ WHERE <predicate> ] ;

Example : DELETE FROM emp;

Above statement removes all the contents of emp table.

Some specific rows can also be deleted by using condition as shown below:

Example : DELETE FROM emp WHERE sal > 3000 ;

Above statement removes all the rows from emp table that have sal greater than 3000.

ALTER TABLE Command

The ALTER TABLE command is used to change definition of existing tables.

ALTER TABLE is used:

1. To add a column

2. To add an integrity constraint

3. To redefine a column (datatype, size, default value).

Kensri School and College, Bengaluru

Computer Science 15 Class 12/PU-II

1. Adding Columns

The new column will be added with NULL values for all rows currently in the table.

Several new columns can be added, separated by commas, in a single command.

It may be possible to drop or alter columns.

Syntax: ALTER TABLE <table name> ADD <column name> <data type><size> [

<constraint name>] ;

Example: ALTER TABLE emp ADD ( Ph_no integer) ;

Above statement add a new column Ph_no of type integer in table emp.

emp Table

Eno Ename Job Mgr Hiredate Sal Comm Dno Ph_no

142 SAMIR CLERK 125 21-MAY-81 3000 500 20

199 TEENA NULL

242 RAVI NULL 135 21-JUNE-19 5500 200 20

2. Changing a Column Name

For changing the name of the column CHANGE clause of ALTER TABLE command is used.

Syntax: ALTER TABLE<TABLENAME> CHANGE [ COLUMN ]

old_col_name new_col_name column_defination ;

Example: ALTER TABLE emp CHANGE Sal Salary DECIMAL ;

Here, complete column description is given along with the new name.

Above statement change the existing column namely Sal of table emp to Salary.

emp Table

Eno Ename Job Mgr Hiredate Salary Comm Dno Ph_no

142 SAMIR CLERK 125 21-MAY-18 3000.00 500 20

199 TEENA NULL

242 RAVI NULL 135 21-JUNE-19 5500.00 200 20

3. Modifying Column Definition:

By using the MODIFY clause we can change any of the following parts of a column definition:

Datatype: We can change any column‟s datatype if all rows for the column contains nulls.

Default value: We can decrease any column‟s size if all rows for the column contains nulls

whereas we can always increase the size or the precision of a column.

Integrity Constraint: By using the MODIFY clause we can add only NOT NULL constraint

to an existing column.

Order of column: With MODIFY clause we can reorder the columns within a table by using

FIRST or AFTER<colname> clause.

Syntax: ALTER TABLE <table name>

MODIFY (column name newdatatype (newsize)) [ FIRST | AFTER column] ;

Example: ALTER TABLE emp MODIFY ( Job char(30) ) ;

Above statement modify column Job of table emp to have new width of 30 characters.

ALTER TABLE emp MODIFY Ename Char FIRST ;

Above statement reorder an existing column say Ename to be the first column in the table emp.

Kensri School and College, Bengaluru

Computer Science 16 Class 12/PU-II

emp Table

Ename Eno Job Mgr Hiredate Salary Comm Dno

SAMIR 142 CLERK 125 21-MAY-81 3000.00 500 20

TEENA 199 NULL

RAVI 242 NULL 135 21-JUNE-19 5500.00 200 20

DROP Command

1. The DROP TABLE Command:

The SQL DROP TABLE statement is used to remove a table definition and all data, indexes,

triggers, constraints, and permission specifications for that table.

Syntax: DROP TABLE [IF EXISTS] <tablename> ;

Example: DROP TABLE emp;

Above statement drop the table namely emp from the database.

The IF EXISTS clause first checks whether the given table exists in the database or not.

Example: DROP TABLE IF EXISTS emp;

Above statement first check for existence of emp table in current database and then drop the

table namely emp from the database.

2. The DROP VIEW Command:

Used for delete a view from database.

When view is dropped it does not cause any change in its base table.

Example: DROP VIEW taxpayee ;

Above statement drops the view taxpayee from the database.

SELECT Command

1. The SELECT Command

The SELECT statement can be used to retrieve a subset of rows or columns from one or more

tables.

Syntax: SELECT <column name> [, <column name>, … ] FROM <table name> ;

Example : SELECT ename, job, sal FROM emp;

Above statement display the information of columns ename, job and sal as shown below:

Ename Job Salary

SAMIR CLERK 3000.00

TEENA NULL

RAVI NULL 5500.00

2. Selecting All Columns:

To select all the columns from the table the asterisk (*) can be used.

Syntax: SELECT* FROM <table name> ;

Example : SELECT * FROM emp;

Above statement display all the rows present in the emp table as shown below:

Kensri School and College, Bengaluru

Computer Science 17 Class 12/PU-II

Ename Eno Job Mgr Hiredate Salary Comm Dno

SAMIR 142 CLERK 125 21-MAY-81 3000.00 500 20

TEENA 199 CLERK 165 2000.00 30

RAVI 242 NULL 125 21-JUNE-19 5500.00 200 20

3. Selecting From All the Rows – ALL keyword

With ALL keyword the result retains the duplicate output rows.

Syntax : SELECT ALL <column name> FROM <table name>;

Example : SELECT ALL job FROM emp;

Above statement display values of job column from every row of the table without

considering the duplicate entries as shown below:

Job

CLERK

CLERK

NULL

4. Selecting Specific Rows – WHERE clause:

The WHERE clause in SELECT statement specifies the criteria for selection of rows to be

returned.

With the use of WHERE clause, only those rows that satisfied the given condition are

displayed in the output.

Syntax: SELECT <column name> [, <column name>, ….. ] FROM <table name>

WHERE <condition> ;

Example : SELECT eno, ename, sal FROM emp WHERE sal < 4000 ;

Above statement display the eno, ename and sal for employees having salary less than 4000

and outputs the result as shown below:

Eno Ename Salary

142 SAMIR 3000.00

199 TEENA 2000.00

Eliminating Redundant Data - DISTINCT keyword

The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement.

Only one NULL value is returned in the results with DISTINCT keyword.

DISTINCT applies to entire output row, not a specific field.

The DISTINCT keyword can be specified only once in a given SELECT clause.

Syntax: SELECT DISTINCT <column-name> FROM <table-name>;

Example : SELECT DISTINCT job FROM emp;

Above statement display job column as shown below:

Job

CLERK

NULL

Kensri School and College, Bengaluru

Computer Science 18 Class 12/PU-II

Reordering Columns in Query Results

While giving a querying, the result can be obtained in any order.

Example : SELECT <column-name>,<column-name>,…FROM <table-name>;

Example : SELECT job, ename, salary, hiredate FROM emp;

Above statement display job as first column, ename as second column, sal as third column and

hire_date as forth column as shown below:

Job Ename Salary Hiredate

CLERK SAMIR 3000.00 21-MAY-81

NULL TEENA 2000.00

NULL RAVI 5500.00 21-JUNE-19

Simple Calculations

1. Method 1

The SELECT statement is used to perform simple calculations and to retrieve rows computed

without reference to any table.

Example : SELECT 1 + 6 ;

Above statement computes the expression 1 + 6 as shown below:

1 + 6

7

2. Method 1 (DUAL)

To perform simple calculations we can also use table DUAL, which is one row, one column

dummy table.

Example : SELECT 4 * 3 FROM dual ;

Above statement computes the expression 4 * 3 as shown below:

4 * 3

12

Using Column Aliases:

Using column alias name we can give a different name to a columns for output purposes.

If alias name contains more than one word, than we have to enclose them in quotes.

Syntax: SELECT <columnname> AS [columnalias]

[<columnname> AS [columnalias] ] …….FROM <tablename> ;

Example : SELECT ename, eno, job AS “Emp Post” FROM emp ;

Above statement give column Job a alias name Designation as shown below:

Ename Eno Emp Post

SAMIR 142 CLERK

TEENA 199 CLERK

RAVI 242 NULL

Handling Nulls:

When we list a column having null values, only non-null values are displayed.

If we want to replace null with a value in the output, we can use IFNULL( ) function.

The result of expression given with

SELECT

The result of expression given with

DUAL

Kensri School and College, Bengaluru

Computer Science 19 Class 12/PU-II

The value being replaced for Null values through IFNULL( ), should be of the same type as

that of the column.

Syntax: IFNULL ( <columnname>, value-to-be-substituted )

Example : SELECT ename, eno, IFNULL (comm, “Zero”) FROM emp ;

Above statement substitute value zero for null in comm as shown below:

Ename Eno IFNULL (comm, “Zero”)

SAMIR 142 500

TEENA 199 Zero

RAVI 242 200

We can also use column alias to replace output heading.

Example : SELECT ename, eno, IFNULL (comm, “Zero”)

AS “Commission Earned” FROM emp ;

Above statement give column Comm a alias name “Commission Earned” as shown below:

Ename Eno Commission Earned

Putting Text in the Query Output:

SQL enables us to putting some items as symbols and comment in the output.

We can insert text in our query also, to making it more presentable.

Example : SELECT ename, „gets the salary‟, sal, „/-‟ FROM emp ;

Above statement give column Comm a alias name “Commission Earned” as shown below:

Ename gets the salary Salary /-

SAMIR gets the salary 3000.00 /-

TEENA gets the salary 2000.00 /-

RAVI gets the salary 5500.00 /-

SQL Operators

1. Arithmetic Operator (Scalar Expression with Selected Fields)

In SQL we can place scalar expression and constant among the selected fields.

If value in the expression is NULL then result of expression will be NULL only.

The operators used in arithmetic expressions are plus (+), minus (-), divide (/), multiply(*),

and modulo (%).

Example : SELECT ename, sal + 200 FROM emp ;

Above statement add 200 to every row of column sal as shown below:

Ename Salary

SAMIR 3200.00

TEENA 2200.00

RAVI 5700.00

2. Relational Operator:

Relational operator is used to compare two values.

Result of comparison is true or false.

Kensri School and College, Bengaluru

Computer Science 20 Class 12/PU-II

The SQL recognizes following relational operators: =, >, <, >=, <=, <> (not equal to)

In CHARACTER data type comparison, < means earlier in the alphabet and > means later in

the alphabet.

Apostrophes are necessary around all CHAR, DATE and TIME data.

Example : SELECT eno, ename, job FROM emp WHERE job = „CLERK‟;

Above statement display the eno, ename and sal for employees having job as clerk and outputs

the result as shown below:

Eno Ename Job

142 SAMIR CLERK

199 TEENA CLERK

3. Logical Operators:

The logical operators OR (||), AND (&&), and NOT (!) are used to connect search conditions

in the WHERE clause.

When all the logical operators are used together, the order of precedence is

NOT (!), AND (&&), and OR(||).

To list the employee‟s details having Job as „CLERK‟ or „MANAGER‟ from table emp,

logical operator OR will be used as:

Example: SELECT eno, ename, job, sal FROM emp WHERE

( job = „CLERK‟ OR job = „MANAGER‟ );

Eno Ename Job

142 SAMIR CLERK

199 TEENA CLERK

SELECT eno, ename, job, sal FROM emp WHERE ( job = „CLERK‟ AND sal > 2000);

Eno Ename Job Sal

142 SAMIR CLERK 3000.00

242 RAVI NULL 5500.00

Condition Based on a Range (BETWEEN Operator)

The Between operator defines a range of values that the column must fall in to make the

condition true.

The range includes both lower and the upper value.

Example : SELECT eno, ename, sal FROM emp WHERE sal

BETWEEN 1000 AND 5000 ;

Above statement display the employees having salary between 1000 to 5000 as shown below:

Ename Eno Sal

SAMIR 142 3000.00

TEENA 199 2000.00

Kensri School and College, Bengaluru

Computer Science 21 Class 12/PU-II

Condition Based on a List (IN Operator)

To specify a list of values, IN operator is used.

The IN operator selects values that match any value in a given list of values.

Example :SELECT eno, ename, job FROM emp

WHERE job IN(„CLERK‟, „MANAGER‟, „ANALYST‟);

Above statement display a list of employees from „MANAGER‟ or „CLERK‟ as shown

below:

Ename Eno Job

SAMIR 142 CLERK

TEENA 199 MANAGER

NOT IN Operator

The NOT IN operator finds rows that do not match in the list.

Example : SELECT eno, ename, job FROM emp WHERE job

IN(„CLERK‟,‟MANAGER‟, „CLERK‟, „SALESMAN‟);

Above statement list employees which have not job as mentioned in the list.

Ename Eno Job

RAVI 242 NULL

Condition Based on Pattern Matches

In SQL string-matching operator LIKE is used for comparison on character strings using

patterns.

Patterns are described using two special wildcard characters as following:

o Percent (%) – The % character matches any substring.

o Underscore (_) – The _ character matches any substring.

Patterns are case-sensitive. For example :

o „Ran%‟ matches any string beginning with „Ran‟.

o „%idge%‟ matches any string containing „idge‟ as a substring.

o „-------‟ matches any string of exactly 4 characters.

o „--------%‟ matches any string of at least 3 characters.

Example : SELECT eno, ename, mgr FROM emp WHERE mgr LIKE ‟12%‟;

Above statement list employees which have mgr starting with 12 as shown below:

Searching for NULL

The NULL value in a column can be searched for in a table using IS NULL in a WHERE

clause.

Non-NULL values can be listed using IS NOT NULL.

Example : SELECT eno, ename, job FROM emp WHERE dno IS NULL ;

Ename Eno Mgr

SAMIR 142 125

RAVI 242 125

Kensri School and College, Bengaluru

Computer Science 22 Class 12/PU-II

Above statement list employees which have dno as NULL as shown below:

Eno Ename Job

199 TEENA NULL

SORT

1. Sorting Results – ORDER BY clause

The ORDER BY clause allows sorting of query results by one or more columns.

The sorting can be done either in ascending or descending order, the default order is

ascending.

Syntax: SELECT <column name> [, <column name> , … ] FROM

<table name> [WHERE <predicate> ] [ ORDER BY <column name> ];

Example : SELECT eno, ename, job FROM emp ORDER BY ename;

Above statement list employee‟s detail in alphabetical order of their names as shown below:

Eno Ename Job

242 RAVI NULL

142 SAMIR CLERK

199 TEENA NULL

Descending order is specified by DESC.

Ascending order is specified by ASC.

Ordering can be performed on multiple attributes, separated by commas.

Example: SELECT eno, ename, job FROM emp ORDER BY Ename DESC;

Above statement list employee‟s detail in descending order of their of job and ascending order

of name as shown below:

Eno Ename Job

199 TEENA NULL

142 SAMIR CLERK

242 RAVI NULL

2. Sorting by Column Alias:

Column alias can be used for sorting records because once a column alias is declared, it can be

used elsewhere in the statement.

Example : SELECT eno, ename, job “Emp Post” FROM emp

ORDER BY “Emp Post”;

Above statement list employee‟s detail in alphabetical order of their jobs by using column

alias as shown below:

Eno Ename Emp Post

142 SAMIR CLERK

199 TEENA NULL

242 RAVI NULL