chapter:12 structured query language(sql) history history sequel (structures english query language)...

101
Chapter:12 Chapter:12 Structured Query Structured Query Language(SQL) Language(SQL) History History SEQUEL (Structures English QUery Language) – SEQUEL (Structures English QUery Language) – early 70’s, IBM Research early 70’s, IBM Research SQL (ANSI 1986), SQL1 or SQL86 SQL (ANSI 1986), SQL1 or SQL86 SQL2 or SQL92 SQL2 or SQL92 SQL3 or SQL99 SQL3 or SQL99 Core specification and optional Core specification and optional specialized packages specialized packages SQL consists of ~20 basic commands SQL consists of ~20 basic commands A lot of research money for each SQL A lot of research money for each SQL command… command… Standard language for all commercial DBMS Standard language for all commercial DBMS

Upload: deirdre-allison

Post on 22-Dec-2015

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Chapter:12Chapter:12Structured Query Language(SQL)Structured Query Language(SQL)

HistoryHistory SEQUEL (Structures English QUery Language) – SEQUEL (Structures English QUery Language) –

early 70’s, IBM Researchearly 70’s, IBM Research SQL (ANSI 1986), SQL1 or SQL86SQL (ANSI 1986), SQL1 or SQL86 SQL2 or SQL92SQL2 or SQL92 SQL3 or SQL99SQL3 or SQL99

Core specification and optional specialized Core specification and optional specialized packagespackages

SQL consists of ~20 basic commandsSQL consists of ~20 basic commands A lot of research money for each SQL command…A lot of research money for each SQL command…

Standard language for all commercial DBMSStandard language for all commercial DBMS

Page 2: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

22

Page 3: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Why a query language?Why a query language?

Given some data,Given some data,

how should users

and computer programs

communicate with it?

?

•we need an interface to the data

Page 4: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

An Overview of An Overview of SQLSQL

SQL stands for SQL stands for SStructured tructured QQuery uery LLanguage.anguage. It is the most commonly used relational It is the most commonly used relational

database language today.database language today. SQL works with a variety of different fourth-SQL works with a variety of different fourth-

generation (4GL) programming languages, such generation (4GL) programming languages, such as Visual Basic.as Visual Basic.

SQL

Page 5: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

5

SQL RequirementsSQL Requirements

SQL Must be embedded in a programming SQL Must be embedded in a programming language, or used with a 4GL like VBlanguage, or used with a 4GL like VB

SQL is a free form language so there is no limit SQL is a free form language so there is no limit to the the number of words per line or fixed line to the the number of words per line or fixed line break.break.

Syntax statements, words or phrases are always Syntax statements, words or phrases are always in lower case; keywords are in uppercase.in lower case; keywords are in uppercase.

SQL

Page 6: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

STRUCTURE QUERY LANGUAGE(SQL): STRUCTURE QUERY LANGUAGE(SQL): The SQL is a language that enables you to The SQL is a language that enables you to create and operate on relational create and operate on relational databases, which are sets of related databases, which are sets of related information stored in tables.information stored in tables.

=> SQL is a simple query language used => SQL is a simple query language used for accessing , handling and managing for accessing , handling and managing data in relational database.data in relational database.

Page 7: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

SQL, enables the following:SQL, enables the following:

(i) Creating/modifying a database’s structure (i) Creating/modifying a database’s structure

(ii) Changing security settings for system(ii) Changing security settings for system

(iii) Permitting users for working on databases (iii) Permitting users for working on databases or tablesor tables

(iv) Querying database(iv) Querying database

(v) Inserting/Modifying/Deleting the database (v) Inserting/Modifying/Deleting the database contents.contents.

Page 8: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Processing Capabilities of SQLProcessing Capabilities of SQL Data definition language-TheData definition language-The SQL DDL SQL DDL

provides commands for defining relation provides commands for defining relation schemas, deleting relations, creating indexes, schemas, deleting relations, creating indexes, and modifying relation schemas.and modifying relation schemas.

Interactive Data Manipulation Language-TheInteractive Data Manipulation Language-The SQL DML includes a query language based on SQL DML includes a query language based on both the relational algebra and the tuple both the relational algebra and the tuple relational calculus.relational calculus.

8

Page 9: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Embedded Data Manipulation Language-Embedded Data Manipulation Language-TheThe Embedded form of SQL is designed for Embedded form of SQL is designed for use within general purpose programming use within general purpose programming languages such as PL/1,Cobol,Fortan,Pascal languages such as PL/1,Cobol,Fortan,Pascal and C.and C.

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

Authorization-Authorization-The SQL DDL includes The SQL DDL includes commands for specifying access rights to commands for specifying access rights to relations and views.relations and views.

9

Page 10: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

IntegrityIntegrity-The SQL provides limited forms -The SQL provides limited forms of integrity checking. Future products and of integrity checking. Future products and standards of SQL are likely to include standards of SQL are likely to include enhanced features for integrity checking.enhanced features for integrity checking.

Transaction Control-SQLTransaction Control-SQL includes includes commands for specifying the beginning commands for specifying the beginning and ending of transactions along with and ending of transactions along with commands to have a control over a commands to have a control over a transaction processing.transaction processing.

10

Page 11: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

=>Data definition language(DDL):=>Data definition language(DDL): A database A database scheme is specified by a set of definition which scheme is specified by a set of definition which are expressed by a special language called a are expressed by a special language called a data data definition languagedefinition language (DDL). (DDL).

The result of compilation of DDL statements is a The result of compilation of DDL statements is a set of tables which are stored in a special file set of tables which are stored in a special file called called Data dictionaryData dictionary (or dictionary). (or dictionary).

i.e. i.e. A data dictionary is a file that contains A data dictionary is a file that contains “Metadata“Metadata” i.e. , “data about data”” i.e. , “data about data”

Classification of sql statementClassification of sql statement All sql statement are instruction to the database All sql statement are instruction to the database

only. And that is where it differs from general-only. And that is where it differs from general-purpose programming languages like ‘C’ or ‘c++’ purpose programming languages like ‘C’ or ‘c++’ or ’BASIC’ etcor ’BASIC’ etc

Page 12: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

DDL perform the following functions:DDL perform the following functions: It should identify the types of data It should identify the types of data

division such as data item, record type, division such as data item, record type, segment, record and database filesegment, record and database file

