Ch-13,14,15 SQL and Mysql
Ch-13,14,15 SQL and Mysql
MySQL ELEMENTS
LITERALS
It refer to a fixed data value. This fixed data value may be of character type or numeric type. For example,
‘replay’ , ‘Raj’, ‘8’ , ‘306’ are all character literals.
Numbers not enclosed in quotation marks are numeric literals. E.g. 22 , 18 , 1997 are all numeric literals.
Numeric literals can either be integer literals i.e., without any decimal or be real literals i.e. with a decimal point
e.g. 17 is an integer literal but 17.0 and 17.5 are real literals.
DATA TYPES
Data types are means to identify the type of data and associated operations for handling it. MySQL data
types are divided into three categories:
Numeric
Date and time
String types
NULL VALUE
If a column in a row has no value, then column is said to be null , or to contain a null. You should use a null value
when the actual value is not known or when a value would not be meaningful. NULL doesn’t used in arithmetic
expression like if we add NULL+10 it will evaluate NULL it is not equal to zero.
DATABASE COMMANDS
In order to insert another row in EMPLOYEE table , we write again INSERT command :
INSERT INTO employee
VALUES(1002 , ‘Akash’ , ‘M’ , ‘A1’ , 35000);
- To insert value NULL in a specific column, we can type NULL without quotes and NULL will be inserted in that
column. E.g. in order to insert NULL value in ENAME column of above table, we write INSERT command as :
- The NOT IN operator finds rows that do not match in the list. E.g.
SELECT * FROM EMPLOYEE
WHERE GRADE NOT IN (‘A1’ , ‘A2’);
Output will be :
ENAME
Ravi
Ruby
to display the names of those students whose marks is NULL, we use the command :
SELECT Name FROM EMPLOYEE
WHERE Marks IS NULL ;
Output will be :
Name
ARUN
SANJAY
SORTING RESULTS
Whenever the SELECT query is executed , the resulting rows appear in a predecided order.The ORDER BY clause allow
sorting of query result. The sorting can be done either in ascending or descending order, the default is ascending.
The ORDER BY clause is used as :
SELECT <column name> , <column name>….
FROM <tablename>
WHERE <condition>
ORDER BY <column name> ;
e.g. to display the details of employees in EMPLOYEE table in alphabetical order, we use command :
SELECT *
FROM EMPLOYEE
ORDER BY ENAME ;
Output will be :
ECODE ENAME GENDER GRADE GROSS
1002 Akash M A1 35000
1004 Neela F B2 38965
1009 Neema F A2 52000
1001 Ravi M E4 50000
1006 Ruby F A1 45000
1005 Sunny M A2 30000
e.g. display list of employee in descending alphabetical order whose salary is greater than 40000.
SELECT ENAME FROM EMPLOYEE WHERE GROSS > 40000 ORDER BY ENAME desc ;
Output will be :
ENAME
Ravi
Ruby
Neema
e.g. to change the salary of employee of those in EMPLOYEE table having employee code 1009 to 55000.
UPDATE EMPLOYEE
SET GROSS = 55000
WHERE ECODE = 1009 ;
UPDATING MORE THAN ONE COLUMNS
e.g. to update the salary to 58000 and grade to B2 for those employee whose employee code is 1001.
UPDATE EMPLOYEE
SET GROSS = 58000, GRADE=’B2’
WHERE ECODE = 1009 ;
OTHER EXAMPLES
e.g.1. Increase the salary of each employee by 1000 in the EMPLOYEE table.
UPDATE EMPLOYEE
SET GROSS = GROSS +100 ;
e.g.2. Double the salary of employees having grade as ‘A1’ or ‘A2’ .
UPDATE EMPLOYEE
SET GROSS = GROSS * 2 ;
WHERE GRADE=’A1’ OR GRADE=’A2’ ;
e.g.3. Change the grade to ‘A2’ for those employees whose employee code is 1004 and name is Neela.
UPDATE EMPLOYEE
SET GRADE=’A2’
WHERE ECODE=1004 AND GRADE=’NEELA’ ;
DELETING DATA FROM TABLES
To delete some data from tables, DELETE command is used. The DELETE command removes rows from a
table. The syntax of DELETE command is :
DELETE FROM <tablename>
WHERE <condition> ;
For example, to remove the details of those employee from EMPLOYEE table whose grade is A1.
DELETE FROM EMPLOYEE
WHERE GRADE =’A1’ ;
TO DELETE ALL THE CONTENTS FROM A TABLE
DELETE FROM EMPLOYEE ;
So if we do not specify any condition with WHERE clause, then all the rows of the table will be deleted. Thus
above line will delete all rows from employee table.
DROPING TABLES
The DROP TABLE command lets you drop a table from the database. The syntax of DROP TABLE command is :
DROP TABLE <tablename> ;
e.g. to drop a table employee, we need to write :
DROP TABLE employee ;
Once this command is given, the table name is no longer recognized and no more commands can be given on that table.
After this command is executed, all the data in the table along with table structure will be deleted.
S.NO. DELETE COMMAND DROP TABLE COMMAND
1 It is a DML command. It is a DDL Command.
2 This command is used to delete only rows This command is used to delete all the data of the table
of data from a table along with the structure of the table. The table is no
longer recognized when this command gets executed.
3 Syntax of DELETE command is: Syntax of DROP command is :
DELETE FROM <tablename> DROP TABLE <tablename> ;
WHERE <condition> ;
To add a column to a table, ALTER TABLE command can be used as per following syntax:
However if you specify NOT NULL constraint while adding a new column, MySQL adds the new column with the
default value of that datatype e.g. for INT type it will add 0 , for CHAR types, it will add a space, and so on.
e.g. Given a table namely Testt with the following data in it.
Col1 Col2
1 A
2 G
Now following commands are given for the table. Predict the table contents after each of the following statements:
(i) ALTER TABLE testt ADD col3 INT ;
(ii) ALTER TABLE testt ADD col4 INT NOT NULL ;
(iii) ALTER TABLE testt ADD col5 CHAR(3) NOT NULL ;
(iv) ALTER TABLE testt ADD col6 VARCHAR(3);
MODIFYING COLUMNS
Column name and data type of column can be changed as per following syntax :
DELETING COLUMNS
To delete a column from a table, the ALTER TABLE command takes the following form :
DEFAULT CONSTARINT
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not
provide a specific value. E.g.
e.g.
Parent Table
TABLE: STUDENT
ROLL_NO NAME CLASS
Primary key
1 ABC XI
2 DEF XII
3 XYZ XI Child Table
TABLE: SCORE
ROLL_NO MARKS
1 55
2 83
3 90
Here column Roll_No is a foreign key in table SCORE(Child Table) and it is drawing its values from
Primary key (ROLL_NO) of STUDENT table.(Parent Key).
CREATE TABLE STUDENT
( ROLL_NO integer NOT NULL PRIMARY KEY ,
NAME VARCHAR(30) ,
CLASS VARCHAR(3) );
CREATE TABLE SCORE
( ROLL_NO integer ,
MARKS integer ,
FOREIGN KEY(ROLL_NO) REFERNCES STUDENT(ROLL_NO) ) ;
* Foreign key is always defined in the child table.
Syntax for using foreign key
FOREIGN KEY(column name) REFERENCES Parent_Table(PK of Parent Table);
REFERENCING ACTIONS
Referencing action with ON DELETE clause determines what to do in case of a DELETE occurs in the parent table.
Referencing action with ON UPDATE clause determines what to do in case of a UPDATE occurs in the parent table.
Actions:
1. CASCADE : This action states that if a DELETE or UPDATE operation affects a row from the parent table, then
automatically delete or update the matching rows in the child table i.e., cascade the action to child table.
2. SET NULL : This action states that if a DELETE or UPDATE operation affects a row from the parent table, then
set the foreign key column in the child table to NULL.
3. NO ACTION : Any attempt for DELETE or UPDATE in parent table is not allowed.
4. RESTRICT : This action rejects the DELETE or UPDATE operation for the parent table.
Q: Create two tables
Customer(customer_id, name)
Customer_sales(transaction_id, amount , customer_id)
Underlined columns indicate primary keys and bold column names indicate foreign key.
Make sure that no action should take place in case of a DELETE or UPDATE in the parent table.
Sol : CREATE TABLE Customer (
customer_id int Not Null Primary Key ,
name varchar(30) ) ;
CREATE TABLE Customer_sales (
transaction_id Not Null Primary Key ,
amount int ,
customer_id int ,
FOREIGN KEY(customer_id) REFERENCES Customer (customer_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION );
Q: Distinguish between a Primary Key and a Unique key in a table.
S.NO. PRIMARY KEY UNIQUE KEY
1. Column having Primary key can’t contain Column having Unique Key can contain
NULL value NULL value
2. There can be only one primary key in Table. Many columns can be defined as Unique key
2. COUNT( )
This function counts the number of rows in a given column.If you specify the COLUMN name in parenthesis of
function, then this function returns rows where COLUMN is not null.If you specify the asterisk (*), this function
returns all rows, including duplicates and nulls.
e.g. SELECT COUNT(*)
FROM EMPL ;
Output
COUNT(*)
5
3. MAX( )
This function returns the maximum value from a given column or expression.
5. SUM( )
This function returns the sum of values in given column or expression.
e.g. SELECT SUM(SAL)
FROM EMPL ;
Output
SUM(SAL)
30258
GROUPING RESULT – GROUP BY
The GROUP BY clause combines all those records(row) that have identical values in a particular field(column) or a
group of fields(columns).
GROUPING can be done by a column name, or with aggregate functions in which case the aggregate produces a
value for each group.
Table : EMPL
JOINS The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a
means for combining fields from two tables by using values common to each.
EQUI JOIN: the join in which columns are compared for equality
NATURAL JOIN: the join in which only one of the identical column (coming from joined tables) exists,
Difference between Natural and Equi join: - duplicate columns are eliminated in the natural join that would
otherwise appear in the Equi join
Consider the table CARDEN and CUSTOMER
Table :CARDEN
Code Cname Make Color capacity charges
501 A-star Suzuki Red 3 14
503 Indigo Tata Silver 3 12
502 Innova Toyoto White 7 15
509 SX4 Suzuki Silver 4 14
510 C-class Mercedes Red 4 35
512 Wagon R Suzuki black 3 14
Table :CUSTOMER
Ccode Name code
1001 Ravi Kumar 501
1002 Jatin Sharma 509
1003 ManojKaushik 503
1004 NitinBhardwaj 502
Example of Equi join :
Select Code, Cname, make ,color, name from carden,customer where carden.code=customer.code;
In this example code will appear twice from both table
Example of Natural join :
Select H.Code,H.Cname, H.make ,H.color, C.name from carden H ,customer C where H.code=C.code;
In this example code will appear only once fro. Carden table as alias of Carden is made from both table
CARTESIAN PRODUCT: the Cartesian product is really a cross-join which returns all the rows in all the
tables listed in a query: each row in the first table is paired with all the rows in the second table. This happens
when there is no relationship defined between the two tables.
The Cartesian product is a new table formed of two tables. If those tables have 3 and 4 lines respectively, the
Cartesian product table will have 3×4 lines.
Table A
Code Colour
C01 Red
C02 Blue
Table: B
Custno Custname
101 Ram
102 Rahim
Select * fromTable A ,Table B
Code Colour
C01 Red 101 Ram
C01 red 102 Rahim
C02 Blue 101 Ram
C02 Blue 102 Rahim