Royal Programming · Learn With Champak

Every SQL Example, Presented as a Problem

Study every distinct example from the six embedded PDFs. Each is presented as a task - such as “Find trains between any two stops” - followed by the exact source data or SQL, expected result, and a detailed explanation.

Every source example is individually presented: No SQL demonstration is hidden inside a combined heading. Every task begins with a problem-style title and is followed by the source data or SQL, the shown or explained result, and a careful walkthrough. No outside dataset, query, name, output, exercise, or quiz has been added.
PDF 1

Tables: Customers, Products, Sales and Sales_Items

The first PDF supplies four related tables for a small sales database.

Example 1Store customer records

Customer NoCustomer NameAddress (Locality)
1PiyushNai Basti
2SunilSigra

Example 2Store product records

Product NoProduct NamePriceNotes
1Pepsi10
2Coca Cola15

Example 3Store sales receipts

Receipt NoDate of SaleCustomer NoNotes
12026-07-061
22026-07-042

Example 4Store the items sold on each receipt

Serial NoReceipt NoProduct NoQuantityPrice
111510
212315
3221515
How the example fits together: Customer No connects Sales to Customers. Receipt No connects Sales_Items to Sales. Product No connects Sales_Items to Products. Thus receipt 1 belongs to Piyush and contains five Pepsi items and three Coca Cola items; receipt 2 belongs to Sunil and contains fifteen Coca Cola items.

SVG: How the four PDF tables are related

Sales database relationshipsCustomers connect to Sales using Customer Number. Sales connects to Sales Items using Receipt Number. Products connects to Sales Items using Product Number.CustomersCustomer NoSalesReceipt No · Customer NoProductsProduct NoSales_ItemsReceipt No · Product NoCustomer NoReceipt NoProduct No
Embedded PDF: Tables
PDF 2

Keys in a Database

The PDF moves from Students to Tickets and then Publications/Subscribers.

Example 1Identify the super key and minimum primary key in Students

RollNoNameAgeCourse
1Himanshu35MBBS
2Himanshu35MBBS
3Ashish15MD

The full rows are unique, but RollNo alone already provides uniqueness. The PDF therefore describes the primary key as the minimum super key.

CREATE TABLE Student(
  RollNo INT PRIMARY KEY,
  Name VARCHAR(50),
  Age INT,
  Course VARCHAR(50)
);

INSERT INTO Student VALUES (1,'Himanshu',35,'MBBS');
INSERT INTO Student VALUES (1,'New Himanshu',34,'MD');
INSERT INTO Student VALUES (NULL,'New Himanshu',34,'MD');

The first insertion succeeds. Reusing RollNo 1 violates uniqueness; using NULL violates the not-null part of the primary key.

Example 2Allow the same roll number in different courses

CREATE TABLE Student(
  RollNo INT,
  Name VARCHAR(50),
  Age INT,
  Course VARCHAR(50),
  PRIMARY KEY(RollNo,Course)
);

The PDF shows RollNo 1 once in MD and once in MBBS. The pair is unique even though RollNo repeats. Another RollNo 1 in MBBS is rejected; NULL in either RollNo or Course is rejected.

Example 3Enforce three candidate keys in Ticket

The PDF identifies three unique choices: TicketNo; PNRNo; and the combination DateofJourney, TrainNo, CoachNo and BerthNo.

CREATE TABLE Ticket(
  TicketNo VARCHAR(50) PRIMARY KEY,
  PNRNo VARCHAR(50) UNIQUE,
  PassengerName VARCHAR(50),
  DateofJourney DATE,
  TrainNo VARCHAR(50),
  CoachNo VARCHAR(50),
  BerthNo INT,
  UNIQUE(DateofJourney,TrainNo,CoachNo,BerthNo)
);

The PDF tests the constraints with Ashish and New Ashish. Repeating TicketNo violates the primary key; repeating PNRNo violates its unique key; repeating the journey/train/coach/berth combination violates the composite unique key. Changing the coach from S1 to S2 allows the row.

