Professional Documents
Culture Documents
Ch 01 - Querying and SQL leip101 - Codes only
Ch 01 - Querying and SQL leip101 - Codes only
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/
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;
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 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);
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;
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;
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;
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;
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;
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.
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