it should give a unique name to each it should give a unique name to each data –item type, record type, file type, data –item type, record type, file type, database etc.database etc.

it should specify the proper data typeit should specify the proper data type it should specify how the record types it should specify how the record types

are related to make structures.are related to make structures. It may define the length of the data It may define the length of the data

items.items.

Page 13: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

It may define the range of values that a It may define the range of values that a data-item can assume.data-item can assume.

checking the error in the data checking the error in the data Create, alter, and drop schema objectCreate, alter, and drop schema object

Page 14: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

=>A DATA MANIPULICATION LANGUAGE(DML)=>A DATA MANIPULICATION LANGUAGE(DML) is a language that enables user to access or is a language that enables user to access or manipulate data as organized by the appropriate manipulate data as organized by the appropriate data model.data model.

=>By data manipulation, we mean=>By data manipulation, we mean1.the retrieval of information stored in the 1.the retrieval of information stored in the

databasedatabase2.the insertion of new information into the 2.the insertion of new information into the

databasedatabase3.The deletion of information from the database3.The deletion of information from the database4.the modification of data stored in the database4.the modification of data stored in the database

Page 15: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

=>The DML are basically of two types:=>The DML are basically of two types:

1.Procedure DML 1.Procedure DML required a user to required a user to specify what data is needed and how to specify what data is needed and how to get it.get it.

2. Non-procedure DMLs 2. Non-procedure DMLs required a user required a user to specify what data is needed without to specify what data is needed without specifying how to get it.specifying how to get it.

Examples:Examples:

INSERT INTO, UPDATE, DELETE, INSERT INTO, UPDATE, DELETE, SELECT, LOCKSELECT, LOCK

Page 16: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

=> DCL(Data control Language): It is used to => DCL(Data control Language): It is used to access to the data base(by GRANTing / access to the data base(by GRANTing / REVOKing etc) and essential to the systemREVOKing etc) and essential to the system

Page 17: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Some MySQL SQL ElementsSome MySQL SQL Elements The MySQL implementation of SQL has The MySQL implementation of SQL has

certain elements that play an important role in certain elements that play an important role in defining /querying a database. These basic defining /querying a database. These basic elements are:elements are:

(i) Literals(i) Literals

(ii) Data types(ii) Data types

(iii) Nulls(iii) Nulls

(iv) Comments(iv) Comments

Page 18: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

(i) Literals(i) Literals Literals in general, refer to a fixed data value. Literals in general, refer to a fixed data value.

The fixed data value may be of character type The fixed data value may be of character type or numeric literal.or numeric literal.

(ii)Data types (ii)Data types Data types are means to identify the type of Data types are means to identify the type of

data and associated operations for handling it.data and associated operations for handling it. Numeric Data TypesNumeric Data Types MySQL uses all the standard ANSI SQL MySQL uses all the standard ANSI SQL

numeric data types. The following list shows numeric data types. The following list shows the common numeric data typesthe common numeric data types

Page 19: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

INTINT TINYINTTINYINT SMALLINTSMALLINT MEDIUMINTMEDIUMINT BIGINTBIGINT FLOAT(M.D)FLOAT(M.D) DOUBLE(M.D)DOUBLE(M.D) DECIMAL(M.D)DECIMAL(M.D) Date and Time TypesDate and Time Types The MYSQL date and time data types are:The MYSQL date and time data types are: DATEDATE DATETIMEDATETIME TIMESTAMPTIMESTAMP TIMETIME YEAR(M) YEAR(M)

Page 20: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

String/Text TypesString/Text Types Most data that you in a database is in Most data that you in a database is in

string format. This list describes the string format. This list describes the common string data types in MySQLcommon string data types in MySQL

CHAR(M)CHAR(M) VARCHAR(M)VARCHAR(M) BLOB or TEXTBLOB or TEXT TINYBLOB or TINYTEXTTINYBLOB or TINYTEXT MEDIUMBLOB or MEDIUMTEXTMEDIUMBLOB or MEDIUMTEXT LONGBLOB or LONGTEXTLONGBLOB or LONGTEXT ENUMENUM

Page 21: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

2121

SQL Data types (from Oracle 9i)SQL Data types (from Oracle 9i) String typesString types

CHARCHAR(n) – fixed-length character data, n characters (n) – fixed-length character data, n characters long Maximum length = 2000 bytes.It is inclosed in long Maximum length = 2000 bytes.It is inclosed in single qoutes( ‘ram’)single qoutes( ‘ram’)

VARCHAR2VARCHAR2(n) – variable length character data, (n) – variable length character data, maximum 4000 bytesmaximum 4000 bytes

LONGLONG – variable-length character data, up to 4GB. – variable-length character data, up to 4GB. Maximum 1 per tableMaximum 1 per table

Numeric typesNumeric types NUMBERNUMBER(p,q) – general purpose numeric data type(p,q) – general purpose numeric data type INTEGERINTEGER(p) – signed integer, p digits wide(p) – signed integer, p digits wide FLOATFLOAT(p) – floating point in scientific notation with p (p) – floating point in scientific notation with p

binary digits precisionbinary digits precision Date/time typeDate/time type

DATEDATE – fixed-length date/time in dd-mm-yy form – fixed-length date/time in dd-mm-yy form

Page 22: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

SQL Server Data TypesSQL Server Data Types

int, integer: 4 byte integerint, integer: 4 byte integer smallint: 2 byte integersmallint: 2 byte integer tinyint: 1 byte integertinyint: 1 byte integer float: 4 or 8 byte floating point numberfloat: 4 or 8 byte floating point number real: 4 byte floating point numberreal: 4 byte floating point number double precision: 8 bype floating point numberdouble precision: 8 bype floating point number numeric, decimal(precision, scale): exact numeric, decimal(precision, scale): exact

numeric, 2 to 17 bytes. Only difference is that numeric, 2 to 17 bytes. Only difference is that only numeric types with a scale of 0 can be used only numeric types with a scale of 0 can be used of the IDENTITY column.of the IDENTITY column.

Destroy a table: Destroy a table: drop tabledrop table table_nametable_name

Page 23: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Difference between Char and Vachar datatypesDifference between Char and Vachar datatypes TheThe difference between CHAR and VARCHAR difference between CHAR and VARCHAR

is that of fixed length and variable length. is that of fixed length and variable length. The CHAR data types specifies a fixed length The CHAR data types specifies a fixed length

