Advanced SQL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Advanced SQL

1. MYSQL Insert

What is INSERT INTO?


The main goal of database systems is to store data in the tables. The data is usually supplied by application
programs that run on top of the database. Towards that end, SQL has the INSERT command that is used to store
data into a table. The INSERT command creates a new row in the table to store data.

Basic syntax
Let's look at the basic syntax of the SQL INSERT command shown below.
INSERT INTO `table_name`(column_1,column_2,...) VALUES (value_1,value_2,...);
HERE

 INSERT INTO `table_name` is the command that tells MySQL server to add new row into a table named
`table_name`.

 (column_1,column_2,...) specifies the columns to be updated in the new row

 VALUES (value_1,value_2,...) specifies the values to be added into the new row

When supplying the data values to be inserted into the new table, the following should be considered while dealing
with different data types.

 String data types - all the string values should be enclosed in single quotes.

 Numeric data types - all numeric values should be supplied directly without enclosing them in single or double
quotes.

 Date data types - enclose date values in single quotes in the format 'YYYY-MM-DD'.
Example:

Suppose that we have the following list of new library members that need to be added into the database.

Date of Physical Postal Contact Email


Full names gender
Birth address address number Address
Leonard
Male Woodcrest 0845738767
Hofstadter
Sheldon Cooper Male Woodcrest 0976736763
Lets' INSERT data one by one. We will start with Leonard Hofstadter. We will treat the contact number as a numeric
data type and not enclose the number in single quotes.
INSERT INTO `members` (`full_names`,`gender`,`physical_address`,`contact_number`) VALUES ('Leonard
Hofstadter','Male','Woodcrest',0845738767);

Executing the script above drops the 0 from Leonard's contact number. This is because the value will be treated as a
numeric value and the zero (0) at the beginning is dropped since it's not significant.
In order to avoid such problems, the value must be enclosed in single quotes as shown below -
INSERT INTO `members` (`full_names`,`gender`,`physical_address`,`contact_number`) VALUES ('Sheldon
Cooper','Male','Woodcrest', '0976736763');
In the case above, zero(0) will not be dropped

Changing the order of the columns has no effect on the INSERT query as long as the correct values have been
mapped to the correct columns.
The query shown below demonstrates the above point.
INSERT INTO `members` (`contact_number`,`gender`,`full_names`,`physical_address`)VALUES
('0938867763','Male','Rajesh Koothrappali','Woodcrest');
The queries above skipped the date of birth column, by default MySQL will insert NULL values in columns that are
skipped in the INSERT query.
Let's now insert the record for Leslie which has the date of birth supplied. The date value should be enclosed in
single quotes using the format 'YYYY-MM-DD'.
INSERT INTO `members` (`full_names`,`date_of_birth`,`gender`,`physical_address`,`contact_number`)
VALUES ('Leslie Winkle','1984-02-14','Male','Woodcrest', '0987636553');

2. MYSQL Delete
What is the DELETE Query?

MySQL DELETE command is used to delete rows that are no longer required from the database tables. It deletes the
whole row from the table and returns count of deleted rows. Delete command comes in handy to delete temporary or
obsolete data from your database.

The Delete query in MySQL can delete more than one row from a table in a single query. This proves to be
advantages when removing large numbers of rows from a database table.

Once a Delete row in MySQL row has been deleted, it cannot be recovered. It is therefore strongly recommended to
make database backups before deleting any data from the database. This can allow you to restore the database and
view the data later on should it be required.

How to Delete a row in MySQL

To delete rows in a MySQL table, use the DELETE FROM statement:


DELETE FROM `table_name` [WHERE condition];
HERE

 DELETE FROM `table_name` tells MySQL server to remove rows from the table ..

 [WHERE condition] is optional and is used to put a filter that restricts the number of rows affected by the
DELETE query.
If the WHERE clause is not used in the DELETE MySQL query, then all the rows in a given table will be deleted.
Example of MySQL Delete Query

Before we go into more details discussion the DELETE command, let's insert some sample data into the movies table
to work with.
INSERT INTO `movies` (`title`, `director`, `year_released`, `category_id`) VALUES ('The Great Dictator',
'Chalie Chaplie', 1920, 7);
INSERT INTO `movies` (`title`, `director`, `category_id`) VALUES ('sample movie', 'Anonymous', 8);

INSERT INTO movies (`title`, `director`, `year_released`, `category_id`) VALUES ('movie 3', 'John Brown',
1920, 8);
Executing the script above adds three (3) movies into the movies table. Before we go any further into our lesson, let's
get all the movies in our table. The script shown below does that.
SELECT * FROM `movies`;

Executing the script above gives us the following results.

movie_id itle director year_released category_id


1 Pirates of the Caribean 4 Rob Marshall 2011 1
2 Forgetting Sarah Marshal Nicholas Stoller 2008 2
3 X-Men NULL 2008 NULL
4 Code Name Black Edgar Jimz 2010 NULL
5 Daddy's Little Girls NULL 2007 8
6 Angels and Demons NULL 2007 6
7 Davinci Code NULL 2007 6
9 Honey mooners John Schultz 2005 8
16 67% Guilty NULL 2012 NULL
18 The Great Dictator Chalie Chaplie 1920 7
19 sample movie Anonymous NULL 8
20 movie 3 John Brown 1920 8

MYSQL Update
What is the UPDATE Query?

UPDATE MySQL command is used to modify rows in a table. The update command can be used to update a single
field or multiple fields at the same time. It can also be used to update a MySQL table with values from another table.

MySQL Update Command Syntax

The basic syntax of the Update query in MySQL is as shown below.


UPDATE `table_name` SET `column_name` = `new_value' [WHERE condition];
HERE

 UPDATE `table_name` is the command that tells MySQL to update the data in a table .

 SET `column_name` = `new_value' are the names and values of the fields to be affected by the update query.
Note, when setting the update values, strings data types must be in single quotes. Numeric values do not need
to be in quotation marks. Date data type must be in single quotes and in the format 'YYYY-MM-DD'.

 [WHERE condition] is optional and can be used to put a filter that restricts the number of rows affected by the
UPDATE MySQL query.
NOT NULL Values
Let's suppose that we want to create a table with certain fields that should always be supplied with values when
inserting new rows in a table. We can use the NOT NULL clause on a given field when creating the table.
The example shown below creates a new table that contains employee's data. The employee number should always
be supplied
CREATE TABLE `employees`(
employee_number int NOT NULL,
full_names varchar(255) ,
gender varchar(6)
);

Let's now try to insert a new record without specifying the employee name and see what happens.
INSERT INTO `employees` (full_names,gender) VALUES ('Steve Jobs', 'Male');
Executing the above script in MySQL workbench gives the following error
-

NULL Keywords
NULL can also be used as a keyword when performing Boolean operations on values that include NULL. The
"IS/NOT" keyword is used in conjunction with the NULL word for such purposes. The basic syntax when null is used
as a keyword is as follows
`comlumn_name' IS NULL
`comlumn_name' NOT NULL

What are JOINS?


Joins help retrieving data from two or more database tables.
The tables are mutually related using primary and foreign keys.
Note: JOIN is the most misunderstood topic amongst SQL leaners. For sake of simplicity and ease of understanding ,
we will be using a new Database to practice sample. As shown below

id first_name last_name movie_id


1 Adam Smith 1
2 Ravi Kumar 2
3 Susan Davidson 5
4 Jenny Adrianna 8
6 Lee Pong 10
id title category
1 ASSASSIN'S CREED: EMBERS Animations
2 Real Steel(2012) Animations
3 Alvin and the Chipmunks Animations
4 The Adventures of Tin Tin Animations

Types of joins
Cross JOIN

Cross JOIN is a simplest form of JOINs which matches each row from one database table to all rows of another.
In other words it gives us combinations of each row of first table with all records in second table.

Suppose we want to get all member records against all the movie records, we can use the script shown below to get
our desired results.

SELECT * FROM `movies` CROSS JOIN `members`


Executing the script above in MySQL workbench gives us the following results.

id title id first_name last_name movie_id


1 ASSASSIN'S CREED: EMBERS Animations 1 Adam Smith 1
1 ASSASSIN'S CREED: EMBERS Animations 2 Ravi Kumar 2
1 ASSASSIN'S CREED: EMBERS Animations 3 Susan Davidson 5
1 ASSASSIN'S CREED: EMBERS Animations 4 Jenny Adrianna 8
1 ASSASSIN'S CREED: EMBERS Animations 6 Lee Pong 10

INNER JOIN
The inner JOIN is used to return rows from both tables that satisfy the given condition.

Suppose you want to get list of members who have rented movies together with titles of movies rented by them. You
can simply use an INNER JOIN for that, which returns rows from both tables that satisfy with given conditions.

SELECT members.`first_name` , members.`last_name` , movies.`title`


FROM members ,movies
WHERE movies.`id` = members.`movie_id`

Executing the script above give

first_name last_name title


Adam Smith ASSASSIN'S CREED: EMBERS
Ravi Kumar Real Steel(2012)
Susan Davidson Safe (2012)
Jenny Adrianna Deadline(2009)
Lee Pong Marley and me
Note the results above script can also be written as follows to achieve the same results.
SELECT A.`first_name` , A.`last_name` , B.`title`
FROM `members`AS A
INNER JOIN `movies` AS B
ON B.`id` = A.`movie_id`

Outer JOINs
MySQL Outer JOINs return all records matching from both tables .

It can detect records having no match in joined table. It returns NULL values for records of joined table if no match is
found.
Sounds Confusing ? Let's look at an example -

LEFT JOIN
Assume now you want to get titles of all movies together with names of members who have rented them. It is clear
that some movies have not being rented by any one. We can simply use LEFT JOIN for the

purpose.

The LEFT JOIN returns all the rows from the table on the left even if no matching rows have been found in the table
on the right. Where no matches have been found in the table on the right, NULL is returned.
SELECT A.`title` , B.`first_name` , B.`last_name`
FROM `movies` AS A
LEFT JOIN `members` AS B
ON B.`movie_id` = A.`id`
Executing the script above in MySQL workbench gives.You can see that in the returned result which is listed below
that for movies which are not rented, member name fields are having NULL values. That means no matching member
found members table for that particular movie.

title first_name last_name


ASSASSIN'S CREED: EMBERS Adam Smith
Real Steel(2012) Ravi Kumar
Safe (2012) Susan Davidson
Deadline(2009) Jenny Adrianna
Marley and me Lee Pong
Alvin and the Chipmunks NULL NULL
The Adventures of Tin Tin NULL NULL
Safe House(2012) NULL NULL
GIA NULL NULL
The Dirty Picture NULL NULL

Note: Null is returned for non-matching rows on right

RIGHT JOIN
RIGHT JOIN is obviously the opposite of LEFT JOIN. The RIGHT JOIN returns all the columns from the table on the
right even if no matching rows have been found in the table on the left where no matches have been found in the
table on the left, NULL is returned.
In our example, let's assume that you need to get names of members and movies rented by them. Now we have a

new member who has not rented any movie yet

SELECT A.`first_name` , A.`last_name`, B.`title`


FROM `members` AS A
RIGHT JOIN `movies` AS B
ON B.`id` = A.`movie_id`

Executing the above script in MySQL workbench gives the following results.

first_name last_name title


Adam Smith ASSASSIN'S CREED: EMBERS
Ravi Kumar Real Steel(2012)
Susan Davidson Safe (2012)
Jenny Adrianna Deadline(2009)
Lee Pong Marley and me
NULL NULL Alvin and the Chipmunks
NULL NULL The Adventures of Tin Tin
NULL NULL Safe House(2012)
NULL NULL GIA
NULL NULL The Dirty Picture
Note: Null is returned for non-matching rows on left

"ON" and "USING" clauses


In JOIN query examples above, we have used ON clause to match the records between table.

USING clause can also be used for the same purpose. The difference with USING is it needs to have identical names
for matched columns in both tables.

In "movies" table so far we used its primary key with the name "id". We referred to same in "members" table with the
name "movie_id".

Let's rename "movies" tables "id" field to have the name "movie_id". We do this in order to have identical matched
field names.
ALTER TABLE `movies` CHANGE `id` `movie_id` INT( 11 ) NOT NULL AUTO_INCREMENT;

Next let's use USING with the LEFT JOIN example above.
SELECT A.`title` , B.`first_name` , B.`last_name`
FROM `movies` AS A
LEFT JOIN `members` AS B
USING ( `movie_id` )

Apart from using ON and USING with JOINs you can use many other MySQL clauses like GROUP BY, WHERE and
even functions like SUM, AVG, etc.

Why should we use joins?


Now you may think, why we use JOINs when we can do the same task running queries. Especially if you have some
experience in database programming you know we can run queries one by one, use output of each in successive
queries. Of course, that is possible. But using JOINs, you can get the work done by using only a one query with any
search parameters. On the other hand MySQL can achieve better performance with JOINs as it can use Indexing.
Simply use of single JOIN query instead running multiple queries do reduce server overhead. Using multiple queries
instead that leads more data transfers between MySQL and applications (software). Further it requires more data
manipulations in application end also.
It is clear that we can achieve better MySQL and application performances by use of JOINs.

1. MYSQL Union

What is a union?
Unions combine the results from multiple SELECT queries into a consolidated result set.

The only requirements for this to work is that the number of columns should be the same from all the SELECT

queries which needs to be combined .


Suppose we have two tables as follows

Let's now create a UNION query to combines both tables using DISTINCT
SELECT column1, column2 FROM `table1`
UNION DISTINCT
SELECT column1,column2 FROM `table2`;

Here duplicate rows are removed and only unique rows are returned.

Note: MySQL uses the DISTINCT clause as default when executing UNION queries if nothing is specified.

Let's now create a UNION query to combines both tables using ALL
SELECT `column1`,` column1` FROM `table1`
UNION ALL
SELECT ` column1`,` column1` FROM `table2`;

Here duplicate rows are included and since we use ALL.

Why use unions


Suppose there is a flaw in your database design and you are using two different tables meant for the same purpose.
You want to consolidate these two tables into one while omitting any duplicate records from creeping into the new
table. You can use UNION in such cases.

This set of Database Multiple Choice Questions & Answers (MCQs) focuses on “Integrity
Constraints”.

1. To include integrity constraint in an existing relation use :


a) Create table
b) Modify table
c) Alter table
d) Drop table
View Answer
Answer: c
Explanation: SYNTAX – alter table table-name add constraint, where constraint can be any
constraint on the relation.
2. Which of the following is not an integrity constraint?
a) Not null
b) Positive
c) Unique
d) Check ‘predicate’
View Answer
Answer: b
Explanation: Positive is a value and not a constraint.
3.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate


Now!
advertisement
CREATE TABLE Employee(Emp_id NUMERIC NOT NULL, Name VARCHAR(20) , dept_name
VARCHAR(20), Salary NUMERIC UNIQUE(Emp_id,Name));
INSERT INTO Employee VALUES(1002, Ross, CSE, 10000)
INSERT INTO Employee VALUES(1006,Ted,Finance, );
INSERT INTO Employee VALUES(1002,Rita,Sales,20000);

What will be the result of the query?


a) All statements executed
b) Error in create statement
c) Error in insert into Employee values(1006,Ted,Finance, );
d) Error in insert into Employee values(1008,Ross,Sales,20000);
View Answer
Answer: d
Explanation: The not null specification prohibits the insertion of a null value for the attribute.
The unique specification says that no two tuples in the relation can be equal on all the listed
attributes.
4.
Check this: RDBMS MCQ | Programming MCQs
CREATE TABLE Manager(ID NUMERIC,Name VARCHAR(20),budget NUMERIC,Details
VARCHAR(30));

Inorder to ensure that the value of budget is non-negative which of the following should be
used?
a) Check(budget>0)
b) Check(budget<0)
c) Alter(budget>0)
d) Alter(budget<0)
View Answer
Answer: a
Explanation: A common use of the check clause is to ensure that attribute values satisfy
specified conditions, in effect creating a powerful type system.
5. Foreign key is the one in which the ________ of one relation is referenced in another
relation.
a) Foreign key
b) Primary key
c) References
d) Check constraint
View Answer
Answer: b
Explanation: The foreign-key declaration specifies that for each course tuple, the
department name specified in the tuple must exist in the department relation.
6.