Example 4Prevent subscriptions to nonexistent publications

CREATE TABLE Publications(
  PublicationName VARCHAR(100) PRIMARY KEY
);

CREATE TABLE Subscribers(
  PublicationName VARCHAR(100),
  CustomerId VARCHAR(100),
  PRIMARY KEY(PublicationName,CustomerId)
);

The PDF contains publications Yuva Bharati and Vivekananda Kendra Patrika, with Ashish and Manish as subscribers. Without a foreign key, Mahesh can be subscribed to the nonexistent Vivekananda Patrika.

CREATE TABLE Subscribers(
  PublicationName VARCHAR(100)
    REFERENCES Publications(PublicationName),
  CustomerId VARCHAR(100),
  PRIMARY KEY(PublicationName,CustomerId)
);

After the relationship is enforced, inserting or updating a subscriber to Vivekananda Patrika fails because the parent is absent. Updating or deleting Yuva Bharati in Publications fails while Ashish refers to it. Dropping Publications also fails while its primary key is referenced.

SVG: Keys used in the PDF examples

Primary, composite, candidate and foreign key examplesStudentRollNoPrimary keyRollNo + CourseComposite keyTicket candidatesTicketNoPNRNoJourney + Train + Coach + BerthThree unique choicesPublicationsPublicationName: primary keySubscribersPublicationName: foreign key
Embedded PDF: Keys in a Database
PDF 3

Creating, Altering and Dropping Tables

The PDF uses Marks, Sample, Trains and Tickets.

Example 1Create Marks with primary-key, NOT NULL and CHECK constraints

CREATE TABLE Marks(
  RollNo INT PRIMARY KEY,
  Name VARCHAR(100) NOT NULL,
  Phy INT NOT NULL CHECK(Phy>=0 AND Phy<=100),
  Chem INT NOT NULL CHECK(Chem>=0 AND Chem<=100)
);

CREATE TABLE Marks(
  RollNo INT,
  Name VARCHAR(100) NOT NULL,
  Phy INT NOT NULL CHECK(Phy>=0 AND Phy<=100),
  Chem INT NOT NULL CHECK(Chem>=0 AND Chem<=100),
  PRIMARY KEY(RollNo)
);

DESC Marks;

Example 2Compare composite uniqueness with individual uniqueness

CREATE TABLE Sample(F1 INT, F2 INT, PRIMARY KEY(F1,F2));

CREATE TABLE Sample(F1 INT PRIMARY KEY, F2 INT UNIQUE);

In the first form, the F1/F2 combination cannot repeat. In the second, each field is independently unique.

Example 3Add and remove a field from Sample

ALTER TABLE Sample ADD F3 INT;
ALTER TABLE Sample DROP COLUMN F3;

The PDF also demonstrates that a datatype change may fail when the column contains data; after deleting the data, the change succeeds.

Example 4Accept only existing train numbers in Tickets

CREATE TABLE Trains(
  TrainNo INT PRIMARY KEY,
  TrainName VARCHAR(100)
);

CREATE TABLE Tickets(
  TicketNo INT PRIMARY KEY,
  TrainNo INT REFERENCES Trains(TrainNo),
  Passenger VARCHAR(100)
);

The parent table contains TrainNo 1 and 2. A ticket for TrainNo 5 fails because that train does not exist; a ticket for an existing train succeeds. Deleting a train with a child ticket fails, while deleting one with no child record succeeds. The PDF then drops the foreign-key constraint, after which nonexistent train numbers become acceptable.

Embedded PDF: Creating Tables in SQL
PDF 4A

Set Operations and Joins

The PDF uses only Cricketers A/C and Footballers B/C.

SetupCreate and populate the two player tables

CREATE TABLE Cricketers(Name VARCHAR(100) PRIMARY KEY, Runs INT);
CREATE TABLE Footballers(Name VARCHAR(100) PRIMARY KEY, Goals INT);

INSERT INTO Cricketers VALUES('A','100');
INSERT INTO Cricketers VALUES('C','150');
INSERT INTO Footballers VALUES('B','15');
INSERT INTO Footballers VALUES('C','25');