character string and VARCHAR data types character string and VARCHAR data types specifies a variable length string.specifies a variable length string.

(iii)Null Values(iii)Null Values If a column in a row has no value, then column is If a column in a row has no value, then column is

said to be said to be nullnull , , or to contain a null.or to contain a null. Nulls can Nulls can appear in columns of any data type provided they appear in columns of any data type provided they are not restricted by NOT NULL or PRIMARY are not restricted by NOT NULL or PRIMARY KEY integrity constraints.KEY integrity constraints.

Page 24: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Comments: Comments: A comment is a text that is not A comment is a text that is not executed ; it is only for documentation executed ; it is only for documentation purpose. Comments within SQL statements purpose. Comments within SQL statements do not affect the statement execution, but they do not affect the statement execution, but they may make your application easier for you to may make your application easier for you to read and maintain. A comment can be given read and maintain. A comment can be given using double minus sing i.e. - -using double minus sing i.e. - -

Page 25: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

SQL COMMAND SYNTAXSQL COMMAND SYNTAX The SQL provides a predefined set of The SQL provides a predefined set of

commands that help us work on relational commands that help us work on relational databases.databases.

KeywordsKeywords are words that have a special are words that have a special meaning in SQL. They are understood to be meaning in SQL. They are understood to be instructions.instructions.

Commands, or statements, Commands, or statements, are instructions are instructions given by you to a SQL database.given by you to a SQL database.

ArgumentsArguments complete or modify the meaning complete or modify the meaning of a clause.of a clause.

Page 26: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

2626

SQL EnvironmentSQL Environment CatalogCatalog

A set of schemas that constitute the description of a A set of schemas that constitute the description of a databasedatabase

SchemaSchema The structure that contains descriptions of objects The structure that contains descriptions of objects

created by a user (base tables, views, constraints)created by a user (base tables, views, constraints) Data Definition Language (DDL)Data Definition Language (DDL)

Commands that define a database, including creating, Commands that define a database, including creating, altering, and dropping tables and establishing altering, and dropping tables and establishing constraintsconstraints

Data Manipulation Language (DML)Data Manipulation Language (DML) Commands that maintain and query a databaseCommands that maintain and query a database

Data Control Language (DCL)Data Control Language (DCL) Commands that control a database, including Commands that control a database, including

administering privileges and committing dataadministering privileges and committing data

Page 27: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

2727

Page 28: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

QueriesQueries

SPECIAL OPERATORSSPECIAL OPERATORS BETWEENBETWEEN - define range limits - define range limits IS NULLIS NULL - check if attribute value is - check if attribute value is

nullnull LIKELIKE - check for similar character - check for similar character

stringsstrings ININ - check if attribute value matches a - check if attribute value matches a

value within a (sub)set of listed valuesvalue within a (sub)set of listed values EXISTSEXISTS - check whether attribute has - check whether attribute has

a valuea value

Page 29: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Basic MySQL Operations Create database use database see data base Create table Insert records Load data Retrieve records Update records Delete records Modify table Join table Drop table Optimize table Count, Like, Order by, Group by More advanced ones (sub-queries, stored procedures,

triggers, views …)

Page 30: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Syntax to Create databaseSyntax to Create databaseCreate database databasenameCreate database databasename ; ; Create a database (make a directory) whose name is

MyDB mysql> create database MyDB; Select database to use mysql> use MyDB; Database changed What tables are currently stored in the MyDB

database? mysql> show tables; Empty set (0.00 sec)

Page 31: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

What are the current databases at the server?mysql> show databases;

+--------------+

| Database |

+--------------+

| mysql |

| test |

+--------------+

mysql is a database (stores users’ password) used by system.

Page 32: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

=>CREATE TABLE COMMAND=>CREATE TABLE COMMAND CREATE TABLECREATE TABLE – defines a table and its – defines a table and its

columns, data types and sizes are supplied columns, data types and sizes are supplied for each column.for each column.

CREATE TABLE Table_Name (column_specifications) Syntax;Syntax; CREATE TABLE <table-name> <table-name> (column name data tpes[size], column name (column name data tpes[size], column name

data tpes[size],….);data tpes[size],….);Example: Example: CREATE TABLE employee ( ecode int, employee ( ecode int,

ename char(20),sex char(1), grade char(2), ename char(20),sex char(1), grade char(2), gross decimal);gross decimal);

Page 33: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Constraint; A CONSTRAINT IS A Constraint; A CONSTRAINT IS A CONDITIONAL OR CHECK APPLICABLE CONDITIONAL OR CHECK APPLICABLE ON A FIELD OR SET OF FIELD.ON A FIELD OR SET OF FIELD.

There are two type of constraints There are two type of constraints Column constraint: It apply only to individual Column constraint: It apply only to individual

columnscolumnsTable Constraint: It apply to groups of one or Table Constraint: It apply to groups of one or

more columns.more columns.Syntax:Syntax:CREATE TABLE table-name ( column-name CREATE TABLE table-name ( column-name

data type[size] column constraint, column-data type[size] column constraint, column-name data type[size] column constraint, ….);name data type[size] column constraint, ….);

Page 34: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

CREATE TABLE employee employee

( ecode int NOT NULL,( ecode int NOT NULL,

ename char(20) NOT NULL,ename char(20) NOT NULL,

sex char(1) NOT NULL,sex char(1) NOT NULL,

grade char(2), grade char(2),

gross decimal);gross decimal); Different Constraints: Different Constraints: Unique ConstraintsUnique Constraints Primary key ConstraintsPrimary key Constraints Default ConstraintsDefault Constraints Check ConstraintsCheck Constraints

Page 35: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Unique Unique Constraints: This Constraints Constraints: This Constraints ensures that no two rows have the same ensures that no two rows have the same value in the specified columns.value in the specified columns.

CREATE TABLE employee employee

( ecode int NOT NULL UNIQUE,( ecode int NOT NULL UNIQUE,

ename char(20), NOT NULLename char(20), NOT NULL

sex char(1), NOT NULLsex char(1), NOT NULL

grade char(2), grade char(2),

gross decimal);gross decimal);

Page 36: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Primary key Constraint: Primary key Constraint: It is a set of column It is a set of column or columns that uniquely identify a row in a or columns that uniquely identify a row in a relation.relation.

CREATE TABLE employee employee

( ecode int NOT NULL PRIMARY KEY,( ecode int NOT NULL PRIMARY KEY,

ename char(20), NOT NULLename char(20), NOT NULL

sex char(1), NOT NULLsex char(1), NOT NULL

grade char(2), grade char(2),

gross decimal);gross decimal);

Page 37: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Default Constraint: Default Constraint: A default value can be A default value can be specified for a column using the default specified for a column using the default clause. When a user does not enter a value for clause. When a user does not enter a value for the column(having default), automatically the the column(having default), automatically the defines default value is inserted in the field.defines default value is inserted in the field.

CREATE TABLE employee employee

( ecode int NOT NULL PRIMARY KEY,( ecode int NOT NULL PRIMARY KEY,

ename char(20), NOT NULLename char(20), NOT NULL

sex char(1), NOT NULLsex char(1), NOT NULL

grade char(2) DEFAULT=‘E’,grade char(2) DEFAULT=‘E’,

gross decimal);gross decimal);

Page 38: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Check Constraints: Check Constraints: This constraint limit values This constraint limit values that can be inserted into a column of a table.that can be inserted into a column of a table.

CREATE TABLE employee employee

( ecode int NOT NULL PRIMARY KEY,( ecode int NOT NULL PRIMARY KEY,

ename char(20), NOT NULLename char(20), NOT NULL

sex char(1), NOT NULLsex char(1), NOT NULL

grade char(2) DEFAULT=‘E’,grade char(2) DEFAULT=‘E’,

gross decimal CHECK(GROSS>2000));gross decimal CHECK(GROSS>2000));

=>When a check constraint involves more =>When a check constraint involves more than one column from the same table, it is than one column from the same table, it is specified after all the columns have been specified after all the columns have been defined.defined.

Page 39: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

CREATE TABLE employee employee

( icode char(5) NOT NULL PRIMARY KEY,( icode char(5) NOT NULL PRIMARY KEY,

descp char(20), NOT NULLdescp char(20), NOT NULL

ROL integer, ROL integer,

QOH integer,QOH integer,

CHECK (ROL<QOH)CHECK (ROL<QOH)

););

Page 40: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Applying Table Constraints:Applying Table Constraints: The Table The Table constraints appear in the end of the table constraints appear in the end of the table definition. definition.

CREATE TABLE items items

( icode char(5) NOT NULL,( icode char(5) NOT NULL,

Descp char(20) NOT NULL,Descp char(20) NOT NULL,

ROL integer,ROL integer,

QOH integer,QOH integer,

CHECK (ROL<QOH),CHECK (ROL<QOH),

UNIQUE (icode,descp));UNIQUE (icode,descp));

Page 41: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

mysql> show tables; +--------------------+ | Tables_in_MyDB | +--------------------+ | student | +--------------------+ 1 row in set (0.00 sec) mysql> describe student; +---------------+----------------------+------+------+----------+--------+ | Field | Type | Null | Key | Default | Extra | +---------------+----------------------+-------+-----+-----------+-------+ | student_ID | int(10) unsigned | | | 0 | | | name | varchar(20) | | | | | | major | varchar(50) | YES | | NULL | | | grade | varchar(5) | YES | | NULL | | +---------------+----------------------+-------+------+----------+-------+ 4 rows in set (0.00 sec)

Page 42: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

The SELECT CommandThe SELECT Command The SELECT command of SQL lets you make The SELECT command of SQL lets you make

queries on the database. A query is a command queries on the database. A query is a command that is given to produce certain specified that is given to produce certain specified information from the database table(s).information from the database table(s).

SELECT statement is used as given below;SELECT statement is used as given below; SELECT <column name>, <column name> , …SELECT <column name>, <column name> , …

FROM <table name> ;FROM <table name> ; Example: SELECT Empno,Empname FROM emp;Example: SELECT Empno,Empname FROM emp;

Page 43: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

SELECT StatementSELECT Statement Used for queries on single or multiple tablesUsed for queries on single or multiple tables Clauses of the SELECT statement:Clauses of the SELECT statement:

SELECTSELECT List the List the columnscolumns (and expressions) that should be returned from (and expressions) that should be returned from

the querythe query FROMFROM

Indicate the Indicate the tabletable(s) or view(s) from which data will be obtained(s) or view(s) from which data will be obtained WHEREWHERE

Indicate the Indicate the conditionsconditions under which a under which a rowrow will be included in the will be included in the resultresult

GROUP BYGROUP BY Indicate Indicate columnscolumns to group the results to group the results

HAVINGHAVING Indicate the Indicate the conditionsconditions under which a under which a groupgroup will be included will be included

ORDER BYORDER BY Sorts the result according to specified Sorts the result according to specified columnscolumns

Page 44: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

4444

Page 45: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

List the selected column of a table SELECT empno,job,sal FROM emp; List the all column of a table * is wildcard character - gives “all rows”* is wildcard character - gives “all rows” SELECT * FROM emp; Reordering columns in query Results SELECT job,empno,sal FROM emp; Eliminating Redundant data (with keyword

DISTINCT): The DISTINCT keyword eliminates duplicates rows from the results of a SELECT statement.

Page 46: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Example: SELECT DISTINCT city FROM suppliers;

Selecting From All the Rows-ALL Keyword: The result retains the duplicates output rows. It is just the same as when you specify neither DISTINCT nor ALL.

EXAMPLE: SELECT ALL city FROM suppliers;

Page 47: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Selecting Specific Rows-Where clause: The tables can contain unlimited rows. If you want to view selected rows from the table.the WHERE clause in SELECT statement specifies the criteria for selection of rows to be returned.

Syntax:SELECT column name, column name,....FROM table name WHERE condition; EXAMPLE: SELECT empname,sal FROM emp WHERE

sal>2900;

Page 48: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

4848

Page 49: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

List all the members not from ‘DELHI’List all the members not from ‘DELHI’ SELECT * FROM suppliers WHERE city < SELECT * FROM suppliers WHERE city <

> ‘ DELHI’ ;> ‘ DELHI’ ; Logical Operator: The logical operators Logical Operator: The logical operators

OR ,AND and NOT are used to connect OR ,AND and NOT are used to connect search conditions is the WHERE clause.search conditions is the WHERE clause.

1.1. To list the employees details having To list the employees details having grade ‘E2’ or ‘E3’ from the table grade ‘E2’ or ‘E3’ from the table employeeemployee

SELECT ecode,ename,grade,gross FROM SELECT ecode,ename,grade,gross FROM employee WHERE(grade=‘E2’ OR employee WHERE(grade=‘E2’ OR grade=‘E’);grade=‘E’);

Page 50: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

2. 2. To list the employees details having To list the employees details having grades ‘E4’ but with the gross<9000 grades ‘E4’ but with the gross<9000 from the table employeefrom the table employee

SELECT ecode,ename,grade,gross FROM SELECT ecode,ename,grade,gross FROM employee WHERE(grade=‘E4’ AND employee WHERE(grade=‘E4’ AND gross<9000);gross<9000);

3. 3. To list all the employees details whose To list all the employees details whose grade are other than ‘G1’.grade are other than ‘G1’.

SELECT ecode,ename,grade,gross FROM SELECT ecode,ename,grade,gross FROM employee WHERE(NOT grade=‘G1’);employee WHERE(NOT grade=‘G1’);

Page 51: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

CONDITION BASED ON A RANGE: The BETWEEN operator defines a range of values that the column values must fall into make the condition true.yhe range includes both lower values and the upper value.

To list the item whose QOH falls between 30 to 50(both inclusive).

SELECT icode ,descp,QOH FROM items WHERE QOH BETWEEN 30 and 50.

SELECT icode ,descp,QOH FROM items WHERE QOH NOT BETWEEN 30 and 50.

Page 52: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

CONDITION BASED ON A LIST: The IN operator selects values that match any value in a given list of values.

To display a list of members from ‘DELHI’, ‘MUMBAI’, ‘CHENNAI’, OR ‘ BANGALORE’ CITIES.

SELECT * FROM members WHERE city IN (‘DELHI’, ‘MUMBAI’, ‘CHENNAI’,

‘ BANGALORE’ );=> SELECT * FROM members WHERE city

NOT IN (‘DELHI’, ‘MUMBAI’, ‘CHENNAI’, ‘ BANGALORE’ );

Page 53: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

CONDITIN BASED ON PATTERN MATCHES: The string matching operatr, LIKE, for comparisons on character strings using patterns. Patters are described using two special wildcard characters.

percent(%): The % character matches any substring.

underscore( _ ): The _ character matches any one character.

Patterns are case sensitive i.e. , upper case characters dot not match lower case characters or vice –versa.

Page 54: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

The keyword NOT LIKE is used to select rows that do not match the specified pattern of characters.

In order for patterns to include the special pattern characters(that is, %,_), SQL allows the specific of an escape character.

The escape character is used immediately before a special pattern character to indicate that the special pattern character is to be treated as a normal character.

Page 55: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

“San%” matches any string beinning with “San”. “%idge%” matches any string containing “idge” as a

substring, for example “ridge” , Bridge”, etc. “ _ _ _ _” matches any string of exactly 4

characters. “ _ _ _ _ %” matches any string of at least 4

characters. 1. To list members which are in areas with pin

codes starting with 13. SELECT firstname, lastname,city FROM members

WHERE pin LIKE “13%”;

Page 56: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

2.To list employees who have four letter first names ending with “ D”.

SELECT empno, empname FROM emp WHERE empname LIKE “ _ _ _ D”;

3.To list members which are not in areas with pin codes starting with 13.

SELECT firstname, lastname,city FROM members WHERE pin NOT LIKE “13%”;

SEARCHING FOR NULL: The NULL value in a column can be searched for in a table using IS NULL in the WHERE clause.

Page 57: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

SELECT empno, empname, job FROM emp WHERE DeptNo IS NULL;

SEARCHING RESULTS- ORDER BY CLAUSE: The ORDER BY clause allows sorting of query results by one or more columns. The sorting can be done either on ascending or descending order. the data in the table is not sorted; only the results that appear on the screen are sorted,

Syntax: SELECT column name,… FROM table name WHEE condition ORDER BY column name.

SELECT * FROM employee ORDER BY ename; SELECT empno , empname , job FROM emp

WHERE sal> 2500 ORDER BY ename ; SELECT * FROM employee ORDER BY ecode

DESC;

Page 58: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

DESC: descending order ASC: Ascending order SELECT * FROM employee ORDER By

grade DESC , ename ASC; SIMPLE CALCULATION: DUAL table is a small worktable , which

has just one row and one column. SELECT 4*3 FROM dual; SELECT sysdate FROM dual;

Page 59: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English
Page 60: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

1.Avg Function1.Avg Function

Query 1: If we want to calculate the AVG of all the salaries in the organization the SQL would beSELECT AVG(SALARY) FROM EMPLOYEE62,500Is this what we expect????Employee table has 7 records and the salaries are 50,000+60,000+50,000+70,000+75,000+70,000+null/7 = 53571

But we obtained 62500 from the query? Why is this so????

The AVG() function returns the average value of a numeric column.

Page 61: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

AVG (Continued….)AVG (Continued….)Remember : COUNT(*) is the only function which won’t ignore Nulls. Other functions like SUM,AVG,MIN,MAX they ignore Nulls. What it means is in the previous query the salary value for a particular employee was NULL. So the query

SELECT AVG(SALARY) FROM EMPLOYEEwould ignore nulls and the way the average is calculated then wouldbe 50,000+60,000+50,000+70,000+75,000+70,000/6 = 62500

Page 62: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

AVG (Continued….)AVG (Continued….)From the information given in the previous slide what do you thinkwould be the output of the following query

Select COUNT(*),COUNT(SALARY) FROM EMPLOYEE;It would be

COUNT(*) COUNT(SALARY) 7 6

Because COUNT(*) is not going to ignore the Nulls in the result whereas COUNT(SALARY) is going to ignore the Nulls.

Page 63: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

2.COUNT2.COUNT The SQL COUNT aggregate function is used to count the The SQL COUNT aggregate function is used to count the

number of rows in a database table. number of rows in a database table. The SQL COUNT syntax is simple and looks like this: The SQL COUNT syntax is simple and looks like this:

COUNT({*[DISTINCT | ALL] expr}) COUNT({*[DISTINCT | ALL] expr})FROM Table1 FROM Table1

If we want to count the number of records in table empl, If we want to count the number of records in table empl, we will use the following SQL COUNT statement: we will use the following SQL COUNT statement:

SELECT COUNT(*) “Total”SELECT COUNT(*) “Total”FROM empl;FROM empl;

The result of this SQL COUNT query will be: The result of this SQL COUNT query will be:

Total14

Page 64: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

3.MAX3.MAX The The SQL MAXSQL MAX aggregate function allows us to select aggregate function allows us to select

the highest (maximum) value for a certain column. the highest (maximum) value for a certain column. The The SQL MAXSQL MAX function syntax is very simple and it function syntax is very simple and it

looks like this: looks like this: MAX([DISTINCT | ALL] expr) MAX([DISTINCT | ALL] expr)

If we want to display maximum salary from table If we want to display maximum salary from table empl empl SQL MAXSQL MAX expression: expression:

SELECT MAX(sal) “Maximum Salary”SELECT MAX(sal) “Maximum Salary”FROM empl;FROM empl;

Maximum Salary5000.00

Page 65: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

4.MIN4.MIN The The SQL MINSQL MIN aggregate function allows us to select aggregate function allows us to select

the lowest (minimum) value for a certain column. the lowest (minimum) value for a certain column. The The SQL MINSQL MIN function syntax is very simple and it function syntax is very simple and it

looks like this: looks like this: MIN([DISTINCT | ALL] expr)MIN([DISTINCT | ALL] expr)

If we want to display the joining date of senior most If we want to display the joining date of senior most employee the following employee the following SQL MINSQL MIN expression is used : expression is used :

SELECT MIN(hiredate) “Minimum Hire Date”SELECT MIN(hiredate) “Minimum Hire Date”FROM empl;FROM empl;

Minimum Hire Date1990-12-18

Page 66: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

5.sum5.sum sumsum is an is an aggregate function. It returns the sum of its . It returns the sum of its

numeric-expressions for each group indicated in the group by numeric-expressions for each group indicated in the group by clause. clause.

Query 1: To find the sum of all salaries in the organization:Query 1: To find the sum of all salaries in the organization: SELECT SUM(SALARY) FROM EMPLOYEE;SELECT SUM(SALARY) FROM EMPLOYEE; 375000375000

Query 2: To find the sum of the salaries grouped by deptQuery 2: To find the sum of the salaries grouped by dept SELECT SUM(SALARY) FROM EMPLOYEE GROUP BYSELECT SUM(SALARY) FROM EMPLOYEE GROUP BY DEPT_NAMEDEPT_NAME

Page 67: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Types of sql functionsTypes of sql functions

(i)Single-Row Functions (i)Single-Row Functions Single-row functions return a single result row for every Single-row functions return a single result row for every

row of a queried table or view. row of a queried table or view. Examples of single row functions are the functions are Examples of single row functions are the functions are

text/Character functions such as year(),day(),etc.text/Character functions such as year(),day(),etc.

(ii) Multiple Row or Group Functions work with data of (ii) Multiple Row or Group Functions work with data of multiple rows at a time and return aggregate value.multiple rows at a time and return aggregate value.

Examples of multiple row functions are the group functions Examples of multiple row functions are the group functions i.e. , sum(),count(),max(),min(), Avg()etc. i.e. , sum(),count(),max(),min(), Avg()etc.

A single row function works with the data of single row A single row function works with the data of single row at a time and returns a single result for each row queried at a time and returns a single result for each row queried upon ; a multiple row function works with the data of upon ; a multiple row function works with the data of group of rows at a time and returns a single result for that group of rows at a time and returns a single result for that group. group.

Page 68: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Grouping result – group byGrouping result – group by The GROUP BY clause combines all those The GROUP BY clause combines all those

records that have high identical values in a records that have high identical values in a particular field or a group of fields. This groupingparticular field or a group of fields. This grouping results into one summary record per group if results into one summary record per group if group-functions are used with it.In other group-functions are used with it.In other words ,the GROUP BY clause is used in SELECT words ,the GROUP BY clause is used in SELECT statements to divide the table into groups. statements to divide the table into groups. Grouping can be done by a column name,or with Grouping can be done by a column name,or with aggregate functions in which case the aggregate aggregate functions in which case the aggregate produces a value for each group.produces a value for each group.

Ex: SELECT job ,COUNT(*),sum(comm)Ex: SELECT job ,COUNT(*),sum(comm)

FROM emp GROUP BY job ;FROM emp GROUP BY job ;

GROUP BY applies the aggregate functions GROUP BY applies the aggregate functions independently to a series of groups that are independently to a series of groups that are defined by having a field value in common.defined by having a field value in common.

Page 69: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

NESTED Groups - Grouping on multiple NESTED Groups - Grouping on multiple ColumnsColumns

With GROUP BY clause ,you can create groups With GROUP BY clause ,you can create groups within groups. Such type of grouping is called within groups. Such type of grouping is called Nested grouping.Nested grouping. This can be done by specifying in This can be done by specifying in GROUP BY expression, where the GROUP BY expression, where the first fieldfirst field determines the determines the highest group level, highest group level, the the second field second field determines the determines the second group levelsecond group level, and so on. The , and so on. The last last field field determines the determines the lowest level of grouping.lowest level of grouping.

SeeSee there are multiple records having same value there are multiple records having same value for depno,we can group records on the basis of for depno,we can group records on the basis of field Deptno.field Deptno.

For instance ,if you want to count the number of For instance ,if you want to count the number of employees in each group ,you need to issue a query employees in each group ,you need to issue a query statement as given below:statement as given below:

SELECT COUNT(empno) FROM emplSELECT COUNT(empno) FROM empl GROUP BY Deptno;GROUP BY Deptno;

Page 70: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Result produced by the query isResult produced by the query is

But can you make out ,these are employee-counts But can you make out ,these are employee-counts for which departments? To get this information , you for which departments? To get this information , you may modify the SELECT list as:may modify the SELECT list as:

SELECT Deptno, COUNT(empno)SELECT Deptno, COUNT(empno) FROM emplFROM empl GROUP BY Deptno ;GROUP BY Deptno ;Deptno count(empno)Deptno count(empno) 10 310 3 20 520 5 30 630 6

Count(empno)356

Page 71: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

One thing should be kept in mind is that while grouping One thing should be kept in mind is that while grouping , you should include only those values in the selected , you should include only those values in the selected list that either have the same value for group or contain list that either have the same value for group or contain a group(aggregate) function i.e. , a group expression. Like a group(aggregate) function i.e. , a group expression. Like in the above query, the first expression Deptno field has in the above query, the first expression Deptno field has one (same) value for a group and the other expression one (same) value for a group and the other expression COUNT(empno) contains a group function.COUNT(empno) contains a group function.

