You are on page 1of 8

SPECTRUM STUDY CIRCLE (The Acme of Excellence) 1

15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)
Class: XII C++ STRUCTURED QUERY LANGUAGE
* Structured Query Language (SQL) is a language that enables to create and operate on relational
databases, which are sets of related information stored in tables.
* Data Definition Language (DDL): The SQL DDL provides commands for defining relation schema,
deleting relations, creating indexes, and modifying relation schemes.
* Data Manipulation Language (DML): The SQL DML includes a query Language bases on both
relational algebra and tuple relational calculus. It includes commando to insert, delete and modify
tuples in database.
DATA DEFINITION LANGUAGE
A database scheme is specified by a set of definitions which are expressed by a special language
called DDL. The result of compilation of DDL statement is set of tables stored in data dictionary (or
directory)
* DATA DICTIONARY is file that contains “meta data” i.e. “data about data”.

DATA MANUPULATION LANGUAGE


After the database scheme has been specified ‘&’ database has been created, the data can be
manipulated using a set of procedures which are expressed by a special language called Data
manipulation Language
→ The retrieval of information stored in data base.
→ The insertion of new information into database.
→ The deletion of information from database
→ The modification of data stored in database
Hence, DML is a Language that enables users to access or manipulate data as organized by the appropriate
data model
The DMLs are basically of two types
• Procedural DML → requires user to specify what data is needed and how to get it
• Non procedural DML → requires user to specify what data is needed without specifying how to get
it.
Concept of SQL Processing
* CHAR (or character): Values of this type must be enclosed in single quotes such as ‘example’
* INT (or integer) : represents a number without a decimal point
* FLOAT : represents a floating point number in base 10 exponential notation. The size
argument consists of a single number specifying minimum precision.
* DEC (or decimal) : represents fractional numbers as17.321, here size argument has two part,
precision & scale
given size (5,2) indicates precision as 5 & scale as 2. Here scaled cannot
exceed the precision
Keywords are words that have special meaning in SQL commands/statements are instructions given to SQL
database command consists of one or more logically distinct parts
called CLAUSES
Example WHERE VALUE = 150.00, or
FROM Sales
* Tables are defined with CREATE TABLE command
* When a table is created, its columns are named, data types & sizes are supplied for each column
// To create an employee table whose scheme is
employee (ecode, ename, sex, grade)
The SQL command will be
CREATE TABLE employee
(
Ecode integer,
ename char (20);
sex char (1);
grade char (2);
SPECTRUM STUDY CIRCLE (The Acme of Excellence) 2
15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)
Class: XII C++ STRUCTURED QUERY LANGUAGE
SYNTAX
CREATE TABLE < table – name>
(
<column-name> <data type> [ (<size>)],
<column name> <data type> [(<size>)].............) ;
CREATE TABLE employee
(
ecode integer Not Null Unique,
ename, char (20) Not Null,
Sex char (1) );
Note: UNIQUE Constraint is always applied to Not Null
PRIMARY KEY CONSTRAINT
This constraint declares a column as primary key of table. It is similar to UNIQUE, except that only one
column (or One group of columns can be applied in this. It cannot allow Null Values
CREATE TABLE employee
(
ecode integer Not Null PRIMARY KEY,
ename char (20) Not Null,
Sex char (1) );
DEFAULT CONSTRAINT
When a year does not enter a value for column, it can set automatically the defined default value for that
column
* NOT NULL columns cannot have NULL as default
* A column can have only one default value

CHECK CONSTRAINT
It limits values that can be inserted into a column of a table
CREATE TABLE employee
(
ecode integer NOT NULL PRIMARY KEY,
ename char(20) NOT NULL,
sex char (1) NOT NULL,
grade char (2) DEFAULT = ‘E’
gross decimal CHECK (gross > 2000);
* This statement ensures that value inserted for gross must be greater than 2000
* It is specified after all, the column, when it involves more than one column
CREATE TABLE items
(
icode char(5),
descp char (20),
ROL integer,
QOH integer,
CHECK (ROL < QOH);
Compares two columns ROL and QOH, hence two columns must defined before check constraint.

Examples of CHECK CONSTRAINT USING ‘IN’


→ descp char (20) CHECK
(descp IN (‘NUT’, ‘BOLT’, ‘SCREW’) )
→ Price decimal CHECK
(price BETWEEN 253.00 and 777.00)
→ CHECK ( (discount = 0.15 AND city = ‘HISSAR’ ) OR
(discount = 0.13 AND city = ‘JAIPUR’) OR
SPECTRUM STUDY CIRCLE (The Acme of Excellence) 3
15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)
Class: XII C++ STRUCTURED QUERY LANGUAGE
(discount = 0.17 AND city = ‘DELHI’) )
TABLE CONSTRAINT
When a Constraint is applied on a group of columns of table, it is called table constraint
CREATE TABLE items
(
icode char (5) NOT NULL,
descp char (20) NOT NULL,
ROL integer,
QOH integer,
CHECK (ROL < QOH),
UNIQUE (icode, descp) );
If you want to declare A PRIMARY KEY as combination firstname and lastname, it can be done as
CREATE TABLE members
(
first name char (15) NOT NULL,
last name char (15) NOT NULL,
city char (20),
PRIMARY KEY (firstname, lastname));
SELECT COMMAND
To make queries on database
Query is a command that is given to produce certain specified information from database table
If you want to view only two columns empno and empname
SELECT Empro, Empname
FROM emp,
SYNTAX
SELECT < column name > [, >column-name>,.............]
FROM < table name>;
* All Keyword retains the duplicate output rows It is just same when you specify neither Distinct nor All
Select All city From suppliers;
The output will be
City
Delhi
Mumbai
Delhi
Banglore
Jaipur
* SELECTING SPECIFIC ROWS
For such condition, when certain rows are needed, we use ‘WHERE” clause
SYNTAX: SELECT < column name > [,<column name>,.............]
FROM < table name >
WHERE < condition> ;
Example: SELECT empname, empno, sal
FROM emp
WHERE (Sal > 2900) ;
Relational Operators
= , >, <, > = , < = , < >
LOGICAL OPERATORS
OR, AND, NOT
example: SELECT * FROM suppliers
Where City < > ‘DELHI’ ;
(OR)
SELECT ecode, ename, grade, gross
SPECTRUM STUDY CIRCLE (The Acme of Excellence) 4
15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)
Class: XII C++ STRUCTURED QUERY LANGUAGE
FROM employee
WHERE (grade = ‘E4’ AND gross < 9000);
SELECT icode, descp, QOH
FROM items
WHERE QOH BETWEEN 30 AND 50 ;
(Condition Based on Range)
This query will list the items whose ROC is below 100 and above 1000
SELECT icode, descp
FROM items
WHERE ROL NOT BETWEEN 100 AND 1000 ;
// Condition Based on List
SELECT * FROM members
WHERE city IN (‘DELHI’, ‘MUMBAI’, ‘CHENNAI’ ) ;
SELECT * FROM members
WHERE city NOT IN (‘DELHI’, ‘MUMBAI’);
It will list members not from the cities mentioned in list
PATTERN MATCHES
% Character matches any substring
(-) under score matches any character
* “LIKE” keyword is used to select rows containing colkumns that match pattern
→ “San %” matches any string beginning with “San”
→ “% bid%” matches any string containing “bid”as substring
→ “ - - - - - -“ matches any string of exactly 4 characters
→ “- - - - - - %” matches any string of at least 3 characters
→ SELECT firstname, lastname, city
FROM members
WHERE pin like “13%”;
// To list employees of names of 4 character endline with “D”
→ SELECT empno, empname
FROM emp
WHERE empname LIKE “ - - - - - -D”;
// Searching for Null
→ SELECT empno, empname, Job
FROM emp
WHERE DeptNo IS NULL;
* SORTING RESULTS BY “ORDER BY” CLAUSE
// To display list of employees in ascending order of their names
SELECT * FROM employee
ORDER BY ename;
// To display list of employees in descending order of employee code
SELECT * FROM employee
ORDER BY ecode DESC;
SELECT * FROM employee
ORDER BY grade DESC, ename ASC.
// For simple calculations, the Dual table is used. It is dummy table
Select 4 * 3 FROM dual
Output: 4 * 3 = 12
// To find system date
SELECT Sysdate FROM dual ;
AGGREGATE FUNCTIONS
avg → To compute average value
min → To find minimum value
SPECTRUM STUDY CIRCLE (The Acme of Excellence) 5
15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)
Class: XII C++ STRUCTURED QUERY LANGUAGE
max → To find maximum value
sum → To find total value
Stddev → To find standard deviation
Count → To count non-null values in a column
Count (*) → To count total number of rows in a table
Variance → To compute variance of values in column
→ SELECT sum (gross) FROM employee WHERE grade = ‘E2’
→ SELECT avg (gross)
FROM employee
WHERE (grade = ‘E2’ OR grade = ‘E1’);
To display the average gross of employee with grades ‘E1’ or ‘E2’
→ SELECT count (*)
FROM employee;
To count no of employees in employee table
→ SELECT count (DISTINCT city)
FROM members;
→ SELECT Count (All city)
FROM members;
Grouping Results – GROUP BY
Select Job, Count (*), Sum (comm.)
emp
GROUP BY job ;
It is used to divide the table into groups. It is done by column name or with aggregate function
GROUP BY applies the aggregate functions independently to a series of groups that are defined by having a
field value in common
Job COUNT (*) SUM (COMM)
PRESIDENT 1 0
MANAGER 3 0
SALESMAN 4 2200
ANALYST 2 0
* HAVING clause places conditions on groups, WHERE clause places conditions on individual rows.
→ SELECT Job, Count (*)
FROM emp
GROUP BY job
HAVING Count (*) < 3 ;
JOB COUNT(*)
PRESIDENT 1
ANALYST 2
→ SELECT avg (gross), sum (gross)
FROM employee
GROUP BY grade
HAVING grade = ‘E4’ ;
// Scalar expression with selected fields
→ SELECT Salesman-name, Comm*100
FROM Salesman;
// Putting Text in Query output
→ SELECT Salesman-name, Comm*100, ‘%’
FROM Salesman;
Salesman-name
AJAY 13.00%
AMIT 11.00%
SHALLY 07.00%
SPECTRUM STUDY CIRCLE (The Acme of Excellence) 6
15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)
Class: XII C++ STRUCTURED QUERY LANGUAGE
→ SELECT salesman-name, ‘gets the commission’, Comm*100, ‘%’ FROM Salesman ;
o/p :Ajay gets the commission 13.00%
Amit gets the commission 11.00%
Shally gets the commission 07.00%
SELECT SYNTAX
SELECT column list
FROM < table name >
WHERE < predicate >
GROUP BY < column name >
HAVING < search condition >
ORDER BY column-name ;
CREATING TABLE FROM EXISTING TABLE
→ CREATE TABLE orditem AS
(
SELECT icode, descp
FROM items
WHERE (QOH < ROL) );
It will create New table orditem from old table items
→ SELECT icode, descp INTO orditems
FROM items
WHERE (QOH < ROL);
It is same o/p, by implementation of SELECT INTO Command
UNION – COMBINING QUERIES
* It operates on two or more queries by combining results into a single set
IF Relation A Relation B
Roll no Name Age Roll no Name Age
1 A1 15 4 A4 17
2 A2 16 7 A7 19
3 A2 17 5 A5 18
3 A3 17
→ SELECT * FROM A
UNION
SELECT * FROM B ;
Roll no Name Age
1 A1 15
2 A2 16
3 A3 17
4 A4 17
7 A7 19
5 A5 18