CREATE TABLE course


( . . .
FOREIGN KEY (dept name) REFERENCES department
. . . );

Which of the following is used to delete the entries in the referenced table when the tuple is
deleted in course table?
a) Delete
b) Delete cascade
c) Set null
d) All of the mentioned
View Answer
Answer: b
Explanation: The delete “cascades” to the course relation, deletes the tuple that refers to
the department that was deleted.
7. Domain constraints, functional dependency and referential integrity are special forms of
_________
a) Foreign key
b) Primary key
c) Assertion
d) Referential constraint
View Answer
Answer: c
Explanation: An assertion is a predicate expressing a condition we wish the database to
always satisfy.
8. Which of the following is the right syntax for the assertion?
a) Create assertion ‘assertion-name’ check ‘predicate’;
b) Create assertion check ‘predicate’ ‘assertion-name’;
c) Create assertions ‘predicates’;
d) All of the mentioned
View Answer
Answer: a
Explanation: None.
9. Data integrity constraints are used to:
a) Control who is allowed access to the data
b) Ensure that duplicate records are not entered into the table
c) Improve the quality of data entered for a specific property (i.e., table column)
d) Prevent users from changing the values stored in the table
View Answer
Answer: c
Explanation: None.
10. Which of the following can be addressed by enforcing a referential integrity constraint?
a) All phone numbers must include the area code
b) Certain fields are required (such as the email address, or phone number) before the
record is accepted
c) Information on the customer must be known before anything can be sold to that customer
d) When entering an order quantity, the user must input a number and not some text (i.e.,
12 rather than ‘a dozen’)
View Answer
Answer: c
Explanation: The information can be referred to and obtained.
This set of SQL Server Multiple Choice Questions & Answers (MCQs) focuses on “Joins”.