A plays only cricket, B plays only football, and C plays both.

Example 1Find every player without duplicates

SELECT Name FROM Cricketers
UNION
SELECT Name FROM Footballers;
Result: A, B, C.

UNION combines both result sets and removes the repeated C. Use it when membership matters but duplicates do not.

Example 2Find every player and retain duplicates

SELECT Name FROM Cricketers
UNION ALL
SELECT Name FROM Footballers;
Result: A, C, B, C.

UNION ALL appends the second result without duplicate removal. C therefore appears twice because C occurs in both source tables.

Example 3Find players who play both games

SELECT Name FROM Cricketers
INTERSECT
SELECT Name FROM Footballers;
Result: C.

INTERSECT keeps only names common to both sets. C is the only name stored in both tables.

Example 4Find players who play cricket but not football

SELECT Name FROM Cricketers
MINUS
SELECT Name FROM Footballers;
Result: A.

MINUS starts with the cricket names and removes every name also found among footballers.

Example 5Find players who play exactly one game using combined sets

SELECT Name FROM Cricketers
UNION
SELECT Name FROM Footballers
MINUS
(SELECT Name FROM Cricketers INTERSECT SELECT Name FROM Footballers);
Result: A, B.

The union gives all players. The intersection gives C, the player common to both games. Subtracting the intersection leaves those who play exactly one game.

Example 6Find players who play exactly one game using two differences

SELECT Name FROM Cricketers
MINUS
SELECT Name FROM Footballers
UNION
(SELECT Name FROM Footballers MINUS SELECT Name FROM Cricketers);
Result: A, B.

The first difference finds cricket-only A. The second finds football-only B. Their union produces the same answer by a different set expression.

Example 7Produce every possible cricketer-footballer pair

SELECT Cricketers.Name, Footballers.Name
FROM Cricketers, Footballers;
Result: (A,B), (A,C), (C,B), (C,C).

This is a Cartesian product. Each of the two Cricketers rows pairs with each of the two Footballers rows, so 2 × 2 gives four rows.

Example 8Find matching people with an inner join

SELECT * FROM Cricketers C
INNER JOIN Footballers F ON C.Name=F.Name;
Result: C with 150 runs and 25 goals.

An inner join keeps only rows for which the join condition is true in both tables.

Example 9Keep every cricketer with a left join

SELECT * FROM Cricketers C
LEFT JOIN Footballers F ON C.Name=F.Name;
Result: A and C; A has empty football columns.

The left table is preserved. C matches a football row, while A remains even though no football record exists.

Example 10Keep every footballer with a right join

SELECT * FROM Cricketers C
RIGHT JOIN Footballers F ON C.Name=F.Name;
Result: B and C; B has empty cricket columns.

The right table is preserved. C matches a cricket row, while B remains without one.

Example 11Keep every person with a full outer join

SELECT * FROM Cricketers C
FULL OUTER JOIN Footballers F ON C.Name=F.Name;
Result: A, B and C.

A full outer join preserves matches and unmatched rows from both tables. Empty columns identify the game that A or B does not play.

SVG: Set membership in the PDF data

Cricketers and Footballers set diagramA is only a cricketer, B is only a footballer, and C is in both sets.CricketersFootballersACBUNION: A, B, C · INTERSECT: C · Cricket MINUS Football: A
PDF 4B · Detailed case

Trains Between Two Stations

The railway example is reproduced with the schema, three trains, route rows and the exact self-join condition from the PDF.

Example 1Create Trains and Stops

CREATE TABLE Trains(
  TrainNo VARCHAR(10) PRIMARY KEY,
  TrainName VARCHAR(100),
  Source VARCHAR(100),
  Dest VARCHAR(100)
);

CREATE TABLE Stops(
  StopNo INT,
  TrainNo VARCHAR(10) REFERENCES Trains(TrainNo),
  Station VARCHAR(100),
  PRIMARY KEY(StopNo,TrainNo)
);

Example 2Store the three trains