A non group field (or expression) is the field that has A non group field (or expression) is the field that has different values in the rows belonging to group. different values in the rows belonging to group.

In the select list of a group ,only those fields or In the select list of a group ,only those fields or expressions state be included that either return single expressions state be included that either return single value for a group are constants.Otherwise you may not value for a group are constants.Otherwise you may not get authentic results.get authentic results.

Page 72: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Placing condition on groups-HAVING Clause:

The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on individual while WHERE conditions cannot include aggregate functions, Having conditions can do so.

SELECT avg (gross), sum(gross)

FROM employee

GORUP BY grade

HAVING grade=‘E4’;

Page 73: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

To display the jobs where the number of employee are less than 3.

SELECT job count(*) FROM emp GROUP By job Having count(*)<3;

SCALAR EXPRESSIONS WITH SELECTED FIELD: SQL allow to place scalar expressions and constants among the selected fields.

SELECT salesman_name , comm * 100 FROM salesman;

Page 74: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

PUTTING TEXT IN THE QUERY OUTPUT: To insert comment or symbol with every row of the output.

SELECT salesman_name , comm * 100 , ‘%’ FROM salesman;

SELECT salesman_name , ‘gets the commission’, comm * 100, ‘%’ FROM salesman;

CREATING TABLE FROM EXISTING TABLE: To create the table without going through the usual data definition process. this can be done by SELECT statement with CREATE TABLE.

CREATE TABLE orditem AS ( SELECT icode, descp FROM items WHERE QOH<ROL );

Page 75: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

A new table create from an existing table with help of SELECT INTO.

SELECT icode, descp INTO orditems FROM items WHERE QOH<ROL ;

Page 76: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Basic Insert: Inserting a Tuple into a TableBasic Insert: Inserting a Tuple into a Table

Insert one tuple into table:Insert one tuple into table:

insert into insert into table_nametable_name[([(column_listcolumn_list)] )] values(value_list)values(value_list)

Ex: Ex: specify values for all attributes:specify values for all attributes:

insert into STUDENT values(‘Mike’, 1, 3.8, 3, ‘CS’)insert into STUDENT values(‘Mike’, 1, 3.8, 3, ‘CS’) Ex: Ex: specify values for only some attributes:specify values for only some attributes:

insert into STUDENT(name, regno, level) insert into STUDENT(name, regno, level)

values (‘Jenny’, 2, 1)values (‘Jenny’, 2, 1) NOTE: in SQL, strings are surrounded by single NOTE: in SQL, strings are surrounded by single

quote, not double quote. Double quotes surround quote, not double quote. Double quotes surround identifiers that contain special characters. To identifiers that contain special characters. To include a single quote in the string use two single include a single quote in the string use two single quotes (eg.,’it’’s good’)quotes (eg.,’it’’s good’)

Page 77: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

INSERTING THE RESULTS OF A QUERY: inserting COMMAND CAN ALSO be used to take or drive values from one table and place them in another by using it with a query.

INSERT INTO branch1 SELECT * FROM branch2 WHERE

gross>7000.00;=> THE DELETE COMMAND: To removes rows

from a table.SYNTAX: DELETE FROM <tablename> [ WHERE<SONDITION> ];SQL> DELETE FROM employee WHERE

gross<2200.00;

Page 78: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Mysql> DELETE FROM student;Will delete ALL student records=> The UPDATE COMMAND: The UPDATE command

specifies the rows to be changed using the WHERE clause, and the new data using the SET keyword.

=> SYNTAX: UPDATE table name SET which columns to change

WHERE condition Example

mysql> UPDATE student SET grade='B' WHERE name='Shannon';

Query OK, 1 row affected (0.00 sec)Rows matched: 1 Changed: 1 Warnings: 0Mysql> UPDATE items SET ROL=250;Mysql> UPDATE items SET ROL=400 WHERE

ROL=300;

Page 79: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

=>UPDATING MULTIPLE COLUMNS:

Mysql> UPDATE items SET ROL=400,QOH=700 WHERE icode<‘I040’;

Using Expressions in UPDATE: Scalar expressions can also be used in the SET clause of the UPDATE command.

Mysql> UPDATE employee SET gross=gross+900;

UPDATING TO NULL VALUES: The NULL values can also be inserted just as other values.

Mysql> UPDATE employee SET grade=NULL WHERE grade=‘E4’;

Page 80: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

The CREATE VIEW COMMAND: A view is a virtual table with no data , but can be operated like any other table;

CTREATE VIEW taxpayee AS SELECT * FROM employee WHERE gross> 8000;

Note : The SELECT statement used in a view definition cannot include:

ORDER BY clause INTO clause CREATE VIEW taxpaee ( empcode,

empname,sex,empgrade,empgross) AS SELECT * FROM employee WHERE gross>8000;

Page 81: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

SOME BUILD – IN FUNCTIONS: 1.LOWER(character expression ): This

function converts a giving character expression into lowercase.

Syntax : LOWER(char); Description: returns the argument

char , with all latter lowercase; SQL> SELECT LOWER(‘MR.ANIL’)

lowername1, LOWER(‘MR. Maithili’) “Lowername2” from dual;

Page 82: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

2.UPPER(character expression ): This function converts a giving character expression into uppercase.

Syntax : UPPER (char); Description: returns the argument char ,

with all latter lowercase; SQL> SELECT UPPER (‘MR.ANIL’)

lowername1, UPPER(‘MR. Maithili’) “Lowername2” from dual;

Output:

Page 83: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

3. Replicate(char-expn,no-of-time): To repeats yhe given char-expn the no-of –times .the no-of-times has to an integer.

