0% found this document useful (0 votes)
17 views8 pages

SQL INSERT, VIEWS, and JOINs Explained

The document outlines SQL operations including inserting new players, creating views for batsmen and bowlers, and querying player statistics. It also explains different types of SQL JOINs: INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN, with examples of their usage. Additionally, it includes creating and populating tables for students and courses, demonstrating how to retrieve data using various JOIN techniques.

Uploaded by

omdinde123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views8 pages

SQL INSERT, VIEWS, and JOINs Explained

The document outlines SQL operations including inserting new players, creating views for batsmen and bowlers, and querying player statistics. It also explains different types of SQL JOINs: INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN, with examples of their usage. Additionally, it includes creating and populating tables for students and courses, demonstrating how to retrieve data using various JOIN techniques.

Uploaded by

omdinde123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Experiment 4

INSERT, VIEWS & Different Types of SQL JOINs

Q1. Insert new player Michale Clark with player ID 300311 in the table player
mysql> INSERT INTO Player VALUES (300311,'Clark','Michale',NULL,NULL,NULL,NULL);

mysql> SELECT * FROM Player;

Q2. Insert new player Sam from India , Ahemdabad with player ID 406317 in the table
player
mysql> INSERT INTO Player (PlayerID, Bplace, Fname, Country) VALUES (406317, 'Ahemdabad', 'Sam',
'India');

mysql> SELECT * FROM Player;

Q3.
mysql> CREATE VIEW Batsman (PID,FName,LName,Country,MID,Score)
AS SELECT PlayerID,FName,LName,Country,MatchID,NRuns
FROM Player,Batting
WHERE PlayerID=PID;

mysql> describe Batsman;


+---------+-------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------------+------+-----+---------+-------+
| PID | int unsigned | NO | | NULL | |
| FName | varchar(15) | YES | | NULL | |
| LName | varchar(15) | YES | | NULL | |
| Country | varchar(25) | YES | | NULL | |
| MID | int unsigned | YES | | NULL | |
| Score | smallint unsigned | YES | | NULL | |
+---------+-------------------+------+-----+---------+-------+
6 rows in set (0.01 sec)

mysql> select * from Batsman;

+-------+-----------+-------------+-----------+------+-------+
| PID | FName | LName | Country | MID | Score |
+-------+-----------+-------------+-----------+------+-------+
| 23001 | Yuvraj | Singh | India | 2755 | 0 |
| 23001 | Yuvraj | Singh | India | 2689 | 38 |
| 24001 | Andrew | Symonds | Australia | 2689 | 42 |
| 25001 | MS | Dhoni | India | 2755 | 71 |
| 25001 | MS | Dhoni | India | 2689 | 36 |
| 27001 | Praveen | Kumar | India | 2689 | 7 |
| 27001 | Praveen | Kumar | India | 2755 | 2 |
| 89001 | Sachin | Tendulkar | India | 2689 | 91 |
| 91001 | Sanath | Jayasuriya | Sri Lanka | 2755 | 60 |
| 92002 | Muthiah | Murlitharan | Sri Lanka | 2755 | 1 |
| 94002 | Chaminda | Vaas | Sri Lanka | 2755 | 17 |
| 95001 | Ricky | Ponting | Australia | 2689 | 1 |
| 98002 | Harbhajan | Singh | India | 2689 | 3 |
| 98002 | Harbhajan | Singh | India | 2755 | 2 |
| 99001 | Breet | Lee | Australia | 2689 | 7 |
| 99002 | Adam | Gilchrist | Australia | 2689 | 2 |
+-------+-----------+-------------+-----------+------+-------+
16 rows in set (0.01 sec)
Q4.
mysql> CREATE VIEW Bowling2689 (PID,FName,LName,Country,NOvers,NWickets)
AS SELECT PlayerID,FName,LName,Country,NOvers,NWickets
FROM Player,Bowling
WHERE PlayerID=PID
AND MatchID=2689;

mysql> describe Bowling2689;