1. What type of join is needed when you wish to include rows that do not have matching
values?
a) Equi-join
b) Natural join
c) Outer join
d) All of the Mentioned
View Answer
Answer: c
Explanation:OUTER JOIN is the only join which shows the unmatched rows.
2. What type of join is needed when you wish to return rows that do have matching values?
a) Equi-join
b) Natural join
c) Outer join
d) All of the Mentioned
View Answer
Answer: d
Explanation: Outer join returns the row having matching as well as non matching values.
3. Which of the following is one of the basic approaches for joining tables?
a) Subqueries
b) Union Join
c) Natural join
d) All of the Mentioned
View Answer
Answer: d
Explanation: The SQL subquery is a SELECT query that is embedded in the main SELECT
statement. In many cases, a subquery can be used instead of a JOIN.
Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
4. The following SQL is which type of join: SELECT CUSTOMER_T. CUSTOMER_ID,
ORDER_T. CUSTOMER_ID, NAME, ORDER_ID FROM CUSTOMER_T,ORDER_T
WHERE CUSTOMER_T. CUSTOMER_ID = ORDER_T. CUSTOMER_ID?
a) Equi-join
b) Natural join
c) Outer join
d) Cartesian join
View Answer
Answer: a
Explanation: Equi-join joins only same data entry field. For example, one table contains
department id and another table should contain department id.
5. A UNION query is which of the following?
a) Combines the output from no more than two queries and must include the same number
of columns
b) Combines the output from no more than two queries and does not include the same
number of columns
c) Combines the output from multiple queries and must include the same number of
columns
d) Combines the output from multiple queries and does not include the same number of
columns
View Answer
Answer: c
Explanation: A single UNION can combine only 2 sql query at a time.
Take SQL Server Tests Now!
6. Which of the following statements is true concerning subqueries?
a) Involves the use of an inner and outer query
b) Cannot return the same result as a query that is not a subquery
c) Does not start with the word SELECT
d) All of the mentioned
View Answer
Answer: a
Explanation: Subquery—also referred to as an inner query or inner select—is a SELECT
statement embedded within a data manipulation language (DML) statement or nested within
another subquery.
7. Which of the following is a correlated subquery?
a) Uses the result of an inner query to determine the processing of an outer query
b) Uses the result of an outer query to determine the processing of an inner query
c) Uses the result of an inner query to determine the processing of an inner query
d) Uses the result of an outer query to determine the processing of an outer query
View Answer
Answer: a
Explanation: A ‘correlated subquery’ is a term used for specific types of queries in SQL in
computer databases. It is a subquery (a query nested inside another query) that uses
values from the outer query in its WHERE clause.
8. How many tables may be included with a join?
a) One
b) Two
c) Three
d) All of the Mentioned
View Answer
Answer: d
Explanation: Join can be used for more than one table. For ‘n’ tables the no of join
conditions required are ‘n-1’.
9. The following SQL is which type of join: SELECT CUSTOMER_T. CUSTOMER_ID,
ORDER_T. CUSTOMER_ID, NAME, ORDER_ID FROM CUSTOMER_T,ORDER_T?
a) Equi-join
b) Natural join
c) Outer join
d) Cartesian join
View Answer
Answer: d
Explanation: Cartesian Join is simply the joining of one or more table which returns the
product of all the rows in these tables.
10. Which is not a type of join in T-SQL?
a) Equi-join
b) Natural join
c) Outer join
d) Cartesian join
View Answer
Answer: b
Explanation: A NATURAL JOIN is an inner join where the RDBMS automatically selects the
join columns based on common columns names. Some RDBMS vendors, like Oracle but
not SQL Server, implement a NATURAL JOIN operator.
https://www.sanfoundry.com/sqlserver-mcqs-joins/#:~:text=9.-
,The%20following%20SQL%20is%20which%20type%20of%20join%3A%20SELECT%20CUSTOMER_T,%2C
%20ORDER_ID%20FROM%20CUSTOMER_T%2CORDER_T%3F&text=Explanation%3A%20Cartesian%20Jo
in%20is%20simply,the%20rows%20in%20these%20tables.

You might also like