0% found this document useful (0 votes)
39 views18 pages

Relatively Easy Questions

1. The document provides a series of exercises to create SQL queries and functions to practice different SQL skills. The exercises include creating error handling for temp tables, functions to return dates and tables, stored procedures, views, joins, cursors and more. 2. The exercises are meant to be completed using sample databases that contain tables of historical events, websites, training courses, and other data. Detailed instructions are provided for each exercise. 3. The goal is to gain experience with a wide range of SQL features and techniques by working through the guided exercises on the sample databases. Feedback is provided for most exercises to help check the results.

Uploaded by

gk.mobm33
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)
39 views18 pages

Relatively Easy Questions

1. The document provides a series of exercises to create SQL queries and functions to practice different SQL skills. The exercises include creating error handling for temp tables, functions to return dates and tables, stored procedures, views, joins, cursors and more. 2. The exercises are meant to be completed using sample databases that contain tables of historical events, websites, training courses, and other data. Detailed instructions are provided for each exercise. 3. The goal is to gain experience with a wide range of SQL features and techniques by working through the guided exercises on the sample databases. Feedback is provided for most exercises to help check the results.

Uploaded by

gk.mobm33
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
You are on page 1/ 18

Relatively Easy Questions

Error trap when creating temp table


If you haven't already done so, run the stored procedure in the above folder to generate
a database of training courses and delegates.

1. Create a query to show all the people with really long names - similar to the
following - and run it twice:

You should find that this displays only 3 people

When you run your query a second time, it should crash because the temporary
table #BigPeople already exists. Apply error trapping at the top of the query such that:

 Your query attempts to delete the table


 If it already exists, the table is deleted and your query prints out a message
saying that this has happened
 If it didn't already exist, you get a message saying that nothing was deleted

You can test out that this final possibility works by adding the following command at the
end of your query:
This command would ensure that the table didn't exist the next time that you run the query

Optionally, save this query as Check deleting temp table.sql, then close it down.

Function to return weekday

2. Create a function (called fnWeekDay?) to show the day of the week for any
given date.

Use your function to show the number of events for each day of the week:

Thursdays are the busiest day in world history ...

Save and close your queries!

Inline table fn to show courses between 2 dates


If you haven't already done so, run the stored procedure in the above folder to generate
a database of training courses and delegates.

This exercise uses columns from the following two tables:


We will use the StartDate column to filter the rows returned

3. Create a function called fnTableCourses to return a table of all of the courses


which start and finish between two specified dates, such that the following query
works:

The function takes 2 arguments of datetime format

The command above should return 6 rows:

The 6 rows which start and finish in January 2010

Optionally, save this query as Courses between dates.sql, then close it down.

List events with most recent first


If you haven't already got it set up in SQL server, restore the Historical
Events database from the above folder.

4. Create a query to list out the following columns from the tblEvent table:

 EventName
 EventDate

Your rows should appear in date order, with the most recent event coming first.
The last event in our database was on 14th November 2007

Make sure you've included comments in your query, and indented it sensibly

Save this query as Listing events in reverse date order, then close it down.

Listing countries with continents


USE the Historical Events database

5. Create a query using an inner join and table aliases to list out the non-European
countries.

Your final result should look like this:

Your query should link the tblCountry and tblContinent tables

Save this query as Countries, and close it down.


Number of events for each country
USE Historical Events database

6. Create a query to show the number of events for each country (with the most
"eventful" country coming at the top of the list):

Proving that the UK is the most interesting place to live?

Save your query as Countries by event.sql, then close it down.

Parameters - show websites for given category


USE database of websites. This exercise uses the following two tables:

Each website belongs to a category

7. Create a stored procedure called spWebsitesByCategory which takes a single


parameter - the name of a category - and displays all of the websites which
belong to that category. For example:
You could execute your stored procedure to show all of the websites in the search engine category,
for example

The above example would show the following output:

The start of the list of search engine websites

Optionally, save the query to generate your stored procedure as Websites for chosen
category.sql, then close it down.

Retail orgs or orgs with lots of people


USE database of training courses and delegates.

8. We want to create a query which shows all companies which either are in the
retail sector or which have more than 12 people working there. To do this, first
select all of the companies in the retail sector (there are only 2) into a new
temporary table called #Org:

This is what you should have so far

Now add code to insert all companies employing more than 12 people into the same
table (you could use a subquery to do this):
Select all of the records from the temporary table that you've compiled. The final
answer should look like this:

Primark and Kingfisher PLC qualify as being part of the retail sector

Optionally, save this query as Retail or big orgs.sql, then close it down.

Script view showing 2000 events


9. Create a new query, and within this create a view called vwSingleYear to show all
those events occurring in 2000.

Execute this query, then right-click on your Views to refresh them. You should now see
your new view!

Run this view - it should show 8 events:

In no particular order ...

Right-click on the view to modify its design, and use the View Design window to change
the criteria so that you show the events in 2001 instead (there should be 7 of them).

Close the view down, saving your changes.


Show end date for given course
10. USE database of training courses and delegates. This exercise refers to
columns from the following two tables:

Each course product can have lots of instances of the course scheduled

Create a function called fnEndDate which takes in:

 The start date of a course; and


 The number of days it lasts

Your function should then return the end date of the course.

Use the DateAdd function to work out the end date: the syntax is DateAdd ( day, Number of days to
add, Start date) .

Incorporate your function within a query to show the start and end dates of all courses
which start and end within January 2010:

You should see six courses

Optionally, save this query as Course end date function.sql, then close it down.
Show length of event descriptions using LEN
USE Historical Events database.
11. Create a query to show the name of each event, together with the length
of its description, sorted so that the longest description appears first:

Why there was most to say about the founding of the UN, owl only knows

Save this query as Showing length of description, then close it down.

Show years elapsed for each event


USE Historical Events database.

12. Create the following query, using:

 CONVERT to convert the date of each event to a more readable format; and
 DATEDIFF to show the difference between each event's date and today in years

Your final output should look like this (sorted in reverse date order):

The DateDiff syntax is: DateDiff(year,EarlierDate,LaterDate)

Save this query as Am I really that old, then close it down.


Showing all continents with no countries
USE Historical Events database .

13. Use a left outer join to show all of the continents with no matching
countries:

The result of running your query

Save this query as Unpopulated continents, then close it down.

If you have time (and energy), repeat this trick to show that Latvia and Uruguay are the
only countries with no corresponding events.

Showing events for a country in a given year


USE Historical Events database .
14. Create a query listing out the event date and event name for all German
events (ie for all events where the CountryId equals 7):

There are 6 events in our database which took place in Germany

Now amend your WHERE clause so that you only see events which took place in
Germany in the 1940s (ie where the EventDate column lies between 1st January 1940
and 31st December 1949):

This should take you down to just these 2 events

Save this query as German events in 40s.sql, and close it down.


Simple cursor exercise - print trainer details
15. If you haven't already done so, run the stored procedure in the above
folder to generate a database of training courses and delegates. This
exercise deals solely with the tblTrainer table:

I'm sure those names seem familiar ...

Write a query which uses a cursor to step through the trainers one by one
in alphabetical order, printing out the details for each:

What the output from your query might look like

This exercise is a good example of when NOT to use a cursor!

Optionally, save this query as List trainers.sql, then close it down.

Simple join view of events, then script change


16. First choose to create a view in the HistoricalEvents database:
You can right-click to create a new view

Design a view to show all of the events occurring in Africa, in date order. As a clue,
here is what the top half of the view designer should look like:

You'll need to include these 3 tables

Run your view - it should return 3 events only:

Not much happens in Africa? Or more likely, the database is hopelessly biased

Save this view as vwAfrica, then close it down.

Right-click on the view to script it to a new window.

Change the script in two ways:

 Firstly, so that it creates a new view called vwAfricaAsia, rather than altering the
existing one; and
 Secondly, so that it shows the events in Africa or Asia

Run this script, then close down its window.


Refresh your list of views, and run your new vwAfricaAsia view to show that it returns
23 events.

Simple stored procedure showing top 10 websites


17. If you haven't already done so, run the stored procedure in the above
folder to generate a database of the world's leading websites. This
database contains a table of websites called tblWebsite:

Rankings are from Alexa, a company which analyses the popularity of websites

Create a query which lists out the top 10 websites in the UK (ie ordered
by AlexaRankUk, where the AlexaRankUk column is not null):

Don't forget to use the UK Alexa ranking when ordering

Now create a stored procedure from this query called spListTopWebsites. Execute
your stored procedure to check that it gives the same answer.
Alter your stored procedure (change the word CREATE to ALTER) so that it lists out the
top 5 websites, not the top 10.

Optionally, save the code to generate the stored procedure as spListTopWebsites.sql,


then close it down.

Stored procedure to show events between 2 dates


18. Create a stored procedure called spEventsBetweenDates, to list all of
the events between two given dates.

Create a query to run this stored procedure, using the example of 1970:

List the arguments after the name of the stored procedure

This is what this query should show:

1970 was a busy year!

Save and close all of your queries.

Subquery using historical events


USE Historical Events database.

19. Create a query/subquery showing all of the events which happened after
the last European Unionevent (or if you prefer, which happened after any
of the European Union events). Here's what your results should look like:
Only 7 events have happened since the last EU event

Save this query as Events after EU, and close it down.

Table variable - C# and Gabriella courses


USE the database of training courses and delegates.

20. The aim of this exercise is to create a table variable holding all of those
course ids where the course is either:

 About C#; or
 Given by Gabriella Montez (the techiest trainer).

To do this, first declare a table variable called @TechieCourses to hold one column
only - each course's ScheduleId.

Insert into this table all of those courses which have C# in the course name:

These are the two tables you will need to join

Now insert into the same table all those courses where the TrainerIds column contains
number 2936(that's Gabriella). To do this, add a comma to the start and end of each of
the things you're comparing:
What your WHERE condition might look like

Create a SELECT statement joining your temporary table to the table of courses to
show your results in course date order:

The first of the 72 rows your query should return

Optionally, save this query as Techie courses.sql, then close it down.

Turning null continent ids into values


USE Historical Events database.

21. Create a query to show a list of the countries in the tblCountry table in
reverse alphabetical order. Where a country has no continent id, replace
this with 0:

Listed in reverse alphabetical order, the World appears first

Save this query as Denullification, and close it down.

Use CTE to list important people courses


22. If you haven't already done so, run the stored procedure in the above
folder to generate a database of training courses and delegates.

Here are the tables that you will need to do the first part of this exercise:
Initially we only need to show the people having a delegate count of 6 or more

Create a query to show the ids of the people who have attended 6 or more courses:

There are only 3 people

Now turn this into a longer query to show the course names that these people have
attended, using a CTE (common table expression) (you'll need to join your CTE to
the tblDelegate, tblSchedule and tblCourse tables to accomplish this):

The first few of the 18 rows your query should return

Optionally, save this query as Important people courses, then close it down.

Write a simple query to list the Doctors


USE Doctor Who training database.

23. Write out a SELECT statement to list out the names from tblDoctor in
date of birth order.

Use the ORDER BY clause to set the sort order of your results.
Your results should look something like this:

The first few of the 12 Doctors.

Optionally save your query as List of Doctors.sql, then close it down.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy