0% found this document useful (0 votes)
7 views23 pages

chapter-14-sql-commands

Uploaded by

naveedshahapuri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
7 views23 pages

chapter-14-sql-commands

Uploaded by

naveedshahapuri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

Chapter14-SQLCommands

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:

 DDL-Data Definition Language:


 DDLdefinestheconceptualschemaprovidingalinkbetweenthelogicalandthephysical structure of
the database.
 The functions of the Data Definition Language(DDL)are:
1. DDL defines the physical characteristics of each record, filed in the record, fields data type,
fields length, fields logical name and also specify relationship among those records.
2. DDL describes the schema and subschema.
3. DDL indicate the keys of records.
4. DDL provides data security measures.
5. DDL provides for the logical and physical data independence.
 Few of the basic commands for DDL are:
Command Description
CREATE Creates a new table, a view of a table, or other object in database
ALTER Modifies an existing database object, such as a table.
DROP Deletes an entire table, a view of a table or other object in the database.

 DML-Data Manipulation Language:


 DMLprovidesthedatamanipulationtechniqueslikeselection,insertion,deletion,updation,
modification, replacement, retrieval, sorting and display of data or records.
 DML facilitates use of relationship between the records.
 DMLprovidesforindependenceofprogramminglanguagesbysupportingseveralhigh-level
programming languages like COBOL, PL/1 and C++.
 Few of the basic commands for DML are:
Command Description
SELECT Retrieves certain records from one or more tables
INSERT Creates a record
UPDATE Modifies records
DELETE Deletes records

2 | Page
Chapter14-SQLCommands

 DCL-Data Control Language:


 These SQL commands are used for providing security to database objects.
 The different DCL commands are:
Command Description
GRANT Gives a privilege to user
REVOKE Takes back privileges granted from user

 TCL–Transaction Control Language:


 It includes commands to control the transactions in a database system.
 The commonly used commands are:
Command Description

COMMIT Make all the changes made by the statements issued


permanent.
ROLLBACK Undoes all changes since the beginning of transaction or
Since a save point.

 Data Types in SQL:


 The following are the most common data types of SQL:
SL
DATATYPE DESCRIPTION
No
A variable-length column. Allowed values are zero,
1 NUMBER
Positive and negative numbers
2 CHAR A variable length fieldupto255characterinlength

3 VARCHAR/VARCHAR2 A variable length fieldupto2000characterinlength


A fixed length field. The time is stored as a part of the
4 DATE/TIME
date. The default format is DD/MON/YY
5 LONG A variable length filed upto 2GBin length
A variable length filed used for binary data up to2000
6 RAW
in length
A variable length filed used for binary data up to2GB
7 LONGRAW
in length

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

 Structure of SQL command:


 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.

4 | Page
Chapter14-SQLCommands

 SELECT, FROM and WHERE are keywords.


 The clauses are “FROM student” and “WHERE Reg No=109”.
 Here SELECT and FROM are mandatory, but WHERE is optional.
 Name, Student, Reg No, are identifier that refers to objects in the database.
 Name and Reg No are column names, while Student is a table name.
 The equal sign is an operator and 109 is a numeric constant.

 What is an Operator 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)

 SQL Logical Operators:


 Here is a list of all the logical operators available in SQL.
Operator Description
ALL The ALL operator is used to compare a value to all values in another value set.
The AND operator allows the existence of multiple conditions in an SQL statement's
AND
WHERE clause.
The ANY operator is used to compare a value to any applicable value in the list according
ANY
to the condition.
The BETWEEN operator is used to search for values that are within a set of values, given
BETWEEN
The minimum value and the maximum value.
The EXISTS operator is used to search for the presence of a row in a specified table that
EXISTS
Meets certain criteria.
The IN operator is used to compare a value to a list of literal values that have been
IN
specified.
LIKE The LIKE operator is used to compare a value to similar values using wild card operators.
The NOT operator reverses the meaning of the logical operator with which it is used. Eg:
NOT
NOT EXISTS, NOT BETWEEN,NOT IN, etc. This is an egate operator.
The OR operator is used to combine multiple conditions in a SQL statement's WHERE
OR
clause.

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

 Implementation of SQL Commands

 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

 It creates an empty STUDENT table which looks like this:

RegNo Name Combination DOB Fees


 Viewing the table information:
o The DESCRIBE or DESC command displays name of the columns, their data type and size
along with the constraints.

 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:

 Usingthe ALTER TABLE command the followingtasks cannot be performed


o Changingatablename.
o Changingthecolumnname.
o Decreasingthe sizeof acolumn iftable data exists.
o Changingacolumn‟sdatatype.

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

 Alltheabovestatementswouldproducethe followingrecords inSTUDENTtable:

 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

 Theremaybeasituation when you have multipleduplicaterecords in atable.Whilefetchingsuch


records, it makes more sense to fetch only unique records instead of fetching duplicate records.
 Syntax:ThebasicsyntaxofDISTINCTkeywordtoeliminateduplicaterecordsisasfollows:

SELECTDISTINCT column1,column2,. .... columnN


FROM Table_name
WHERE [condition]

 Example:ConsidertheSTUDENTtablehavingthefollowingrecords:

 First,letusseehowthefollowingSELECTqueryreturnsduplicatecombination records:

 Now,letususeDISTINCTkeywordwiththeaboveSELECTqueryandseethe result:

SQL>SELECTDISTINCTCOMBINATIONFROMSTUDENT ORDER
BY COMBINATION;

 Thiswould producethe followingresult wherewedo not haveanyduplicateentry:

 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:

SELECT column1,column2,columnN Table_name


FROM [condition1]AND[condition2]...AND [conditionN];
WHERE

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

 Syntax:ThebasicsyntaxofOR operator withWHEREclauseisas follows:

SELECT column1,column2,columnN Table_name


FROM [condition1] OR[condition2]...OR[conditionN];
WHERE

 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:

 Followingis an example, which wouldsort theresult in ascendingorder byNAME:

 Followingisanexample,which wouldsort theresult indescendingorderbyNAME:

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:

RegNo Name CC Phy Che Mat Cs Total City


101 Ajay C1 98 100 97 99 394 Hassan
102 Banu C2 38 50 37 49 174 Belur
103 Chandan C2 100 100 97 99 396 Mysuru
104 John C3 78 80 67 79 304 Alur
105 Kaleem C1 88 80 91 79 338 Hassan
106 Raheem C2 100 98 97 79 374 Hassan
107 Sanjay C3 47 60 56 78 241 Alur
108 Tarun C3 33 34 77 28 172 Arasikere
109 Uday C2 100 98 97 79 374 Hassan
110 Venki C3 47 60 56 78 241 Belur

 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

 Example:ConsiderthefollowingCREATETABLEcommandcreatesanewtablecalled PRODUCT and


add six columns, two which PID and Description specify not to accept NULLs.
CREATETABLEPRODUCT (
PID CHAR(4) NOT NULL,
Description VARCHAR2(25),NOTNULL
CompanyId CHAR(10),
DOM DATE,
Type CHAR(10),
Price NUMBER(10,2)
);
 UNIQUEConstraints:
 This constraint ensures that no rows have the same value in the specified column(s). A table must
have many unique keys.
 Example: UNIQUE constraint applied on PID of PRODUCT table ensures that no rows have
thesame PID value, as shown below
CREATETABLEPRODUCT (
PID CHAR(4) NOTNULLUNIQUE,
Description VARCHAR2(25),NOTNULL
CompanyId CHAR (10),
DOM DATE,
Type CHAR(10),
Price NUMBER(10,2)
);
 PRIMARYKEYConstraints:
 A primarykeyis a field which uniquelyidentifies each row in a database table. A primarykeyin a
table has special attributes:
 BydefaultthiscolumnisNOTNULL.Itdefinesthecolumnasamandatorycolumni.e.the column cannot
be left blank.
 Thedata held in thiscolumn must be unique.
 Example:
CREATETABLEPRODUCT (
PID CHAR(4) PRIMARYKEY,
Description VARCHAR2(25),NOTNULL
CompanyId CHAR (10),
DOM DATE,
Type CHAR(10),
Price NUMBER(10,2)
);

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

 SQL Join Types:


 TherearedifferenttypesofjoinsavailableinSQL:
o INNERJOIN: returnsrows whenthereisa matchin both tables.
o LEFTJOIN:returnsallrowsfromthelefttable,eveniftherearenomatchesintheright table.
o RIGHTJOIN:returnsallrowsfromtherighttable,eveniftherearenomatchesintheleft table.
o FULLJOIN:returns rowswhen thereis amatchinone ofthe tables.
o SELFJOIN:isusedtojoinatabletoitselfasifthetableweretwotables,temporarily renaming at least
one table in the SQL statement.

21 | Page
Chapter14-SQLCommands

o CARTESIANJOIN:returnstheCartesianproductofthesetsofrecordsfromthetwoor more joined


tables.

 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:

1. Givethesyntax andexampleforDELETE commandin SQL. [March2015]


2. ListthedatatypessupportedinSQL. [June 2015]
3. Writethesyntax forDELETEandINSERTcommandsin SQL. [March2016]
4. Mentionthelogicaloperatorsusedin SQL. [June 2016]
5. GivethesyntaxandexampleofUPDATE commandin SQL. [March2017]

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:

1. Explainvariousgroupfunctionsin SQL. [March2015,March2017,June2017]


2. Whatisdatadefinitionlanguage?ExplainSELECTandUPDATE command. [June 2015]
3. Describeanyfivelogicaloperatorsavailablein SQL. [March2016]
4. WhatisSQL?ExplainthedifferentSQLcommands.
5. WhatisthepurposeofCREATEcommand?WritethesyntaxandexampleofCREATE command.
6. ExplainSELECTstatementwithsyntax andwithminimum3examples.
7. Explain5variationsofSELECTcommand.
8. WhatareSQLconstraints?Explain anytwo constraints.

****************

23 | Page

You might also like