INSERT INTO Trains VALUES(1,'Mahanagari','Varanasi','Mumbai');
INSERT INTO Trains VALUES(2,'Mahanagari','Mumbai','Varanasi');
INSERT INTO Trains VALUES(3,'Ratnagiri','Varanasi','Mumbai');

Example 3Store the stops on the route

INSERT INTO Stops VALUES(1,1,'Varanasi');
INSERT INTO Stops VALUES(2,1,'Jabalpur');
INSERT INTO Stops VALUES(3,1,'Itarsi');
INSERT INTO Stops VALUES(4,1,'Jalgaon');
INSERT INTO Stops VALUES(5,1,'Mumbai');

The PDF then displays the complete Stops table and separately selects each train’s stops in StopNo order:

SELECT * FROM Stops WHERE TrainNo=1 ORDER BY StopNo;
SELECT * FROM Stops WHERE TrainNo=2 ORDER BY StopNo;
SELECT * FROM Stops WHERE TrainNo=3 ORDER BY StopNo;

Example 4Find trains between any two stops

SELECT *
FROM Stops Source
INNER JOIN Stops Dest
  ON Source.TrainNo=Dest.TrainNo
INNER JOIN Trains Train
  ON Source.TrainNo=Train.TrainNo
WHERE Source.Station='Itarsi'
  AND Dest.Station='Jalgaon'
  AND Source.StopNo<Dest.StopNo;
Why it works: Source and Dest are two aliases for Stops. The first join keeps two stop rows belonging to the same train. The second join supplies that train’s details. The WHERE clause requires Itarsi and Jalgaon, while Source.StopNo < Dest.StopNo ensures that the train reaches Itarsi before Jalgaon. The PDF’s result contains two rows.
Use it for any two stops: replace 'Itarsi' with the required boarding stop and 'Jalgaon' with the required destination stop. The table names, joins and stop-order condition remain unchanged.

SVG: How the railway self-join finds a valid direction

Find trains between Itarsi and JalgaonThe Source alias selects Itarsi and the Destination alias selects Jalgaon on the same train. Stop number three is less than stop number four.Stops for Train 1, ordered by StopNo1 Varanasi2 Jabalpur3 Itarsi4 Jalgaon5 MumbaiSource aliasItarsi · StopNo 3Dest aliasJalgaon · StopNo 43 < 4: valid travel direction
Embedded PDF: Intersect, Union, Union All, Minus & Joins
PDF 5

Aggregate Queries in Oracle

Every aggregate example uses the PDF’s Cricket_Scores table.

SetupCreate and populate Cricket_Scores

MAX and MIN work on orderable types; SUM and AVG work on numbers; COUNT counts records.

CREATE TABLE Cricket_Scores(
  Batsman VARCHAR(100),
  InningsNo INT,
  MatchType VARCHAR(10),
  Score INT
);

INSERT INTO Cricket_Scores VALUES('Champak',1,'Test',111);

The complete PDF data has ten rows: Champak scores 111 in Test and 112 and 113 in One Day; Gaurav scores 0 and 10 in One Day; Pappu scores 3, 2, 1, 0 and 0 in One Day.

Example 1Find the highest score

SELECT MAX(Score) FROM Cricket_Scores;
Result: 113.

MAX compares all Score values and returns the greatest.

Example 2Find the lowest score

SELECT MIN(Score) FROM Cricket_Scores;
Result: 0.

MIN returns the least Score value.

Example 3Find the total of all scores

SELECT SUM(Score) FROM Cricket_Scores;
Result: 352.

SUM adds all ten scores.

Example 4Find the average score

SELECT AVG(Score) FROM Cricket_Scores;
Result: 35.2.

AVG divides the total 352 by the ten recorded scores.

Example 5Count the recorded scores

SELECT COUNT(Score) FROM Cricket_Scores;
Result: 10.

COUNT(Score) counts the non-null Score values.

Example 6Try to display a batsman beside an ungrouped maximum

SELECT Batsman, MAX(Score) FROM Cricket_Scores;
Result: the query fails.

