Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Querying and SQL Functions

Sample database Database: CARSHOWROOM


Relations:
• INVENTORY (CarID, CarName, Price, Model, YearManufacture, FuelType)
• CUSTOMER (CustID, CustName, CustAdd, Phone, Email)
• SALE (InvoiceNo, CarID, CustID, SaleDate, PaymentMode, EmpID, SalePrice)
• EMPLOYEE (EmpID, EmpName, DOB, DOJ, Designation, Salary)
• MANAGER(MNo, MNAME)
• DANCE(SNo, Name, Class)
• MUSIC(SNo, Name, Class)
SQL Functions
A. Single Row or Scalar
Functions
A.1. Numeric or Math
Functions
A.1.1. POWER(base, exp) SELECT POWER(2, 3); #8
A.1.2. ROUND(num, dec) SELECT ROUND(2912.564, 1); #2912.6
SELECT ROUND(283.2); #283
SELECT ROUND(283.2, -1); #280
SELECT ROUND(283.2, -2); #300
SELECT ROUND(283.2, -3); #0
Calculate GST as 12% of Price and display the result after rounding it off to one decimal
place.
SELECT ROUND(12/100*Price,1) 'GST' FROM INVENTORY;
Add a new column FinalPrice to the table inventory, which will have the value as sum of
Price and 12% of the GST.
ALTER TABLE INVENTORY ADD(FinalPrice Numeric(10,1));
UPDATE INVENTORY SET FinalPrice=Price+Round(Price*12/100,1);
Add a new column Commission to the SALE table. The column Commission should have a
total length of 7 in which 2 decimal places to be there. Calculate commission for sales agents
as 12 per cent of the SalePrice, insert the values to the newly added column Commission and
then display records of the table SALE where commission > 73000.
ALTER TABLE SALE ADD(Commission Numeric(7,2));
UPDATE SALE SET Commission=ROUND(12/100*SalePrice,2);
Display InvoiceNo, SalePrice and Commission such that commission value is rounded off to
0.
SELECT InvoiceNo, SalePrice, Round(Commission,0) FROM SALE;
Display the InvoiceNo and commission value rounded off to zero decimal places.
Display the details of SALE where payment mode is credit card.
A.1.3. MOD(num, den) SELECT MOD(20, 2); #0
SELECT MOD(21, 2); #1
Calculate and display the amount to be paid each month (in multiples of 1000) which is to be
calculated after dividing the FinalPrice of the car into 10 instalments. After dividing the
amount into EMIs, find out the remaining amount to be paid immediately, by performing
modular division.
SELECT CarId, FinalPrice, ROUND((FinalPrice -
MOD(FinalPrice,10000))/10,0) 'EMI', MOD(FinalPrice,10000) 'Remaining
Amount' FROM INVENTORY;
A.2. String or Text Functions
A.2.1. UCASE(string) SELECT UCASE("Informatics Practices"); #INFORMATICS PRACTICES
OR Convert the CarMake to uppercase if its value starts with the letter ‘B’.
UPPER(string)
A.2.2. LOWER(string) SELECT LOWER("Informatics Practices"); #informatics practices
OR Display customer name in lower case and customer email in upper case from table
LCASE(string) CUSTOMER.
SELECT LOWER(CustName), UPPER(Email) FROM CUSTOMER;
A.2.3. MID(string, pos, n) SELECT MID("Informatics", 3, 4); #form
OR SELECT MID('Informatics',7); #atics
SUBSTRING(string, pos, n) Let us assume that four digit area code is reflected in the mobile number starting from
OR position number 3. For example, 1851 is the area code of mobile number 9818511338. Write
SUBSTR(string, pos, n) the SQL query to display the area code of the customer living in Rohini.
SELECT MID(Phone,3,4) FROM CUSTOMER WHERE CustAdd like '%Rohini%';
#1163
A.2.4. INSTR(string, substring) SELECT INSTR("Informatics", "ma"); #6
Display designation of employee and the position of character ‘e’ in designation, if present.
A.2.5. LENGTH(string) SELECT LENGTH("Informatics"); #11
If the length of the car’s model is greater than 4 then fetch the substring starting from
position3 till the end from attribute Model.

Display the length of the email and part of the email from the email ID before the character
‘@’. Do not print ‘@’.

