Chapter 12 – SQL Notes
What is SQL?
– When a user wants to get some information from a database file, he can issue a query.
– A query is a user–request to retrieve data or information with a certain condition.
– SQL is a query language that allows user to specify the conditions. (instead of
algorithms)
Concept of SQL :
– The user specifies a certain condition.
– The program will go through all the records in the database file and select those records
that satisfy the condition.(searching).
– Statistical information of the data.
– The result of the query will then be stored in form of a table.
Basic structure of an SQL query
General SELECT, ALL / DISTINCT, *,
Structure AS, FROM, WHERE
Comparison IN, BETWEEN, LIKE "% _"
Grouping GROUP BY, HAVING,
COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )
Display Order ORDER BY, ASC / DESC
Logical AND, OR, NOT
Operators
Output INTO TABLE / CURSOR
TO FILE [ADDITIVE], TO PRINTER, TO SCREEN
Union UNION
SELECT ...... FROM ...... WHERE ......
SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ;
FROM tablename WHERE condition
– The query will select rows from the source tablename and output the result in table
form.
– Expressions expr1, expr2 can be :
SQL Notes Compiled By Ms. Chandni Agarwal(MAMS) Page 1
– (1) a column, or (2) an expression of functions and fields.
– And col1, col2 are their corresponding column names in the output table.
– DISTINCT will eliminate duplication in the output while ALL will keep all duplicated rows.
– condition can be :
– (1) an inequality, or (2) a string comparison
– using logical operators AND, OR, NOT.
– The Situation: Student Particulars
field type width contents
id numeric 4 student id number
name character 10 name
dob date 8 date of birth
sex character 1 sex: M / F
class character 2 class
hcode character 1 house code: R, Y, B, G
dcode character 3 district code
remission logical 1 fee remission
mtest numeric 2 Math test score
Before using SQL, open the student file: USE student
eg. 1 List all the student records.
SELECT *
eg. 2 List
Function FROM student ;
the names and house code of 1A
students.
SELECT
s: name, hcode, class FROM student
WHERE class="1A" ;
eg. 3 List
members. # days : the residential district of the Red House
SELECT
hcode="R" ; DATE( ) DISTINCT dcode FROM student WHERE
– dob
SQL Notes Compiled By Ms. Chandni Agarwal(MAMS) Page 2
# years :
eg. 4 (DATE( )
List the names and ages (1 d.p.) of 1B girls.
– dob) /
SELECT name, ROUND((DATE( )-dob)/365,1) AS age
FROM student WHERE class="1B" AND sex="F" ;
II Comparison
–
365
expr IN ( value1, value2, value3)
– expr BETWEEN value1 AND value2
1 d.p.:
– expr LIKE "%_"
eg. 6 List the students who were born on Wednesday or Saturdays.
eg. 7
ROUND(
SELECT name, class, CDOW(dob) AS bdate FROM student WHERE DOW(dob) IN (4,7) ;
List the students who were not born in January, March, June, September.
eg. 8
__ , 1)
SELECT name, class, dob FROM student WHERE MONTH(dob) NOT IN (1,3,6,9) ;
List the 1A students whose Math test score is between 80 and 90 (incl.)
SELECT name, mtest FROM student WHERE class="1A" AND mtest BETWEEN 80 AND 90 ;
eg. 9 List the students whose names start with "T".
SELECT name, class FROM student WHERE name LIKE "T%" ;
eg. 10 List the Red house members whose names contain "a" as the 2nd letter.
SELECT name, class, hcode FROM student WHERE name LIKE "_a%" AND hcode="R" ;
III Grouping: -SELECT ...... FROM ...... WHERE condition GROUP BY groupexpr [HAVING requirement];
Group functions: COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )
– groupexpr specifies the related rows to be grouped as one entry. Usually it is a column
– WHERE condition specifies the condition of individual rows before the rows are group.
HAVING requirement specifies the condition involving the whole group.
eg. 11 List the number of students of each class.
class class
1
SELECT class, COUNT(*) FROM student GROUP BY class; 1 11 11
eg. 12 List the average Math test score of each class. 11A 11A A
A A
SELECT class, AVG(mtest) FROM student GROUP BY class; 11B1 A 111BB
B
B 1B B
eg. 13 List the number of girls of each district. 1B11 B 11
B
B B 1C
Student1C Student
SELECT dcode, COUNT(*) FROM student WHERE sex="F" GROUP
C
BY
C
C
dcode ; C
SQL Notes Compiled By Ms. Chandni Agarwal(MAMS) Page 3
eg. 14 List the max. and min. test score of Form 1 students of each district.
SELECT MAX(mtest), MIN(mtest), dcode FROM student WHERE class LIKE "1_" GROUP BY dcode ;
IV Display Order
eg. 16 List the boys of class 1A, order by their names.
SELECT name, id FROM student WHERE sex="M" AND class="1A" ORDER BY name;
eg. 17 List the 2A students by their residential district.
SELECT name, id, class, dcode FROM student WHERE class="2A" ORDER BY dcode ;
eg. 18 List the number of students of each district (in desc. order).
SELECT COUNT(*) AS cnt, dcode FROM student GROUP BY dcode ORDER BY cnt DESC;
Natural Join
A Natural Join is a join operation that joins two tables by their common column. This operation is
similar to the setting relation of two tables.
SELECT a.comcol, a.col1, b.col2, expr1, expr2 FROM table1 a, table2 b WHERE a.comcol = b.comcol ;
eg. 26 Find the number of students learning piano in each class.
SELECT s.class, COUNT(*) FROM student s, music m WHERE s.id=m.id AND
m.type="Piano" GROUP BY class ORDER BY class
Summary of SQL Queries
A query in SQL can consist of up to six clauses, but only the first two, SELECT and
FROM, are mandatory. The clauses are specified in the following order:
SELECT <attribute list> FROM <table list> [WHERE <condition>] [GROUP BY <grouping attribute(s)>]
[HAVING <group condition>] [ORDER BY <attribute list>]
The SELECT-clause lists the attributes or functions to be retrieved
The FROM-clause specifies all relations (or aliases) needed in the query but not those needed in
nested queries
The WHERE-clause specifies the conditions for selection and join of tuples from the relations
specified in the FROM-clause
GROUP BY specifies grouping attributes
HAVING specifies a condition for selection of groups
SQL Notes Compiled By Ms. Chandni Agarwal(MAMS) Page 4
ORDER BY specifies an order for displaying the result of a query
A query is evaluated by first applying the WHERE-clause, then
GROUP BY and HAVING, and finally the SELECT-clause
The INSERT INTO Statement is used to insert new rows into a table.
Syntax :- INSERT INTO table_name VALUES (value1, value2,....) ;
You can also specify the columns for which you want to insert data:
INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....) ;
Insert a New Row
INSERT INTO Persons VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes') ;
Insert Data in Specified Columns
INSERT INTO Persons (LastName, Address) VALUES ('Rasmussen', 'Storgt 67') ;
The UPDATE Statement is used to modify the data in a table.
Syntax : UPDATE table_name SET column_name = new_value WHERE column_name
= some_value;
Update one Column in a Row - We want to add a first name to the person with a last name of
"Rasmussen":
UPDATE Person SET FirstName = 'Nina' WHERE LastName = 'Rasmussen' ;
Update several Columns in a Row- We want to change the address and add the name of the city:
UPDATE Person SET Address = 'Stien 12', City = 'Stavanger' WHERE LastName =
'Rasmussen' ;
The Delete Statementis used to delete rows in a table.
Syntax: DELETE FROM table_name WHERE column_name = some_value ;
Delete a Row - "Nina Rasmussen" is going to be deleted:
DELETE FROM Person WHERE LastName = 'Rasmussen'
Delete All Rows- It is possible to delete all rows in a table without deleting the table. This means that the
table structure, attributes, and indexes will be intact:
DELETE FROM table_name Or DELETE * FROM table_name ;
SQL Notes Compiled By Ms. Chandni Agarwal(MAMS) Page 5