The table is reduced to one maximum, but SQL has no rule for choosing a single Batsman value. The non-aggregate column must be grouped.

Example 7Find the maximum score of every batsman

SELECT Batsman, MAX(Score)
FROM Cricket_Scores
GROUP BY Batsman;
Result: Gaurav 10, Pappu 3, Champak 113.

GROUP BY Batsman creates one group per player, and MAX is calculated separately in each group.

Example 8Find complete statistics for every batsman

SELECT Batsman, MAX(Score), MIN(Score), AVG(Score), SUM(Score), COUNT(Score)
FROM Cricket_Scores
GROUP BY Batsman;

Each batsman produces one row containing five summaries: maximum, minimum, average, total and count.

Example 9Find statistics for every batsman and match type

SELECT Batsman, MatchType, MAX(Score), MIN(Score), AVG(Score), SUM(Score), COUNT(Score)
FROM Cricket_Scores
GROUP BY Batsman, MatchType;

Grouping by two columns creates a separate group for every batsman/match-type combination. Champak therefore receives separate Test and One Day summaries.

Example 10Reverse the grouping-column order

SELECT Batsman, MatchType, MAX(Score), MIN(Score), AVG(Score), SUM(Score), COUNT(Score)
FROM Cricket_Scores
GROUP BY MatchType, Batsman;

The same combinations are produced. The PDF notes that column order can affect processing time even when the result does not change.

Example 11Find batsmen whose maximum score is at least 100

SELECT Batsman, MAX(Score)
FROM Cricket_Scores
GROUP BY Batsman
HAVING MAX(Score)>=100;

HAVING filters groups after the maximum has been calculated. It is required because the condition uses an aggregate.

Example 12Find first-innings Test batsmen whose maximum score is at least 100

SELECT Batsman, MAX(Score)
FROM Cricket_Scores
WHERE InningsNo=1 AND MatchType='Test'
GROUP BY Batsman
HAVING MAX(Score)>=100;

WHERE first keeps first-innings Test rows. GROUP BY forms batsman groups, and HAVING then tests each group maximum.

Example 13Find the highest score in Test Matches and One Days

SELECT MatchType, MAX(Score)
FROM Cricket_Scores
GROUP BY MatchType;

One group is created for each MatchType, so the output contains one maximum for Test and one for One Day.

Example 14Find each batsman’s highest first-innings score

SELECT Batsman, InningsNo, MAX(Score)
FROM Cricket_Scores
WHERE InningsNo=1
GROUP BY Batsman, InningsNo;

The row filter keeps innings 1. Grouping by Batsman and InningsNo then returns each player’s first-innings maximum.

Example 15Find the overall highest first-innings score

SELECT InningsNo, MAX(Score)
FROM Cricket_Scores
WHERE InningsNo=1
GROUP BY InningsNo;

Removing Batsman from SELECT and GROUP BY combines all first-innings rows and returns one overall maximum.

Example 16Find the batsman with the highest average

SELECT Batsman, AVG(Score)
FROM Cricket_Scores
GROUP BY Batsman
HAVING AVG(Score) = (
  SELECT MAX(Average)
  FROM (
    SELECT Batsman, AVG(Score) AS Average
    FROM Cricket_Scores
    GROUP BY Batsman
  )
);

The inner grouped query calculates one average per batsman. The next query finds the maximum of those averages. HAVING retains the batsman whose average equals that maximum.

SVG: Aggregate-query processing shown by the PDF examples

Where, Group By, aggregate and Having pipelineCricket_Scoressource rowsWHEREfilter rowsGROUP BYmake groupsMAX / AVGsummariseHAVINGfilter groupsExample: first-innings Test rows → groups by Batsman → MAX(Score) → keep MAX ≥ 100
Embedded PDF: Aggregate Queries in Oracle
PDF 6

Understanding ORDER BY

The final PDF uses the Result table and presents a query containing WHERE, GROUP BY, HAVING and ORDER BY.

Example 1Create Result and insert the three students