770945127.docx 1
Function INSTR returns the position of "@" in the email column, so to print email without
"@" use (position-1).
SELECT LENGTH(Email), LEFT(Email, INSTR(Email, "@")-1) FROM CUSTOMER;
LENGTH(Email) LEFT(Email, INSTR(Email, "@")-1)
19 amitsaha2
19 rehnuma
19 charvi123
19 gur_singh
A.2.6. LEFT(string, N) SELECT LEFT("Computer", 4); #Comp
A.2.7. RIGHT(string, N) SELECT RIGHT("SCIENCE", 3); #NCE
Display employee name and the last 2 characters of his EmpId.
A.2.8. LTRIM(string) SELECT LENGTH(" DELHI "),LENGTH(LTRIM(" DELHI ")); #11 7
A.2.9. RTRIM(string) SELECT LENGTH(" DELHI "),LENGTH(RTRIM(" DELHI ")); #11 9
A.2.10. TRIM(string) SELECT LENGTH(" DELHI "),LENGTH(RTRIM(" DELHI ")); #11 5
Display emails after removing the domain name extension “.com” from emails of the
customers.
SELECT TRIM(".com" from Email) FROM CUSTOMER;
TRIM(".com" FROM Email)
amitsaha2@gmail
rehnuma@hotmail
charvi123@yahoo
gur_singh@yahoo
Display details of all the customers having yahoo emails only.
SELECT * FROM CUSTOMER WHERE Email LIKE "%yahoo%";
CustID CustName CustAdd Phone Email
C0003 CharviNayyar 10/9, FF, Rohini 6811635425 charvi123@yahoo.com
C0004 Gurpreet A-10/2,SF, 3511056125 gur_singh@yahoo.com
MayurVihar
.
A.3. Date and Time Functions
A.3.1. NOW() SELECT NOW(); #2019-07-11 19:41:17
A.3.2. DATE(date/time) SELECT DATE(NOW()); #2019-07-11
A.3.3. MONTH(date) SELECT MONTH(NOW()); #7
A.3.4. MONTHNAME(date) SELECT MONTHNAME(“2003-11-28”); # November
A.3.5. YEAR(date) SELECT YEAR(“2003-10-03”); #2003
A.3.6. DAY(date) SELECT DAY(“2003-03-24”); #24
A.3.7. DAYNAME(date) SELECT DAYNAME(“2019-07-11”); # Thursday
Select the day, month number and year of joining of all employees.
SELECT DAY(DOJ), MONTH(DOJ), YEAR(DOJ) FROM EMPLOYEE;
DAY(DOJ) MONTH(DOJ) YEAR(DOJ)
12 12 2017
5 6 2016
8 1 1999
2 12 2010
1 7 2012
1 1 2017
23 10 2013
If the date of joining is not a Sunday, then display it in the following format "Wednesday,
26, November, 1979."
SELECT DAYNAME(DOJ), DAY(DOJ), MONTHNAME(DOJ), YEAR(DOJ) FROM
EMPLOYEE WHERE DAYNAME(DOJ)!='Sunday';
DAYNAME(DOJ) DAY(DOJ) MONTHNAME(DOJ) YEAR(DOJ)
Tuesday 12 December 2017
Friday 8 January 1999
Thursday 2 December 2010
Wednesday 23 October 2013
List the day of birth for all employees whose salary is more than 25000.
Aggregate or Group or
Multiple Row Functions
MAX(col) SELECT MAX(Price) FROM INVENTORY; #673112.00
MIN(col) SELECT MIN(Price) FROM INVENTORY; #355205.00
Find the maximum and minimum commission from the SALE table.
AVG(col) SELECT AVG(Price) FROM INVENTORY; #576091.625000
Display the average price of all the cars with Model LXI from table INVENTORY.
SELECT AVG(Price) FROM INVENTORY WHERE Model="LXI"; #548306.500000
SUM(col) SELECT SUM(Price) FROM INVENTORY; #4608733.00
Find sum of Sale Price of the cars purchased by the customer having ID C0001 from table
SALE.
COUNT(col) SELECT COUNT(NAME) FROM MANAGER; #3
Display the total number of different types of Models available in table INVENTORY.
SELECT COUNT(DISTINCT Model) FROM INVENTORY; #6
COUNT(*) SELECT COUNT(*) from MANAGER; #4

770945127.docx 2
Display the total number of records from table INVENTORY having model VXI.
SELECT COUNT(*) FROM INVENTORY WHERE Model="VXI"; #2
GROUP BY IN SQL Display the number of cars purchased by each customer from the SALE table.
SELECT CustID, COUNT(*) "Number of Cars" FROM SALE GROUP BY CustID;
CustID Number of Cars
C0001 2
C0002 2
C0003 1
C0004 1
Display the customer Id and number of cars purchased if the customer purchased more
than 1 car from SALE table.
SELECT CustID, COUNT(*) FROM SALE GROUP BY CustID HAVING Count(*)>1;
CustID COUNT(*)
C0001 2
C0002 2
Display the number of people in each category of payment mode from the table SALE.
SELECT PaymentMode, COUNT(PaymentMode) FROM SALE GROUP BY Paymentmode
ORDER BY Paymentmode;
PaymentMode Count(PaymentMode)
Bank Finance 2
Cheque 1
Credit Card 2
Online 1
Display the PaymentMode and number of payments made using that mode more than once.
SELECT PaymentMode, Count(PaymentMode) FROM SALE GROUP BY Paymentmode
HAVING COUNT(*)>1 ORDER BY Paymentmode;
PaymentMode Count(PaymentMode)
Bank Finance 2
Credit Card 2
List the total number of cars sold by each employee.
List the maximum sale made by each employee.
To display the class strength of 10A, 11A and 12C if class strength is more than 30.
SELECT class, count(*) FROM student WHERE class IN('10A','11A','12C')
GROUP BY class HAVING count(*)>30;