SELECT empno, empname


FROM Accounts → Relation 1
UNION
SELECT empno, empname
FROM Sales → Relation 2
ORDER BY empno desc;
* FOR UNION OPERATOR, the select lists must have same number of columns having similar data
types & order
→ SELECT ecode, ename
FROM R1
UNION
SPECTRUM STUDY CIRCLE (The Acme of Excellence) 7
15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)
Class: XII C++ STRUCTURED QUERY LANGUAGE
SELECT ename, ecode
FROM R2
* IN UNION operator, the ORDER BY occur at end of UNION. It can’t be used with in individual
queries, BUT, GROUP BY & HAVING CLAUSES are allowed within individual queries, since
these cannot be used to affect final Result set
INTERSECT OPERATOR
It gives those rows that are common in multiple tables
SELECT job FROM Accounts
INTERSECT
SELECT job FROM Research
INTERSECT
SELECT job FROM Sales ;
O/p: Manager
(Since all the relations have Manager Job in common)
MINUS OPERATION
(A –B) Part/portion of A, which is not in B hence, all the rows that are selected by first Query, which are not
in following query
SELECT job FROM Accounts
MINUS
SELECT job FROM Sales
O/p only the jobs that are in Accounts relation but not in sales relation
INSERT COMMAND
Syntax: INSERT INTO < tablename > [< column List >
VALUES ( < value >, <value > , - - - - - - - );
→ INSERT INTO employee (ecode, ename, sex)
VALUES (2014, ‘Manju’, ‘F’);
The columns that are not listed will have their default value or Null value
→ INSERT INTO employee
VALUES (1001, ‘Ravi’, ‘M’, ‘E4’, 467.00);
* Only those columns can be omitted that have either default value defined or they allow Null values
INSERT INTO branch1
SELECT * FROM branch2
WHERE gross > 7000.00;
DELETE COMMAND
This removes entire rows, not individual field values.
DELETE FROM < table name>
[WHERE < predicate > ];
→ DELETE FROM items ; // to delete all contents of item table
→ DELETE FROM employee
WHERE gross < 2200.00;
DROP TABLE COMMAND
It drop a table from database, It must be an Empty table A table with rows cannot be dropped
DELETE FROM items; → It removes all rows
// Now to drop empty table
DROP TABLE items;
* UPDATE COMMAND *
// To change ROL of all items to 250
UPDATE items
SET ROL = 250 ;
To change ROL to 400 only for those that have ROL = 300
UPDATE items
SET ROL = 400
SPECTRUM STUDY CIRCLE (The Acme of Excellence) 8
15/22 IInd Floor Ashok Nagar, New Delhi-110018. Ph.: 25499279, 55711031(O), 9810865706(M)
Class: XII C++ STRUCTURED QUERY LANGUAGE
WHERE ROL = 300;
Update multiple columns
UPDATE items
SET ROL = 400, QOH = 700
WHERE icode < ‘1040’ ;
→ UPDATE employee
SET gross = gross + 900
WHERE (grade= ‘E3’ or grade = ‘E4’);
// updating to Null
→ UPDATE employees
SET grade = NULL
WHERE grade = ‘E4’;
CREATE VIEW COMMAND
It is a virtual table with no data, but can be operated like any other table
→ CREATE VIEW taxpayee
As SELECT *
FROM employee
WHERE gross>8000;
Now, the view can be queried as
SELECT * FROM taxpayee;
CREATE VIEW can be specified by Column name (new)
→ CREATE VIEW taxpayee (empcode, empname, sex)
As SELECT * FROM employee
WHERE gross > 8000;
→ CREATE VIEW taxpayee (ecode, ename, tax)
As SELECT ecode, ename, gross*0.1
FROM employee;
DROP-VIEW COMMAND
To delete a view from a database,
DROP VIEW taxpayee ;
to drop the view taxpayee
ALTER TABLE COMMAND
Syntax: ALTER TABLE < table name> ADD < column> <data type> <size> ;
example →
ALTER TABLE Emp
ADD (tel-number integer);
// It is also used to modify existing columns
ALTER TABLE Emp
MODIFY (JOB char (30) );
Syntax: ALTER TABLE < table name>
MODIFY (column name newdata type (newsize)

You might also like