CREATE TABLE Result(
  RollNo INT PRIMARY KEY,
  Phy INT,
  Chem INT,
  Maths INT,
  Name VARCHAR(100),
  DOB DATE
);

INSERT INTO Result VALUES(1,40,40,40,'A','1-Jan-2013');
INSERT INTO Result VALUES(2,70,80,39,'B','2-Jan-2013');
INSERT INTO Result VALUES(3,99,98,100,'C','3-Jan-2013');

SELECT * FROM Result;
RollNoPhyChemMathsNameDOB
1404040A01-JAN-13
2708039B02-JAN-13
39998100C03-JAN-13

Example 2Display qualifying Physics results in descending roll-number order

SELECT MAX(Phy), RollNo
FROM Result
WHERE RollNo<=10
GROUP BY RollNo
HAVING AVG(Phy)>40
ORDER BY RollNo DESC;

FROM chooses Result. WHERE admits RollNo values up to 10. GROUP BY makes one group per RollNo. HAVING removes the group whose average Physics mark is not above 40. SELECT returns the maximum Physics mark and RollNo, and ORDER BY displays the remaining RollNo values in descending order.

SVG: Result query, clause by clause

Processing the Result table queryFROMResultWHERERollNo ≤ 10GROUP BYRollNoHAVINGAVG(Phy) > 40SELECTMAX(Phy), RollNoORDER BYRollNo DESCRollNo 1 is removed by HAVING; RollNo 3 and 2 are displayed in descending order.
Embedded PDF: Understanding ORDER BY
Source-based assessment

Multiple-Choice Questions

Every question below is derived from a table, query, result or rule demonstrated in the embedded PDFs.

1. In the sales tables, which field connects Sales_Items to Sales?
2. Why is RollNo sufficient as the primary key in the first Student example?
3. Which combination is a candidate key in the Ticket example?
4. What does the foreign key in Subscribers prevent?
5. What is the result of Cricketers UNION Footballers?
6. Which set operation returns C, the player present in both tables?
7. In the railway self-join, why is Source.StopNo < Dest.StopNo required?
8. What does SELECT MAX(Score) return for Cricket_Scores?
9. Which clause filters groups whose MAX(Score) is at least 100?
10. Why does SELECT Batsman, MAX(Score) fail without GROUP BY?
11. In the Result query, which row is removed by HAVING AVG(Phy)>40?
12. Which order is produced by ORDER BY RollNo DESC after the Result query filters?
Practice from the PDFs

Assignments

Complete these using only the schemas, records and query patterns already taught above.

Assignment 1: Trace the sales relationships

  1. For receipt 1, identify the customer from Customers and Sales.
  2. Use Sales_Items and Products to list both products on that receipt.
  3. Calculate each line value using Quantity × Price and then the receipt total.
  4. Repeat the trace for receipt 2.

Assignment 2: Test Student primary keys

  1. Create the first Student table with RollNo as its primary key.
  2. Run the three INSERT statements shown in the lesson and record which succeeds.
  3. Create the composite-key form using RollNo and Course.
  4. Explain why RollNo 1 may occur once in MD and once in MBBS but not twice in MBBS.

Assignment 3: Test Ticket candidate keys

  1. Create Ticket with TicketNo as primary key and PNRNo as UNIQUE.
  2. Add the composite UNIQUE constraint on DateofJourney, TrainNo, CoachNo and BerthNo.
  3. Using the Ashish/New Ashish tests described in the PDF example, identify which constraint rejects each duplicate.
  4. Explain why changing CoachNo from S1 to S2 makes the complete combination different.

Assignment 4: Enforce the publication relationship

  1. Create Publications and Subscribers first without the foreign key.
  2. Observe why Vivekananda Patrika can incorrectly be used.
  3. Recreate Subscribers with REFERENCES Publications(PublicationName).
  4. Test insertion, parent update, parent deletion and table drop exactly as described in the example.