770945127.docx 3
OPERATIONS ON
RELATIONS
Union To get the list of students participating in either of events; returns those rows which are same
DANCE U MUSIC in both the tables.
SELECT * FROM DANCE
UNION
SELECT * FROM MUSIC;
To return the cities (distinct values) from both "Customers" and "Suppliers" tables.
SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY
City;
To return the cities (including duplicate values) from both "Customers" and "Suppliers"
tables.
SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER
BY City;
To return German cities (distinct values) from both "Customers" and the "Suppliers" tables.
SELECT City, Country FROM Customers WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers WHERE Country='Germany' ORDER BY
City;
To return German cities (incl. duplicate values) from both "Customers" and the "Suppliers"
tables.
SELECT City, Country FROM Customers WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers WHERE Country='Germany' ORDER BY
City;
To list all the customers and suppliers.
SELECT 'Customer' AS Party, ContactName, City, Country FROM Customers
UNION
SELECT 'Supplier' AS Party, ContactName, City, Country FROM
Suppliers;
Intersection To display the list of students who are participating in both the events; returns the common
DANCE ∩ MUSIC tuples from two tables.
SELECT * FROM DANCE
INTERSECT
SELECT * FROM MUSIC;
Minus or Set Difference or To display the list of students who are only participating in only first event i.e. DANCE but
Exception not in second or MUSIC event; returns the tuples which are in the first table but not in the
DANCE - MUSIC second table.
SELECT * FROM DANCE
MINUS
SELECT * FROM MUSIC;
SQL JOINS
Cartesian Product To return all probable combinations of tuples from two relations, regardless of whether or
OR not they have the same values on common attributes. Returns a relation in which Degree =
Cross Join sum of degrees of input relations and Cardinality = product of cardinality of input relations.
DANCE  MUSIC SELECT * FROM DANCE
CROSS JOIN
SELECT * FROM MUSIC;
OR
SELECT * FROM DANCE, MUSIC;
To fetch all the rows from both joining tables
SELECT * FROM customers CROSS JOIN contacts;
To avoid redundant columns, use individual column names instead of SELECT * statement
which also helps in fetching the columns without ambiguity from multiple tables where
some column names are similar in both the tables – use the table name before the column
names.
SELECT customer.customer_id, customer.cust_name, customer.income,
orders.order_id, orders.price FROM customer CROSS JOIN orders;
CROSS JOIN with WHERE clause to return the filter result from the table.
SELECT customers.customer_id, customers.cust_name, customers.income,
orders.order_id, orders.price
FROM customers CROSS JOIN orders USING(customer_id)
WHERE price>1500 AND price<5000;
CROSS JOIN multiple tables - To join three table customers, orders, and contacts. First
CROSS JOIN between orders and contacts and then LEFT JOIN to be executed according to
the specified condition.
SELECT * FROM customer LEFT JOIN(orders CROSS JOIN contacts)
ON customer.customer_id=contact_id ORDER BY income;

770945127.docx 4
Equi Join JOIN operation combines tuples from two tables based on specified conditions unlike
cartesian product which make all possible combinations of tuples.
From the all possible combinations of tuples of relations DANCE and MUSIC, display only
those rows such that the attribute name in both have the same value. Returns tuples with
same values in the name column.
(i) Using condition in where clause
SELECT * FROM DANCE D, MUSIC M WHERE D.Name=M.Name;
D and M are relation aliases (shortened names) for DANCE and MUSIC.
(ii) Explicit use of JOIN clause (without where clause)
SELECT * FROM UNIFORM U JOIN COST C ON U.Ucode=C.Ucode;
Condition given with join clause.
To return the rows from both the relations related on the values of common columns –
typically column in one relation is PK and related column in second relation is FK.
SELECT * FROM STUDENT s, TUTOR t WHERE s.roll=t.roll;
SELECT s.roll, s.sname, t.tname FROM STUDENT s, TUTOR t WHERE
s.roll=t.roll;
#s.roll is primary key , t.roll is foreign key
To join three tables using equijoin
SELECT C.custname, C.account, B.balance, I.mobile
FROM customer AS C, balance AS B, custinfo AS I
WHERE C.account = B.accnum AND B.accnum = I.accnum;
Natural Join SELECT * FROM STUDENT NATURAL JOIN TUTOR;
Inner Join To avoid redundant column in the result of equi join queries
(equivalent of intersection of SELECT * FROM STUDENT s INNER JOIN TUTOR t ON s.roll=t.roll;
two sets)
Left Outer Join SELECT * FROM STUDENT s LEFT OUTER JOIN TUTOR t ON s.roll=t.roll;
Right Outer Join SELECT * FROM STUDENT s RIGHT OUTER JOIN TUTOR t ON s.roll=t.roll;
Full Outer Join SELECT * FROM STUDENT s FULL OUTER JOIN TUTOR t ON s.roll=t.roll;
OR
Full Join
Self Join SELECT * FROM STUDENT s1, Student s2 WHERE s1.roll<>s2.roll AND
s1.group=s2.group;
Self join is a join in which a table is joined with itself (called Unary relationships),
especially when the table has a FOREIGN KEY which references its own PRIMARY KEY.
Consider a table EMPLOYEE that has one-to-many relationship.
CREATE TABLE employee(empid varchar(5) NOT NULL, empname varchar(20)
NULL, dtofjoin date NULL, empsupv varchar(5) NULL, CONSTRAINT empid
PRIMARY KEY(empid), CONSTRAINT empsupv FOREIGN KEY(empsupv)
REFERENCES employee(empid));
Unary relationship to employee
In table EMPLOYEE, empid is the primary key. The field empsupv is the foreign key i.e. the
supervisor’s employee id.
To list the employees and the names of their supervisors, JOIN the EMPLOYEE table to
itself to get this list.
How employees are related to themselves
An employee may report to another employee (supervisor). An employee may supervise
himself (i.e. zero) to many employees (subordinates).
To get the list of employees and their supervisor, use the table EMPLOYEE twice by using
the alias of the table.
SELECT a.emp_id AS "Emp_ID",a.emp_name AS "Employee Name",
b.emp_id AS "Supervisor ID",b.emp_name AS "Supervisor Name"
FROM employee a, employee b
WHERE a.emp_supv = b.emp_id;