mysql>SELECT replicate(“*#”,4) FROM Dual;Output: *#*#*#*#

4.SUBSTR: This function extract a substring from a given string.

Syntax: SUBSTR(char, m[, n]) Description: Returns a portion of char,

beginning at character m, n character long. if m is 0.it is treated as 1.if m is positive , negative. If n is less than 1,a null is returned.

Page 84: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

SQL> select SUBSTR(‘Pointer’, 3,2) “subs” from dual;

Output: in

5.getdate( ): it return the current system date.

Mysql>SELECT getdate( ) FROM Dual;

6.CONCAT: Syntax: CONCAT(char1,char2). SQL>select CONCAT(ename, ecode)

“name and code” from emp where empno =7900 or empno=7788.

Page 85: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

7. INITCAP:

Syntax: INITCAP(char) Description: Returns the given

arguments char, with the first letter of each word in uppercase, all other letters in lowercase.

SQL>select INITCAP( ‘the soap’) “Capitals” from dual;

Page 86: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

8.LPAD: This function left-pads (i.e., inserts the left side) the giving character to given string to reach at given width.

Syntax:LPAD(char1, n [, char2]) Description: Returns argument char1,left-padded to

length n with the sequence of characters in argument char2.

The arguments n is the total length of the return values as it is displayed on the screen.

SQL> select LPAD(‘hello’,15,’*.’) “left padded ename” from EMP where empno=7788;

9.RPAD: function RPAD is similar to that of LPAD. only difference is that the specified character are right padded.

Page 87: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

=>Join is a query that combines rows from two or more tables. that is Join is used to give the data from multiple table with single query. The function of combining data from multiple table is called Joining.

SQL> SELECT patient_no, description, normal_charge,charge FROM billed,item WHERE billed.item_code= item.item_code;CARTESIAN PRODUCT: In unrestricted join or Cartesian product of two table ,all possible concatenations are formed of all rows of both the tables. SELECT * FROM EMP,DEPT ;

Page 88: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

=>A Table Alias is a temporary label given along with table name in FROM clause.

SQL>SELECT DISTINCT patient_no, phy_id FROM treats WHERE phy_id IN(8887,8886,8883,8882);

Page 89: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Types of Join

1. Inner or Equi-Join

2.Self Join

3.Outer Join

(a). Left outer Join

(b). Right outer Join

(c). Full outer Join

4.Natural Join

1. Inner or Equi-Join: The join in which columns are compared for equality, is called Equi-Join. OR INNER Join.

Page 90: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Inner Join is used to give the matching records from Joined tables.

For example: Table A.equi join table BSQL>SELCT billed.patient_no,

date_discharged, charge FROM billed,patient WHERE

patient.patient_no =billed.patient_no;=>Non-Equi Joins: A non- equi-join is a

query that specifies some relationship other than equality between the columns.

2.Natural Join: The Join in which only one of the identical columns(coming from joined tables) exits, is called Natural Join.

Page 91: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

3. Self Join: A table Joined with itself is called self join

SQL> select.*,sup2.supp# from suppliers where sup1.supp#<>sup2.supp# and sup1.city= sup2.city;

Outer Join: Outer Join selects all the rows that satisfy the join condition and those rows from one table for which no rows from the other table satisfy the join condition.

Page 92: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Left-Outer Join: Left outer jon give the results as combination of matching record from both the table plus remaining record from left side tables.

It is denoted by +

For left join + is used to the right side table variable

SQL>select sname, email, feebal from student s, fees f where s.sid =f.sid (+);

Page 93: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Right-outer Join: It Gives the results as combination of matching records plus remaining record from right sides tables.

SQL>select sname,email,feebal from student s,fees f where s.sid(+)=f.sid;

Full outer-join: It Gives the results as combination of matching records and remaining record from left sides table plus remaining record from right sides tables.

SQL>select sname, email, feebal from student s, fees f where s.sid(+)=f.sid(+);

Page 94: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

=>UNION: The SQL UNION operator allows manipulation of results returns by two or more queries by combining the results of wach query into a single result set.

Mysql> SELECT * FROM A UNION SELECT * FROM B;

It remove the duplicate rows from results. if the all option is used,all rows, including

duplicate are included in the results. SELECT statement UNION [ALL]

SELECT statement;

Page 95: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

RULE OF using UNION OPERATOR:1. Both the SELECT statements must be

UNION compatible, that is, the select-list of SELECT statement must have same number of column having similar data type and order.

Mysql> SELECT ecode,ename FROM branch1 UNION

SELECT ecode,ename FROM branch2;2. The ORDER BY clause occurs only at the end

of the UNION statement. It can’t be used within the individual queries that make the UNION statement.

Page 96: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

3. The GROUP BY and HAVING clause are allowed only within individual queries . These clause cannot be used to affect the final result set.

Page 97: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

ALTERING TABLE: It is used to change definitions of existing tables.

1.To add a column2. To add an integrity constraint3. To redefine a column (data type, size , default

value).ADDING COLUMNS: SYNTAX: ALTER TABLE <table name> ADD <column

name> <data type> <size> [<constraint name>]; SQL>ALTER TABLE Emp ADD (tel_number

integer);=>The new column will be added with NULL

values for all rows currently in the table.

Page 98: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

Mysql> ALTER TABLE Emp ADD (tel_number integers);

Modifying Column Definitions:SYNTAX:ALTER TABLE <table name> MODIFY

(column name new data types (new size));

SQL> ALTER TABLE Emp MODIFY (Job char(30));

Removing Integrity ConstraintsTo drops the primary key of table DEPTSQL> ALTER TABLE dept DROP PRIMARY

KEY CASCADE ;

Page 99: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

ENABLING OR DISABLING CONSTRAINTS: The ALTER TABLE command can be used for enabling or disabling a constraint.

SQL> ALTER TABLE products ENABLE pk_produce_01 ;

SQL> ALTER TABLE products DISABLE UNIQUE (serial#) ;

TRUNCTING TABLE: It allows users to delete information from a table quickly, using TRUNCTING COMMAND.

SQL> TRUNCTING TABL products;=>TRUNCATE is a part of DDL unlike DELETE

which is a part of DML

Page 100: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

THE DROP TABLE COMMAND: To drop a table from databse.It must be an empty table

SQL> DELETE FROM items ;

SQL> DROP TABLE items;

SQL> TRUCATING TABLE items; A table with rows in it cannot be dropped.

Page 101: Chapter:12 Structured Query Language(SQL) History History SEQUEL (Structures English QUery Language) – early 70’s, IBM Research SEQUEL (Structures English

THE DROP VIEW COMMAND:

To delete a view from the database ,the DROP VIEW command is used.

Mysql>DROP VIEW taxpayee;To drops the view taxpayee

from database. When a view is dropped, it does not cause any change in its base table after the removal of view taxpayee.