Assignment 5: Compare constraints on Marks and Sample

  1. Create Marks with its primary key, NOT NULL rules and 0-to-100 checks.
  2. Create Sample once with PRIMARY KEY(F1,F2).
  3. Create Sample again with F1 as PRIMARY KEY and F2 as UNIQUE.
  4. Write a short comparison of combination uniqueness and individual uniqueness.
  5. Add F3 and then drop F3 using the supplied ALTER TABLE statements.

Assignment 6: Work through every A/B/C set

  1. Create and populate Cricketers and Footballers exactly as shown.
  2. Run UNION, UNION ALL, INTERSECT and MINUS.
  3. Predict each result before running it.
  4. Use both supplied methods to find A and B, the players who play exactly one game.
  5. Run the Cartesian product and explain why it has four rows.

Assignment 7: Compare the four joins

  1. Run the INNER JOIN and explain why only C remains.
  2. Run the LEFT JOIN and identify the empty football columns.
  3. Run the RIGHT JOIN and identify the empty cricket columns.
  4. Run the FULL OUTER JOIN and verify that A, B and C are all retained.

Assignment 8: Find trains between two stops

  1. Create Trains and Stops and insert the PDF’s three trains and route rows.
  2. Display each train’s route in StopNo order.
  3. Run the self-join for Itarsi and Jalgaon.
  4. Label the row used by Source and the row used by Dest.
  5. Remove Source.StopNo < Dest.StopNo, compare the result, and explain why the condition is essential.
  6. Substitute another source/destination pair already present in the PDF’s Stops data and retain the same join structure.

Assignment 9: Calculate Cricket_Scores summaries

  1. Run MAX, MIN, SUM, AVG and COUNT separately and verify 113, 0, 352, 35.2 and 10.
  2. Group by Batsman and verify the maximums Gaurav 10, Pappu 3 and Champak 113.
  3. Group by Batsman and MatchType, then reverse those grouping columns and compare the combinations.
  4. Use HAVING to retain batsmen whose maximum is at least 100.

Assignment 10: Follow the complete Result query

  1. Create Result and insert A, B and C exactly as shown.
  2. Write down the rows remaining after WHERE RollNo<=10.
  3. Write down the groups formed by GROUP BY RollNo.
  4. Identify the group removed by HAVING AVG(Phy)>40.
  5. Verify that ORDER BY RollNo DESC produces RollNo 3 followed by RollNo 2.
Assignment answer guide
  1. Receipt 1 belongs to Piyush: Pepsi 5×10 and Coca Cola 3×15, total 95. Receipt 2 belongs to Sunil: Coca Cola 15×15, total 225.
  2. The first Student insert succeeds; duplicate RollNo and NULL RollNo fail. With the composite key, only the RollNo/Course pair must be unique and neither component may be NULL.
  3. Duplicate TicketNo breaks the primary key; duplicate PNRNo breaks UNIQUE; duplicate journey/train/coach/berth breaks the composite UNIQUE constraint; changing S1 to S2 changes that combination.
  4. The foreign key rejects a publication absent from Publications and protects a referenced parent from incompatible update, deletion or drop.
  5. PRIMARY KEY(F1,F2) protects the pair; F1 PRIMARY KEY plus F2 UNIQUE protects each column separately. F3 is added and removed with ALTER TABLE.
  6. UNION: A,B,C; UNION ALL: A,C,B,C; INTERSECT: C; cricket MINUS football: A; exactly one game: A,B; Cartesian product: four pairs.
  7. INNER: C; LEFT: A,C; RIGHT: B,C; FULL OUTER: A,B,C.
  8. The aliases select two rows for the same TrainNo. Itarsi has StopNo 3 and Jalgaon has StopNo 4, so 3<4 confirms the direction. The PDF query returns two rows.
  9. Overall: MAX 113, MIN 0, SUM 352, AVG 35.2, COUNT 10. Per-batsman maximums: Champak 113, Gaurav 10, Pappu 3.
  10. WHERE retains all three supplied rows, HAVING removes RollNo 1 because 40 is not greater than 40, and descending order displays 3 then 2.

Live SQL Premium Editor

Run the examples from the PDFs.
Open full screen