770945127.docx 5
Reference: https://www.w3schools.com/sql/

INSERT INTO statement inserts new records in a table.


INSERT INTO table_name (col1, col2, col3, ...) VALUES (val1, val2, val3, ...);

ORDER BY clause sorts the resultset in ascending (default) or descending order of the values of the specified columns.
SELECT * FROM Customers ORDER BY Country ASC, CustomerName DESC;

LIMIT clause limits the number of rows in the resultset.


SELECT * FROM Customers LIMIT 3;

EXISTS Operator
EXISTS operator tests for the existence of any row in a subquery and returns TRUE if subquery returns one or more rows.
SELECT colname(s) FROM tablename WHERE EXISTS (SELECT colname FROM tablename WHERE condition);
To return TRUE and list the suppliers with a product price less than 20
SELECT SupplierName FROM Suppliers WHERE EXISTS (SELECT ProductName FROM Products WHERE
Products.SupplierID = Suppliers.supplierID AND Price < 20);
To return TRUE and list the suppliers with a product price equal to 22
SELECT SupplierName FROM Suppliers WHERE EXISTS (SELECT ProductName FROM Products WHERE
Products.SupplierID = Suppliers.supplierID AND Price = 22);

ANY and ALL Operators


ANY and ALL operators perform a comparison between a single column value and a range of other values.

ANY operator returns a boolean value as a result and returns TRUE if ANY of the subquery values meet the condition.
ANY means that the condition will be true if the operation is true for any of the values in the range.
SELECT column_name(s) FROM table_name WHERE column_name operator ANY (SELECT column_name FROM
table_name WHERE condition);
The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
To list the ProductName if it finds ANY records in the OrderDetails table has Quantity equal to 10 (this will return TRUE
because the Quantity column has some values of 10):
SELECT ProductName FROM Products WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails
WHERE Quantity =10);
To list the ProductName if it finds ANY records in the OrderDetails table has Quantity larger than 99. This will return TRUE
because the Quantity column has some values larger than 99.
SELECT ProductName FROM Products WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails
WHERE Quantity > 99);
The following SQL statement lists the ProductName if it finds ANY records in the OrderDetails table has Quantity larger than
1000 (this will return FALSE because the Quantity column has no values larger than 1000):
SELECT ProductName FROM Products WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails
WHERE Quantity > 1000);

ALL operator returns a boolean value as a result and returns TRUE if ALL of the subquery values meet the condition. It is
used with SELECT, WHERE and HAVING statements. ALL means that the condition will be true only if the operation is true
for all values in the range.
SELECT ALL column_name(s) FROM table_name WHERE condition;
SELECT column_name(s) FROM table_name WHERE column_name operator ALL (SELECT column_name FROM
table_name WHERE condition);
The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
To list ALL the product names
SELECT ALL ProductName FROM Products WHERE TRUE;
To list the ProductName if ALL the records in the OrderDetails table has Quantity equal to 10. This will return FALSE
because the Quantity column has many different values (not only the value of 10).
SELECT ProductName FROM Products WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails
WHERE Quantity = 10);

SELECT INTO Statement


The SELECT INTO statement copies data from one table into a new table.
Copy all columns into a new table
SELECT * INTO newtable [IN externaldb] FROM oldtable WHERE condition;
Copy only some columns into a new table
SELECT column1, column2, column3, ... INTO newtable [IN externaldb] FROM oldtable WHERE
condition;
New table will be created with column-names and types as defined in the old table. Create new column names using AS clause.
To create a backup copy of Customers
SELECT * INTO CustomersBackup2017 FROM Customers;
Using IN clause to copy the table into a new table in another database
SELECT * INTO CustomersBackup2017 IN 'Backup.mdb' FROM Customers;
Copies only a few columns into a new table

