chapter-14-sql-commands
chapter-14-sql-commands
Chapter-14
SQL COMMANDS
What is 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.
AllrelationaldatabasemanagementsystemslikeMySQL,MSAccess,andOracle,Sybase,Informix, and
SQL Server use SQL as standard database language.
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
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.
Simple diagram showing SQL Architecture:
1 | Page
Chapter14-SQLCommands
SQL Commands:
The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP.
These commands can be classified into groups based on the irnature:
2 | Page
Chapter14-SQLCommands
1. NUMBER:
o Used to store a numeric value In a field column.
o It may be decimal, integer or real value.
o General syntax: NUMBER(n, d)
3 | Page
Chapter14-SQLCommands
o Where n specifies the number of digits and d specifies the number of digits to right of the
decimal point.
o Example: marks NUMBER(3), average NUMBER(2,3)
2. CHAR:
o Used to store a character type data in a column.
o General syntax: CHAR(size)
o Where size represents the maximum(255 Characters)number of characters in a column.
o Example: name CHAR(15)
3. VARCHAR/VARCHAR2:
o It is used to store variable length alphanumeric data.
o General syntax: VARCHAR(size)/ VARCHAR2(size)
o Where size represents the maximum(2000 Characters) number of characters in a column.
o Example: addressVARCHAR2(50)
4. DATE:
o It is used to store date in columns.
o SQL supports the various date formats other than the standard DD-MON-YY.
o Example: dob DATE
5. TIME:
o It is used to store time in columns.
o SQL supports the various time formats other than the standard hh-mm-ss.
o EveryDATEandTIMEcanbeadded,subtractedorcomparedasitcanbedonewithother data types.
6. LONG:
1. It is used to store variable length strings of up to2GBsize.
2. Example: description LONG
4 | Page
Chapter14-SQLCommands
5 | Page
Chapter14-SQLCommands
IS NULL The NULL operator is used to compare a value with a NULL value.
The UNIQUE operator searches every row of a specified table for uniqueness(no
UNIQUE
duplicates).
CREATE TABLE
The SQL CREATE TABLE statement isused to create a new table.
Creating a basic table involves naming the table and defining its columns and each column's data
type.
Syntax: Basic syntax of CREATE TABLE statement is as follows:
CREATE TABLE Table_name
(
column1datatype,
column2datatype,
column3datatype,
.....
Column N datatype,
PRIMARYKEY(one ormorecolumns)
);
o Here CREATE TABLE is the keyword followed by the Table_name, followed by an open
parenthesis, followed by the column names and data types for that column, and followed by a
closed parenthesis.
o For each column, a name and a data type must be specified and the column name must be a
unique within the table definition.
o Column definitions are separated by commas (,).
o Upper case and lowercase letters makes no difference in column names.
o Each table must have atleast one column.
o SQL commands should end with a semicolon (;).
Example: Create a table “STUDENT” that contains five columns: RegNo, Name, Combination,
DOB and Fees.
CREATETABLESTUDENT (
RegNo NUMBER(6),
Name VARCHAR2(15),
Combination CHAR(4),
DOB DATE,
Fees NUMBER(9,2),
PRIMARY KEY ( RegNo )
);
6 | Page
Chapter14-SQLCommands
ALTERStatement:
Thetablecan bemodified or changedbyusingtheALTER command.
Syntax:BasicsyntaxofALTERTABLEstatementisasfollows:
1. ALTERTABLE Table_name
ADD(column_name1DataType,Cloumn_name2DataType……);
2. ALTERTABLE Table_name
MODIFY(column_name1DataType,Cloumn_name2DataType……);
3. ALTERTABLE Table_name
DROP(column_name1DataType,Cloumn_name2DataType……);
Example:
DROPTABLE:
TheSQLDROPTABLE statementisusedtoremoveatabledefinitionandalldata,indexes, triggers,
constraints, and permission specifications for that table.
Syntax:Basicsyntax ofDROPTABLEstatementisas follows:
7 | Page
Chapter14-SQLCommands
DROPTABLETable_name;
Example:
INSERT:
TheSQLINSERT INTOStatement is usedto add new rows ofdata to atablein thedatabase.
Syntax:
Therearetwobasicsyntaxesof INSERT INTOstatementas follows:
INSERTINTOTABLE_NAME[(column1,column2,column3,...columnN)] VALUES
(value1, value2, value3,...valueN);
Here, column1, column2,...columnN are the names of the columns in the table into which you
want to insert data.
Youmaynot need to specifythecolumn(s)name in theSQLqueryif you areaddingvaluesforall
thecolumns ofthetable. But makesuretheorder ofthevaluesis in thesameorderas thecolumns in the
table.
METHOD1:TheSQLINSERTINTOsyntaxwouldbeasfollows:
INSERTINTOTABLE_NAMEVALUES(value1,value2,value3,...valueN);
Example:FollowingstatementswouldcreatesixrecordsinSTUDENT table:
SQL>INSERTINTOSTUDENTVALUES(1401,'RAMESH','PCMC','07-AUG-99',14000);
1 row created.
SQL>INSERTINTOSTUDENTVALUES(1402,'JOHN','PCMB','15-SEP-99',13500);
1 row created.
SQL>INSERTINTOSTUDENTVALUES(1403,'GANESH','PCME','19-AUG-99',16000);
1 row created.
SQL>INSERTINTOSTUDENTVALUES(1404,'MAHESH','PCMC','14-JAN-98',17650);
1 row created.
SQL>INSERTINTOSTUDENTVALUES(1405,'SURESH','PCMB','03-MAR-98',11500);
1 row created.
SQL>INSERTINTOSTUDENTVALUES(1410,'ARUN','PCMC','01-APR-04',13000);
METHOD2:TheSQLINSERTINTOsyntaxwouldbeasfollows:
SQL>INSERTINTOSTUDENT(REGNO,NAME,FEES)VALUES(1411,'SHREYA',24000);
1 row created.
8 | Page
Chapter14-SQLCommands
SQL>INSERTINTOSTUDENT(REGNO,COMBINATION,FEES)VALUES(1412, 'PCMB',21000);
1 row created.
UPDATE:
SQLprovides theabilityto changedatathrough UPDATE command.
TheUPDATE commandusedto modifyor updatean alreadyexistingroworrows ofatable.
Thebasicsyntax ofUPDATEcommandisgivenbelow.
UPDATE Table_name
SET column_name=value
[,column_name =value .............. ]
[WHERE condition];
Example:
SQL>UPDATESTUDENTSETCOMBINATION='CEBA'WHERE REGNO=1411;
1 row updated.
SQL>UPDATESTUDENTSETNAME='AKASH'WHEREREGNO=1412;
1 row updated.
DELETEcommand:
InSQL,analreadyexistingroworrowsareremovedfromtablesthroughtheuseofDELETE command.
ThebasicsyntaxofDELETEcommandisgiven below.
DELETE Table_name
[WHERE condition];
Example:
SQL>DELETESTUDENTWHERE REGNO=1412;
1 row deleted.
9 | Page
Chapter14-SQLCommands
SELECT:
SQLSELECTstatement is used to fetch the data from a database table which returns data in the
form of result table. These result tables are called result-sets.
Syntax:ThebasicsyntaxofSELECTstatementisasfollows:
SELECTcolumn1,column2,columnN Compulsory
FROM Table_name; Part
[WHEREcondition(s)]
[GROUPBYcolumn-list] Optional
[HAVINGcondition(s)] Part
[ORDERBYcolumn-name(s)];
Here, column1, column2...are the fields of a table whose values you want to fetch. If you want to
fetch all the fields available in the field, then you can use the following syntax:
SELECT*FROM table_name;
Example:ConsidertheSTUDENTtablehavingthefollowingrecords:
Following is an example, which would fetch REGNO, NAME and COMBINATION fields of the
customers available in STUDENT table:
DISTINCT:
The SQLDISTINCTkeyword is used in conjunction with SELECT statement to eliminate all the
duplicate records and fetching only unique records.
10 | Page
Chapter14-SQLCommands
Example:ConsidertheSTUDENTtablehavingthefollowingrecords:
First,letusseehowthefollowingSELECTqueryreturnsduplicatecombination records:
Now,letususeDISTINCTkeywordwiththeaboveSELECTqueryandseethe result:
SQL>SELECTDISTINCTCOMBINATIONFROMSTUDENT ORDER
BY COMBINATION;
WHEREclause–(Extractingspecificrows)
The SQLWHEREclause is used to specify a condition while fetching the data from single table or
joining with multiple tables.
If the given condition is satisfied then onlyit returns specific value from the table. You would use
WHERE clause to filter the records and fetching only necessary records.
11 | Page
Chapter14-SQLCommands
TheWHEREclauseisnotonlyusedinSELECTstatement,butitisalsousedinUPDATE, DELETE
statement, etc., which we would examine in subsequent chapters.
Syntax:ThebasicsyntaxofSELECTstatementwithWHERE clauseisas follows:
SELECT column1,column2,columnN
FROM Table_name
WHERE [condition]
Youcan specifyaconditionusing comparisonorlogicaloperators like>, <,=,LIKE,NOT, etc.
FollowingisanexamplewhichwouldfetchREGNO,NAMEandFEESfieldsfromthe STUDENT table
where FEES is greater than 15000:
Following is an example, which would fetch REGNO, NAME and COMBINATION fields from
the STUDENT table for a COMBINATION is „PCMC‟.
Here, it is important to note that all the strings should be given inside single quotes ('') where
asnumeric values should be given without any quote as in above example:
TheSQLANDandORoperatorsareusedtocombinemultipleconditionstonarrowdatainan SQL
statement. These two operators are called conjunctive operators.
Theseoperatorsprovideameanstomakemultiplecomparisonswithdifferentoperatorsinthe same SQL
statement.
TheANDOperator:
TheANDoperatorallowstheexistenceofmultipleconditionsinanSQLstatement'sWHERE clause.
Syntax:ThebasicsyntaxofANDoperatorwithWHERE clauseisas follows:
12 | Page
Chapter14-SQLCommands
You can combine N number of conditions using AND operator. For an action to be taken by the
SQLstatement, whether it be a transaction or query, all conditions separated by the AND must be
TRUE.
Example:ConsidertheSTUDENTtablehavingthefollowingrecords:
Following is an example, which would fetch REGNO, NAME and DOB fields from the
STUDENT table where fees is less than 1500 AND combination is „PCMC:
The OR Operator:
TheOR operator is usedto combine multipleconditions inan SQLstatement's WHERE clause.
You can combine N number of conditions using OR operator. For an action to be taken by the
SQLstatement, whether it be a transaction or query, only anyONE of the conditions separated by
the OR must be TRUE.
Following is an example, which would fetch REGNO, NAME and DOB fields from the
STUDENT table where fees is less than 1500 OR combination is „PCMC:
13 | Page
Chapter14-SQLCommands
ORDERBY–(Sortingthedata)
The SQLORDER BYclause is used to sort the data in ascending or descending order, based on
one or more columns. Some database sorts query results in ascending order by default.
Syntax:ThebasicsyntaxofORDERBY clauseisasfollows:
SELECT column-list
FROM Table_name
[WHERE condition]
[ORDERBY column1,column2,..columnN][ASC|DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever columnyouare
using to sort, that column should be in column-list.
Example:ConsidertheSTUDENTtablehavingthefollowingrecords:
14 | Page
Chapter14-SQLCommands
Workingoutsimplecalculations.
Whenever we want to perform simple calculations such as 10 / 5, we can perform using SELECT
statement which causes an output on monitor.
ButSELECTrequirestablenametooperate.
One can make use of the dummy table provided by SQL called DUAL which is a single row
andsingle column table.
Itisusedwhendatafromtableisnot required.
Forexample,whenacalculationistobeperformedsuchas10*3,10/2etc.andtodisplaythe current system
date, we could use the following queries.
SQLFunctions:
TheSQLfunctions servethepurposeofmanipulatingdataitems andreturningaresult.
Thereare manybuilt in functions included inSQLand can be classified as Group Functions and
Scalar Functions.
GroupFunctions:
o Functionsthatactonset ofvaluesarecalledgroupfunctions.
o A group functions can takes entire column of data as its arguments and produces a single
data item that summarizes the column.
o FollowingaretheSQLgroup functions.
Function Description
AVG Returnsaveragevalueof„N‟,ignoringNULLvalues
COUNT(expr) Returnsthenumberofrowswhere„expr‟isnotNULL
Returnsthenumberofrowsinthetableincludingduplicatesandthosewith
COUNT(*)
NULL values
MIN Returnsminimumvalueof„expr‟
MAX Returnsmaximumvalueof „expr‟
SUM Returnssumofvalues„N‟
ScalarFunctions:
o Functionsthatactononlyonevalueatatimearecalledscalar functions.
o Wecan further classifythefunctions usingthe typeof data with theyaredesigned towork.
15 | Page
Chapter14-SQLCommands
Function Description
Numeric Work with numbers.
Functions Examples:ABS,POWER,ROUND,SQRT
String Workwithcharacterbaseddata.
Functions Examples:LOWER,INITCAP,UPPER,SUBSTR,LENGTH,LTRIM,RTRIM
Date WorkwithDatedata types.
Functions Example:ADD_MONTHS,LAST_DAY,MONTHS_BETWEEN,NEXT_DAY
Conversion Thesefunctions areused to convert onetypeof data to another.
Functions Example:TO_NUMBER,TO_CHAR,TO_DATE
ConsidertheEXAMINATION table:
COUNT() Function:
Thisfunction is usedtocount the number ofvalues in a column.
COUNT (*) is used to count the number of rows in the table including duplicates and those with
NULL values.
Example1:
o SELECTCOUNT(*)FROMEXAMINATION;
o Theabove queryreturns10.
Example2:
o SELECTCOUNT(RegNo)FROMEXAMINATIONWHERECC=„C3‟;
o Theabove queryreturns4.
16 | Page
Chapter14-SQLCommands
AVG()Function:
Thisfunction is usedtofind the averageof thevaluesin a numeric column.
Example1:
o SELECTAVG (Cs)FROMEXAMINATION;
o Theabove queryreturns74.7
SUM() Function:
Thisfunction isusedtofindthe sum ofthe valuesina numeric column.
Example:
o SELECTSUM(Phy)FROMEXAMINATION;
o Theabove queryreturns729
MAX()Function:
Thisfunction is usedtofind the maximumvaluesin a column.
Example:
o SELECTMAX(Phy) FROMEXAMINATION;
o Theabove queryreturns100
MIN() Function:
Thisfunctionis usedtofindthe minimumvalues inacolumn.
Example:
o SELECTMIN(Phy)FROM EXAMINATION;
o Theabove queryreturns33
GROUPBY(GroupingResult)
TheSQLGROUPBY clauseisusedincollaborationwiththeSELECTstatementtoarrange identical
data into groups.
TheGROUPBYclausefollowstheWHEREclauseinaSELECTstatementandprecedesthe ORDER BY
clause.
Syntax:ThebasicsyntaxofGROUPBYclauseisgivenbelow.
SELECT column1,column2
FROM Table_name
WHERE [ conditions ]
GROUPBY column1,column2
ORDER BY column1,column2
17 | Page
Chapter14-SQLCommands
Example1:Tofindthenumberofstudentsineachcollege.
SELECT CC, COUNT (CC)
FROM EXAMINATION
GROUPBY CC;
Example2:Tofindthenumberofstudents,sum,average,maximum,minimummarksin computer
science from each city.
SELECT City,COUNT(City),SUM(Cs),AVG(Cs),MAX(Cs),MIN(Cs)
FROM EXAMINATION
GROUPBY City;
SQLCONSTRAINTS:
Constraintsaretherules enforcedondata columnsontable.
Thesearelimitingthe typeof datathatcango intoatable.
Thisensures the accuracyandreliabilityof thedata into the database.
SQLallows twotypes ofconstraints.
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.
Followingarethe commonlyused constraintsavailablein SQL.
Constraints Description
NOTNULL Ensuresthat a column cannot haveNULLvalue
UNIQUE Ensuresthatallvaluesincolumnare different
PRIMARYKEY Uniquelyidentifiedeacrow in adatabasetable.
FOREIGNKEY Uniquelyidentifiedeachrownin anyotherdatabase table
DEFAULT Providesadefault valueforacolumnwhen noneis specified
CHECK Ensuresthatall valuesinacolumn satisfycertaincondition.
NOTNULLConstraint:
Bydefaultcolumn canhold NULLvalues.
Whenacolumnis definedas NOT NULLthen thecolumnbecomes amandatorycolumn.
It implies that avaluemust beentered into thecolumn iftherowis to beinsertedforstoragein the table.
18 | Page
Chapter14-SQLCommands
19 | Page
Chapter14-SQLCommands
FOREIGNKEYConstraint:
AFOREIGN KEYis usedto linktwo tables together.
Aforeign keyisacolumn whosevaluesarederivedfrom thePRIMARYKEYofsomeother table.
Example:
CREATETABLEPRODUCT (
PID CHAR(4) PRIMARYKEY,
Description VARCHAR2(25),NOT NULL
CompanyId CHAR(10)REFERENCESCOMPANY(CID)
DOM DATE,
Type CHAR(10),
Price NUMBER(10,2)
);
CREATETABLECOMPANY
(
CID CHAR(10) PRIMARYKEY,
CProfile VARCHAR2 (200),
Noofproducts NUMBER(20),
DOE DATE
);
DEFAULTConstraints:
Adefault value canbespecifiedforacolumnusing theDEFAULT clause.
TheDEFAULTconstraintprovidesadefaultvaluetoacolumnwhentheINSERTINTO command does
not provide a specific value.
Example:
CREATETABLEPRODUCT (
PID CHAR(4) PRIMARYKEY,
Description VARCHAR2(25),NOTNULL
CompanyId CHAR (10),
DOM DATE,
Type CHAR(10),
Price NUMBER(10,2)DEFALUT1000.00
);
CHECKConstraints:
The CHECK Constraint is used to establish a TRUE/FALSE condition that is applied to the
dataplaced in a column.
If avaluedoesnot meetthecondition,itcannot be placed inthecolumn.
Example:
CREATETABLE PRODUCT
20 | Page
Chapter14-SQLCommands
(
PID CHAR(4) CHECK(PIDLIKE ‘P%’),
Description VARCHAR2(25),
CompanyId CHAR(10),
DOM DATE,
Type CHAR(10),
Price NUMBER(10,2)CHECK(Price>0)
);
TABLEConstraints:
Whenaconstraintis appliedto agroup ofcolumns ofthetable,it iscalledatableconstraint.
Columnconstraint isdefinedalongwith theend of the column.
Tableconstraints aredefinedat theend ofthetable.
Example:
CREATETABLEPRODUCT (
PID CHAR(4) NOTNULL,
Description VARCHAR2(25)NOTNULL,
CompanyId CHAR (10),
DOM DATE,
Type CHAR(10),
Price NUMBER(10,2),
PRIMARYKEY(PID,Description)
);
Joins
TheSQLJoinsclauseareusedtofetch/retrievedatafromtwoormoretablesbasedonthejoin condition
which is specified in the WHERE condition.
Basically data tables are relatedto each other with keys.We can used these keysrelationship inSQL
joins.
21 | Page
Chapter14-SQLCommands
CreatingVIEWs:
DatabaseViewsarecreatedusingtheCREATEVIEWstatement.
Viewscanbecreated fromasingletable,multiple tablesoranother view.
Tocreateaview,ausermusthavetheappropriatesystemprivilegeaccordingtothespecific
implementation.
Syntax:ThebasicCREATEVIEWsyntax isasfollows:
SQL>CREATEVIEW view_name AS
SELECTFROM column1,column2…..
WHERE table_name
[ condition];
PrivilegesandRoles:
Privileges:Privileges definesthe accessrights providedto auseronadatabaseobject.
Therearetwotypes of privileges:
o SystemPrivileges:ThisallowstheusertoCREATE,ALTER,orDROPdatabaseobjects.
o Object privileges:This allows the user toEXECUTE, SELECT,INSERT, UPDATE
orDELETE data from database objects to which privileges apply.
CHAPTER14–STRUCTUREDQUERYLANGUAGEBLUEPRINT
VSA(1 marks) SA(2marks) LA(3Marks) Essay(5Marks) Total
- 01 Question - 01 Question 02 Question
- Questionno17 - Questionno36 06 Marks
ImportantQuestions
TwoMarksQuestions:
22 | Page
Chapter14-SQLCommands
6. What is the difference between ORDER BY and GROUP BY clause used in SQL? Give example
for each. [June 2017]
7. ListtherelationaloperatorssupportedbySQL.
8. Whythe DROPcommand used?Writeitssyntax.
9. Whatarethe differencebetweenDROP andDELETEcommand?
10. Givethesyntax andexampleforCREATEVIEW commandin SQL.
11. Classifythe built-in functions inSQL.
FiveMarksQuestion:
****************
23 | Page