+----------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+-------+
| PID | int unsigned | NO | | NULL | |
| FName | varchar(15) | YES | | NULL | |
| LName | varchar(15) | YES | | NULL | |
| Country | varchar(25) | YES | | NULL | |
| NOvers | tinyint unsigned | YES | | NULL | |
| NWickets | tinyint unsigned | YES | | NULL | |
+----------+------------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

mysql> select * from Bowling2689;


+-------+-----------+---------+-----------+--------+----------+
| PID | FName | LName | Country | NOvers | NWickets |
+-------+-----------+---------+-----------+--------+----------+
| 99001 | Breet | Lee | Australia | 10 | 1 |
| 24001 | Andrew | Symonds | Australia | 3 | 1 |
| 23001 | Yuvraj | Singh | India | 3 | 0 |
| 98002 | Harbhajan | Singh | India | 10 | 1 |
+-------+-----------+---------+-----------+--------+----------+
4 rows in set (0.02 sec)

Q5. Find name of all players who have scored 60 or more runs.
Using view Batsman
mysql> SELECT FName, LName FROM Batsman WHERE Score >= 60;
+--------+------------+
| FName | LName |
+--------+------------+
| MS | Dhoni |
| Sanath | Jayasuriya |
| Sachin | Tendulkar |
+--------+------------+
3 rows in set (0.01 sec)
Without using view
mysql> SELECT FName, LName FROM Player,Batting WHERE PlayerID=PID AND NRuns>=60;
+--------+------------+
| FName | LName |
+--------+------------+
| MS | Dhoni |
| Sanath | Jayasuriya |
| Sachin | Tendulkar |
+--------+------------+
3 rows in set (0.00 sec)
Q6. Find the names of bowlers that have not taken any wickets in ODI match 2689
Using view Bowling2689

mysql> SELECT FName, LName FROM Bowling2689 WHERE NWickets=0;


+--------+-------+
| FName | LName |
+--------+-------+
| Yuvraj | Singh |
+--------+-------+
1 row in set (0.00 sec)

Without using view


mysql> SELECT FName, LName FROM Player,Bowling WHERE PlayerID=PID AND
MatchID=2689 AND NWickets=0;
+--------+-------+
| FName | LName |
+--------+-------+
| Yuvraj | Singh |
+--------+-------+
1 row in set (0.00 sec)

Q7. Define a view NPlayer for obtaining the names of the countries & number of
players from each country.

mysql> CREATE VIEW NPlayer (Country, C)


AS SELECT Country, COUNT(*)
FROM Player
GROUP BY Country;

mysql> SELECT Country, COUNT(*) AS C


FROM Player
GROUP BY Country
HAVING COUNT(*)=
(SELECT MAX(C) FROM NPlayer);

+---------+----+
| Country | C |
+---------+----+
| India | 11 |
+---------+----+
1 row in set (0.00 sec)

Display all tables and views.


mysql> SHOW FULL TABLES;
Create New Database for SQL JOINs
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:

(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table

CREATE TABLE Student (


Roll_No SMALLINT UNSIGNED,
Name varchar (20),
Address varchar (100),
Phone char(13),
Age TINYINT UNSIGNED);

insert into Student (Roll_No, Name, Address, Phone,Age) values (1,'Harsh','Delhi', '+919999999990', 18);
insert into Student (Roll_No, Name, Address, Phone,Age) values (2,'Pratik','Mumbai', '+919999999991', 19);
insert into Student values (3,'Priyanka','Pune', '+919999999992', 20),
(4,'Deep','Ahemdabad', '+919999999993', 18),
(5,'Sagar','Bhopal', '+919999999994', 19),
(6,'Raj','Haydrabad', '+919999999995', 20),
(7,'Rohit','Banglore', '+919999999996', 18),
(8,'Niraj','Nasik', '+919999999997', 19);

mysql> select * from Student;


+---------+----------+-----------+---------------+------+
| Roll_No | Name | Address | Phone | Age |
+---------+----------+-----------+---------------+------+
| 1 | Harsh | Delhi | +919999999990 | 18 |
| 2 | Pratik | Mumbai | +919999999991 | 19 |
| 3 | Priyanka | Pune | +919999999992 | 20 |
| 4 | Deep | Ahemdabad | +919999999993 | 18 |
| 5 | Sagar | Bhopal | +919999999994 | 19 |
| 6 | Raj | Haydrabad | +919999999995 | 20 |
| 7 | Rohit | Banglore | +919999999996 | 18 |
| 8 | Niraj | Nasik | +919999999997 | 19 |
+---------+----------+-----------+---------------+------+
8 rows in set (0.00 sec)

CREATE TABLE Course (


Course_ID SMALLINT UNSIGNED,
Roll_No SMALLINT UNSIGNED);

insert into Course(Course_Id,Roll_No) values (1,1);


insert into Course(Course_Id,Roll_No) values (2,2);
insert into Course values (2,3),(3,4),(1,5),(4,9),(5,10),(4,11);

mysql> select * from Course;


+-----------+---------+
| Course_ID | Roll_No |
+-----------+---------+
| 1 | 1 |
| 2 | 2 |
| 2 | 3 |
| 3 | 4 |
| 1 | 5 |
| 4 | 9 |
| 5 | 10 |
| 4 | 11 |
+-----------+---------+
8 rows in set (0.00 sec)
INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as
long as the condition satisfies. This keyword will create the result-set by
combining all rows from both the tables where the condition satisfies i.e value
of the common field will be same.
Syntax:
SELECT tableA.column1,table1.column2,tableB.column1,....
FROM tableA
INNER JOIN tableB
ON tableA.matching_column = tableB.matching_column;

tableA: First table.

tableB: Second table

matching_column: Select all records from Table A and Table B,

where the join condition is met.

Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER
JOIN.

mysql> SELECT Course.Course_ID, [Link], [Link] FROM Student INNER


JOIN Course ON Student.Roll_NO = Course.Roll_NO;

+-----------+----------+------+
| Course_ID | Name | Age |
+-----------+----------+------+
| 1 | Harsh | 18 |
| 2 | Pratik | 19 |
| 2 | Priyanka | 20 |
| 3 | Deep | 18 |
| 1 | Sagar | 19 |
+-----------+----------+------+
5 rows in set (0.00 sec)
LEFT JOIN: This join returns all the rows of the table on the left side of the join
and matching rows for the table on the right side of join. The rows for which
there is no matching row on right side, the result-set will contain null. LEFT JOIN
is also known as LEFT OUTER JOIN.

Syntax:
SELECT tableA.column1,table1.column2,tableB.column1,....
FROM tableA
LEFT JOIN tableB
ON tableA.matching_column = tableB.matching_column;

tableA: First table.

tableB: Second table


matching_column: Select all records from Table A, along with
records from Table B for which the join condition is met (if at all).

Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are same.

mysql> SELECT [Link],Course.Course_ID FROM Student LEFT JOIN Course ON


Course.Roll_No = Student.Roll_No;

+----------+-----------+
| Name | Course_ID |
+----------+-----------+
| Harsh | 1 |
| Pratik | 2 |
| Priyanka | 2 |
| Deep | 3 |
| Sagar | 1 |
| Raj | NULL |
| Rohit | NULL |
| Niraj | NULL |
+----------+-----------+
8 rows in set (0.00 sec)
RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of
the table on the right side of the join and matching rows for the table on the
left side of join. The rows for which there is no matching row on left side, the
result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.

Syntax:
SELECT tableA.column1,table1.column2,tableB.column1,....
FROM tableA
RIGHT JOIN tableB
ON tableA.matching_column = tableB.matching_column;

tableA: First table.

tableB: Second table

matching_column: Select all records from Table B, along with records from
Table A for which the join condition is met (if at all).

Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are
same.

mysql> SELECT [Link],Course.Course_ID FROM Student RIGHT JOIN Course ON


Course.Roll_No = Student.Roll_No;

+----------+-----------+
| Name | Course_ID |
+----------+-----------+
| Harsh | 1 |
| Pratik | 2 |
| Priyanka | 2 |
| Deep | 3 |
| Sagar | 1 |
| NULL | 4 |
| NULL | 5 |
| NULL | 4 |
+----------+-----------+
8 rows in set (0.00 sec)
FULL JOIN: FULL JOIN creates the result-set by combining result of both LEFT JOIN
and RIGHT JOIN. The result-set will contain all the rows from both the tables. The rows
for which there is no matching, the result-set will contain NULL values.
Syntax:
SELECT tableA.column1,table1.column2,tableB.column1,....
FROM tableA FULL JOIN tableB
ON tableA.matching_column = tableB.matching_column;

tableA: First table.

tableB: Second table

matching_column: Select all records from Table A and Table B, regardless


of whether the join condition is met or not.

SELECT [Link],Course.Course_ID FROM Course FULL JOIN Student ON


Course.Roll_No = Student.Roll_No;

Note: If your Database does not support FULL JOIN (MySQL does not support
FULL JOIN), then you can use UNION ALL clause to combine these two JOINS as
shown below.
mysql> SELECT [Link],Course.Course_ID FROM Student RIGHT JOIN Course ON
Course.Roll_No = Student.Roll_No
UNION
SELECT [Link],Course.Course_ID FROM Student LEFT JOIN Course ON
Course.Roll_No = Student.Roll_No;
+----------+-----------+
| Name | Course_ID |
+----------+-----------+
| Harsh | 1 |
| Pratik | 2 |
| Priyanka | 2 |
| Deep | 3 |
| Sagar | 1 |
| NULL | 4 |
| NULL | 5 |
| Raj | NULL |
| Rohit | NULL |
| Niraj | NULL |
+----------+-----------+
10 rows in set (0.00 sec)

Common questions

Powered by AI

Different join types on the Course and Student tables reveal various aspects of data integrity and representational completeness. An INNER JOIN ensures that only records with a match in both tables appear in the result, maintaining referential integrity for students actively enrolled in courses. This omits students without courses, thus retaining only complete representational records . In contrast, using LEFT JOIN or RIGHT JOIN exposes the existence of unmatched records, as seen where certain Students have NULL Course_IDs or vice versa, indicating data gaps such as students not enrolled in any course or courses without enrolled students, highlighting issues with data completeness. FULL JOIN, simulated via UNION in MySQL, underscores potential mismatches and ensures a comprehensive view of all records, thus useful in integrity checks by revealing orphaned records in either table .

Using VIEWS in SQL provides an abstraction layer that simplifies complex queries into a single reference point. This can enhance performance in some contexts, as VIEWS predefine the join and selection logic, potentially optimizing query execution times for frequent accesses. However, VIEWS do not store data themselves; they are stored as SELECT statements. This means any performance gains are primarily at the query planning stage unless the RDBMS supports materialized views, which precompute and store the actual data. For frequently queried datasets, VIEWS can significantly reduce query complexity and improve code maintainability, while their impact on storage is negligible since they occupy minimal space aside from query definitions themselves .

In SQL, LEFT JOIN returns all records from the left table (Student) and the matched records from the right table (Course). If there are no matching records in the right table, the result set will contain NULL values for columns from the right table. For example, a LEFT JOIN between the Student and Course tables would return all Student entries, including those without a corresponding entry in Course, where Course_ID would be NULL for Raj, Rohit, and Niraj . RIGHT JOIN, on the other hand, returns all records from the right table (Course) and matched records from the left table (Student), with NULLs for left table columns where there is no match. In the case of Course RIGHT JOIN Student, entries with Course_ID 4 and 5 in Course that have no matching Roll_No in Student would have NULLs for the Student fields in the result .

A scenario where a view simplifies a complex query involves analyzing player performance, where one might want to see a player's bowling and batting statistics together. Without a view, the query would require multiple joins and subqueries to aggregate data from different tables concerning player performances in matches. For example, to obtain player names and their scores, as well as bowling statistics for match 2689, it would need to join the Player, Batting, and Bowling tables in a composite query. With a view like Batsman or Bowling2689, these complexities are abstracted into predefined views, allowing the user to query them directly, like SELECT * FROM Batsman WHERE MID = 2689 AND Score > 30. This reduces complexity by providing a standardized representation of commonly accessed data .

To determine which country has the maximum number of players, we can create a view that aggregates players by country and then select the country with the maximum count. Based on the document, the query first creates a view NPlayer that counts players per country: CREATE VIEW NPlayer (Country, C) AS SELECT Country, COUNT(*) FROM Player GROUP BY Country. To find the country with the maximum players, we query: SELECT Country, COUNT(*) AS C FROM Player GROUP BY Country HAVING COUNT(*) = (SELECT MAX(C) FROM NPlayer). This query explicitly uses the previously defined view to identify 'India' with 11 players as the country with the maximum count .

To determine which students are taking multiple courses, perform a query that groups course records by the student identifier (Roll_No) and counts these groups. The SQL would be: SELECT Student.Name, COUNT(Course.Course_ID) AS CourseCount FROM Student INNER JOIN Course ON Student.Roll_No = Course.Roll_No GROUP BY Student.Roll_No HAVING CourseCount > 1. This query leverages INNER JOIN to align students to their courses, grouping by Roll_No, and uses COUNT to determine the number of courses per student. The HAVING clause filters out students with only single enrollments, thus identifying those involved in multiple courses .

To simulate a FULL JOIN in MySQL, which does not support it natively, you can use a combination of LEFT JOIN and RIGHT JOIN with a UNION ALL clause. This method involves executing a LEFT JOIN to get all records from the left table and matched entries from the right table, and a RIGHT JOIN to get all records from the right table and matched entries from the left table. These results are combined using UNION ALL, which merges the two result sets. If deduplication is necessary, UNION could be used instead of UNION ALL, but at the cost of additional processing to eliminate duplicates. The SQL statement would look like this: SELECT fields FROM left_table LEFT JOIN right_table ON condition UNION SELECT fields FROM left_table RIGHT JOIN right_table ON condition .

To find players who participated in match 2689 but did not score any runs using the Batsman view, the query should select entries from Batsman where MID is 2689 and Score is 0. However, since in the available data of the Batsman view, no player's Score is listed as 0 for match 2689 directly, the query highlighting players with no runs specifically might not retrieve results unless records in Batsman with MID 2689 exist with Score 0. An example of such a query, hypothetically expecting the dataset to include relevant zeros, could be: SELECT FName, LName FROM Batsman WHERE MID = 2689 AND Score = 0 .

To list all students without course enrollments using a LEFT JOIN, you would execute a query that selects student fields and joins the Course table, ensuring the result shows NULL for Course_ID where no match is found. The query would be: SELECT Student.Name, Course.Course_ID FROM Student LEFT JOIN Course ON Student.Roll_No = Course.Roll_No WHERE Course.Course_ID IS NULL. This query illustrates how LEFT JOIN operations retain all records from the left table (Student), and for those entries without corresponding matches in the right table (Course), the resultant table fills in NULL for unmatched right table columns, thereby effectively highlighting students without enrollments .

The SQL INSERT statement can be used with different syntaxes to add new records to a table, affecting how column values are assigned. When all columns are included implicitly, as in INSERT INTO Player VALUES (...), the order of values must exactly match the column order in the table schema. Missing values are typically handled by default settings or NULLs . Conversely, specifying columns with INSERT INTO Player (column1, column2, ...) VALUES (...) allows for more flexibility by explicitly defining which columns are receiving values. This can be preferable to handle tables with nullable fields or to insert data selectively without needing all field entries, as seen when Sam is inserted using only a subset of Player table columns .

You might also like