770945127.docx 6
SELECT CustomerName, ContactName INTO CustomersBackup2017 FROM Customers;
To copy only the German customers into a new table
SELECT * INTO CustomersGermany FROM Customers WHERE Country = 'Germany';
To copy data from more than one table into a new table
SELECT Customers.CustomerName, Orders.OrderID INTO CustomersOrderBackup2017 FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
To use SELECT INTO to create a new empty table using the schema of an existing table, just add a WHERE clause that causes
the query to return no data.
SELECT * INTO newtable FROM oldtable WHERE 1 = 0;

INSERT INTO SELECT Statement


The INSERT INTO SELECT statement copies data from one table and inserts it into another table. It requires that the data
types in source and target tables match. The existing records in the target table are unaffected.
Copy all columns from one table to another table
INSERT INTO table2 SELECT * FROM table1 WHERE condition;
Copy only some columns from one table into another table
INSERT INTO table2(col1,col2,...) SELECT col1,col2,... FROM table1 WHERE condition;
To copy "Suppliers" into "Customers" (the columns that are not filled with data, will contain NULL)
INSERT INTO Customers (CustomerName, City, Country) SELECT SupplierName, City, Country FROM
Suppliers;
To copy "Suppliers" into "Customers", fill all columns
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country) SELECT
SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;
To copy only the German suppliers into "Customers"
INSERT INTO Customers (CustomerName, City, Country) SELECT SupplierName, City, Country FROM
Suppliers WHERE Country='Germany';

CASE Statement
The CASE statement goes through conditions and returns a value when the first condition is met (like an if-then-else
statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in
the ELSE clause. If there is no ELSE part and no conditions are true, it returns NULL.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
To go through the conditions and return a value when the first condition is met.
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText FROM OrderDetails;
To order the customers by City. If City is NULL, then order by Country.
SELECT CustomerName, City, Country FROM Customers
ORDER BY (CASE WHEN City IS NULL THEN Country ELSE City END);

NULL Functions
IFNULL(), ISNULL(), COALESCE(), and NVL() Functions
Assuming "UnitsOnOrder" column which may contain NULL values, following statement will return NULL for rows if
"UnitsOnOrder" value is NULL for that row.
SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder) FROM Products;
IFNULL() function returns an alternative value if an expression is NULL
SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0)) FROM Products;
or use COALESCE() function
SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0)) FROM Products;

SQL Comments
Comments are used to explain sections of SQL statements, or to prevent execution of SQL statements.
Single Line Comments
Single line comments start with --. Any text between -- and the end of the line is ignored i.e. it is not executed.
To use a single-line comment as an explanation
--Select all:
SELECT * FROM Customers;
To use a single-line comment to ignore the end of a line:
SELECT * FROM Customers -- WHERE City='Berlin';
To use a single-line comment to ignore a statement
--SELECT * FROM Customers;
SELECT * FROM Products;

770945127.docx 7
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored.
To use a multi-line comment as an explanation
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;
To use a multi-line comment to ignore many statements
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;
To ignore just a part of a statement, also use the /* */ comment.
To use a comment to ignore part of a line
SELECT CustomerName, /*City,*/ Country FROM Customers;
To use a comment to ignore part of a statement
SELECT * FROM Customers WHERE (CustomerName LIKE 'L%' OR CustomerName LIKE 'R%' /*OR
CustomerName LIKE 'S%' OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%') AND
Country='USA' ORDER BY CustomerName;

CREATE DATABASE Statement


CREATE DATABASE statement creates a new SQL database.
CREATE DATABASE databasename;
To create a database called "testDB"
CREATE DATABASE testDB;
Once a database is created, to check it in the list of databases
SHOW DATABASES;

DROP DATABASE Statement


DROP DATABASE statement drops an existing SQL database
DROP DATABASE databasename;
Be careful before dropping a database. Deleting a database will result in loss of complete information stored in the database.
To drop the existing database "testDB"
DROP DATABASE testDB;

BACKUP DATABASE Statement


BACKUP DATABASE statement creates a full back up of an existing SQL database
BACKUP DATABASE databasename TO DISK = 'filepath';
BACKUP WITH DIFFERENTIAL Statement
A differential back up only backs up the parts of the database that have changed since the last full database backup.
BACKUP DATABASE databasename TO DISK = 'filepath' WITH DIFFERENTIAL;
To create a full back up of the existing database "testDB" to the D disk
BACKUP DATABASE testDB TO DISK = 'D:\backups\testDB.bak';
Always back up the database to a different drive than the actual database. Then, if you get a disk crash, you will not lose your
backup file along with the database.

CREATE TABLE Statement


CREATE TABLE statement creates a new table in a database.
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
Column parameters specify the names of the columns of the table. Datatype parameter specifies the type of data the column
can hold e.g. varchar, int, date, etc.
The following example creates a table called "Persons" that contains five columns: PersonID, LastName, FirstName, Address,
and City:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
The PersonID column is of type int and will hold an integer.
The LastName, FirstName, Address, and City columns are of type varchar and will hold characters, and the maximum length
for these fields is 255 characters.

770945127.docx 8
The empty "Persons" table can now be filled with data with the SQL INSERT INTO statement.
Create table using another table
A copy of an existing table can also be created using CREATE TABLE. New table gets the same column definitions. All
columns or specific columns can be selected.
If a new table is created by using an existing table, the new table is filled with the existing values from the old table.
CREATE TABLE new_table_name AS SELECT col1,col2,...FROM existing_table_name WHERE...;
To create a new table called "TestTables" which is a copy of the "Customers" table
CREATE TABLE TestTable AS SELECT customername, contactname FROM customers;

DROP TABLE Statement


DROP TABLE statement drops an existing table in a database. Be careful before dropping a table. Deleting a table will result
in loss of complete information stored in the table.
DROP TABLE table_name;
To drop the existing table "Shippers"
DROP TABLE Shippers;

TRUNCATE TABLE Statement


TRUNCATE TABLE statement deletes the data inside a table, but not the table itself.
TRUNCATE TABLE table_name;

ALTER TABLE Statement


ALTER TABLE statement adds, deletes, or modifies columns in an existing table. It also adds and drops various constraints on
an existing table.
ALTER TABLE - ADD COLUMN
To add a column in a table
ALTER TABLE table_name ADD column_name datatype;
To add an "Email" column to the "Customers" table
ALTER TABLE Customers ADD Email varchar(255);
To add a column named "DateOfBirth" of type date in the "Persons" table
ALTER TABLE Persons ADD DateOfBirth date;
ALTER TABLE - DROP COLUMN
To delete a column of a table
ALTER TABLE table_name DROP COLUMN column_name;
To delete the "Email" column from the "Customers" table
ALTER TABLE Customers DROP COLUMN Email;
To delete the column named "DateOfBirth" in the "Persons" table.
ALTER TABLE Persons DROP COLUMN DateOfBirth;
ALTER TABLE - ALTER/MODIFY COLUMN
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
To change the data type of the column named "DateOfBirth" in the "Persons" table.
ALTER TABLE Persons ALTER COLUMN DateOfBirth year;

SQL Constraints
SQL constraints are used to specify rules for the data in a table. Constraints are used to limit the type of data that can go into a
table. This ensures the accuracy and reliability of the data in the table. If there is any violation between the constraint and the
data action, the action is aborted. Constraints can be column level or table level. Column level constraints apply to a column,
and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
 NOT NULL - Ensures that a column cannot have a NULL value
 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified
 CREATE INDEX - Used to create and retrieve data from the database very quickly
Create Constraints
Constraints can be specified when the table is created with the CREATE TABLE statement, or after the table is created with
the ALTER TABLE statement.
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
....
);
NOT NULL Constraint
By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT accept NULL values.

770945127.docx 9
This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without
adding a value to this field.
To set the "ID", "LastName", and "FirstName" columns to NOT accept NULL values while creating the table "Persons"
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
To create a NOT NULL constraint on the "Age" column of an existing table "Persons"
ALTER TABLE Persons MODIFY Age int NOT NULL;

UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and PRIMARY KEY constraints
provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a
UNIQUE constraint. There can be many UNIQUE constraints in a table, but only one PRIMARY KEY constraint per table.
To create a UNIQUE constraint on the "ID" column while creating the table "Persons"
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
To create a UNIQUE constraint on the "ID" column of an existing table
ALTER TABLE Persons ADD UNIQUE (ID);
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns
ALTER TABLE Persons ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);
To drop a UNIQUE Constraint
ALTER TABLE Persons DROP INDEX UC_Person;

PRIMARY KEY Constraint


PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot
contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or
multiple columns (fields).
To create a PRIMARY KEY on the "ID" column while creating the table "Persons"
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
To name the PRIMARY KEY constraint and define define a PRIMARY KEY constraint on multiple columns. There is only
one primary key (PK_Person). However, the value of the primary key is made up of two columns (ID + LastName), called
composite primary key.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
To create a PRIMARY KEY constraint on the "ID" column of an existing table
ALTER TABLE Persons ADD PRIMARY KEY (ID);
To name a PRIMARY KEY constraint and to define a PRIMARY KEY constraint on multiple columns
ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);
To use ALTER TABLE to add a primary key, the primary key column(s) must have been declared to not contain NULL values
when the table was first created.
DROP a PRIMARY KEY Constraint
ALTER TABLE Persons DROP PRIMARY KEY;

770945127.docx 10
FOREIGN KEY Constraint
FOREIGN KEY constraint prevents actions that could destroy links between tables. It is a field or a collection of fields in one
table that refers to the PRIMARY KEY in another table. The table with the foreign key is called the child table, and the table
with the primary key is called the referenced or parent table.
Consider two tables: Persons(PersonID, LastName, FirstName, Age) and Orders(OrderID , OrderNumber, PersonID)
The "PersonID" column (FOREIGN KEY) in "Orders" table points to the "PersonID" column (PRIMARY KEY) in "Persons"
table. The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column, because it has to
be one of the values contained in the parent table.
To create a FOREIGN KEY on the "PersonID" column while creating the "Orders" table
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
To name a FOREIGN KEY constraint and to define a FOREIGN KEY constraint on multiple columns
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);
To create a FOREIGN KEY constraint on the "PersonID" column of an existing table "Orders"
ALTER TABLE Orders ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
To name the FOREIGN KEY constraint to define a FOREIGN KEY constraint on multiple columns
ALTER TABLE Orders ADD CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID) REFERENCES
Persons(PersonID);
To drop the FOREIGN KEY constraint
ALTER TABLE Orders DROP FOREIGN KEY FK_PersonOrder;

CHECK Constraint
CHECK constraint limits the value range that can be placed in a column. CHECK constraint defined on a column allows only
certain values for this column. CHECK constraint defined on a table limits the values in certain columns based on the values in
other columns in the row.
To create a CHECK constraint on "Age" column while creating the table "Persons".
To ensure that the age of a person must be 18, or older.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
To name a CHECK constraint, and to define a CHECK constraint on multiple columns
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
To create a CHECK constraint on the "Age" column of an existing table
ALTER TABLE Persons ADD CHECK (Age>=18);
To name a CHECK constraint and to define a CHECK constraint on multiple columns
ALTER TABLE Persons ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
To drop a DEFAULT constraint
ALTER TABLE Persons DROP CHECK CHK_PersonAge;

DEFAULT Constraint
To set a default value for a column which will be added to all new rows, if no other value is specified.
To set a DEFAULT value for the "City" column while creating the "Persons" table
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes',

770945127.docx 11
recordupdate date DEFAULT NOW()
);
To assign a DEFAULT constraint on the "City" column of an existing table
ALTER TABLE Persons ALTER City SET DEFAULT 'Sandnes';
To drop a DEFAULT constraint
ALTER TABLE Persons ALTER City DROP DEFAULT;

CREATE INDEX Statement


CREATE INDEX statement creates indexes in tables. Indexes are used to retrieve data from the database faster. Users cannot
see the indexes, they are just used to speed up searches or queries. Updating a table with indexes takes more time than updating
a table without because the indexes also need an update. So, only create indexes on columns that need frequently searched
against.
Creates an index on a table. Duplicate values are allowed.
CREATE INDEX index_name ON table_name (column1, column2, ...);
Creates a unique index on a table. Duplicate values are not allowed.
CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...);
To create an index "idx_lastname" on "LastName" column in the "Persons" table
CREATE INDEX idx_lastname ON Persons (LastName);
To create an index on a combination of columns, list the column names within the parentheses, separated by commas:
CREATE INDEX idx_pname ON Persons (LastName, FirstName);

DROP INDEX Statement


DROP INDEX statement deletes an index in a table.
ALTER TABLE table_name DROP INDEX index_name;

AUTO INCREMENT Field


Generates a unique number automatically when a new record is inserted into a table.
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);
By default, starting value for AUTO_INCREMENT is 1 and it is incremented by 1 for each new record. Need not specify a
value for "Personid" column while inserting a new record.
To start AUTO_INCREMENT sequence with value 102
ALTER TABLE Persons AUTO_INCREMENT=100;

MySQL data data types for storing a date or a date/time value in the database
 DATE format YYYY-MM-DD
 DATETIME format YYYY-MM-DD HH:MI:SS
 TIMESTAMP format YYYY-MM-DD HH:MI:SS
 YEAR format YYYY or YY
To select the records with an OrderDate of "2008-11-11"
SELECT * FROM Orders WHERE OrderDate='2008-11-11'
Two dates can easily be compared if there is no time component involved. If "Orders" table has time component in the
"OrderDate" column then WHERE OrderDate='2008-11-11' will not get any result.

CREATE VIEW Statement


View is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table.
The fields in a view are fields from one or more real tables in the database. You can add SQL statements and functions to a
view and present the data as if the data were coming from one single table. A view always shows up-to-date data. The database
engine recreates the view, every time a user queries it.
A view is created with the CREATE VIEW statement.
CREATE VIEW view_name AS SELECT column1, column2, ...FROM table_name WHERE condition;
To create a view that shows all customers from Brazil and to query that view
CREATE VIEW [Brazil Customers] AS SELECT CustomerName, ContactName FROM Customers WHERE
Country = 'Brazil';
SELECT * FROM [Brazil Customers];
To create a view that selects every product in the "Products" table with a price higher than the average price
CREATE VIEW [Products Above Average Price] AS SELECT ProductName, Price FROM Products WHERE
Price > (SELECT AVG(Price) FROM Products);
SELECT * FROM [Products Above Average Price];

770945127.docx 12
SQL in Web Pages
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
Batched SQL Statements
A batch of SQL statements is a group of two or more SQL statements, separated by semicolons.
To return all rows from the "Users" table, then delete the "Suppliers" table.
SELECT * FROM Users; DROP TABLE Suppliers
Using SQL Parameters for Protection against SQL Injection
To protect a web site from SQL injection, use SQL parameters. SQL parameters are values that are added to an SQL query at
execution time, in a controlled manner. Parameters are represented in the SQL statement by a special marker. SQL engine
checks each parameter to ensure that it is correct for its column and are treated literally, and not as part of the SQL to be
executed.
To build parameterized queries in some common web languages and Python database connectivity application
INSERT INTO STATEMENT IN PHP
$stmt = $dbh->prepare("INSERT INTO Customers(CustomerName,Address) VALUES(:nam, :add,)");
$stmt->bindParam(':nam', $txtNam);
$stmt->bindParam(':add', $txtAdd);
$stmt->execute();

770945127.docx 13
2. Write the output produced by the following SQL commands:
(a) SELECT POW(2, 3);
(b) SELECT ROUND(123.2345, 2), ROUND(342.9234, -1);
(c) SELECT LENGTH("Informatics Practices");
(d) SELECT YEAR('1979/11/26'), MONTH('1979/11/26'), DAY('1979/11/26'), MONTHNAME('1979/11/26');
(e) SELECT LEFT("INDIA", 3), RIGHT("Computer Science", 4);
(f) SELECT MID("Informatics", 3, 4), SUBSTR("Practices", 3);
3. Consider the following table named “Product”, showing details of products being sold in a grocery shop.
PCode PName UPrice Manufacturer
P01 Washing Powder 120 Surf
P02 Tooth Paste 54 Colgate
P03 Soap 25 Lux
P04 Tooth Paste 65 Pepsodant
P05 Soap
i. SELECT COUNT(DISTINCT PName) FROM Product;
ii. SELECT PName, MAX(UPrice), MIN(UPrice) FROM Product GROUP BY PName;
4. Using the CARSHOWROOM database given in the chapter, write the SQL queries for the following:
(a) Add a new column Discount in the INVENTORY table.
(b) Set appropriate discount values for all cars keeping in mind the following:
(i) No discount is available on the LXI model.
(ii) VXI model gives a 10% discount.
(iii) A 12% discount is given on cars other than LXI model and VXI model.
(c) Display the name of the costliest car with fuel type “Petrol”.
(d) Calculate the average discount and total discount available on Car4.
(e) List the total number of cars having no discount.
5. Consider the following tables Student and Stream in the Streams_of_Students database.
The primary key of the Stream table is StCode (stream code) which is the foreign key in the Student table.
The primary key of the Student table is AdmNo (admission number).
AdmNo Name StCode
211 Jay NULL
241 Aditya S03
290 Diksha S01
333 Jasqueen S02
356 Vedika S01
380 Ashpreet S03
StCode Stream
S01 Science
S02 Commerce
S03 Humanities
Write SQL queries for the following:
(a) Create the database Streams_Of_Students.
(b) Create the table Student by choosing appropriate data types based on the data given in the table.
(c) Identify the Primary keys from tables Student and Stream. Also, identify the foreign key from the table Stream.
(d) Jay has now changed his stream to Humanities. Write an appropriate SQL query to reflect this change.
(e) Display the names of students whose names end with the character ‘a’. Also, arrange the students in alphabetical
order.
(f) Display the names of students enrolled in Science and Humanities stream, ordered by student name in
alphabetical order, then by admission number in ascending order (for duplicating names).
(g) List the number of students in each stream having more than 1 student.
(h) Display the names of students enrolled in different streams, where students are arranged in descending order of
admission number.
(i) Show the Cartesian product on the Student and Stream table. Also mention the degree and cardinality produced
after applying the Cartesian product.
(j) Add a new column "TeacherIncharge" in the Stream table. Insert appropriate data in each row.
(k) List the names of teachers and students.
(l) If Cartesian product is again applied on Student and Stream tables, what will be the degree and cardinality of this
modified table?
38 Dove
P06 Shampoo
245 Dove
(a) Write SQL queries for the following:
i. Create the table Product with appropriate data types and constraints.
ii. Identify the primary key in Product.
iii. List the Product Code, Product name and price in descending order of their product name. If
PName is the same then display the data in ascending order of price.
iv. Add a new column Discount to the table Product.
v. Calculate the value of the discount in the table Product as 10 per cent of the UPrice for all those
products where the UPrice is more than 100, otherwise the discount will be 0.
vi. Increase the price by 12 per cent for all the products manufactured by Dove.
vii. Display the total number of products manufactured by each manufacturer.

(b) Write the output(s) produced by executing the following queries on the basis of the information given
above in the table Product:
i. SELECT PName, Average(UPrice) FROM Product GROUP BY Pname;
ii. SELECT DISTINCT Manufacturer FROM Product;

770945127.docx 14

You might also like