• SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database

SQL Exercises

  • SQL Concepts and Queries
  • SQL Inner Join
  • SQL - SELECT LAST
  • SQL for Data Science
  • Comparison Operators in SQL
  • SQL Query Interview Questions
  • 7 Best Books for SQL
  • SAP Labs Interview Experience
  • Oracle Interview Experience
  • Shell India Interview Experience
  • DE Shaw Interview Experience
  • TCS NQT Interview Experience
  • Sapient Interview Experience | Set 4
  • Spring Works Interview Experience
  • TCS Ninja Interview Experience
  • Infosys InfyTQ Interview Experience
  • SAP Labs Interview Experience | Set 7

SQL ( Structured Query Language ) is a powerful tool used for managing and manipulating relational databases. Whether we are beginners or experienced professionals, practicing SQL exercises is essential for our skills and language mastery.

In this article, we’ll cover a series of SQL practice exercises covering a wide range of topics suitable for beginners , intermediate , and advanced learners. These exercises are designed to provide hands-on experience with common SQL tasks, from basic retrieval and filtering to more advanced concepts like joins window functions , and stored procedures.

List of SQL Exercises

  • SQL Questions for Practice

SQL Practice Exercises for Beginners

Sql practice exercises for intermediate, sql practice exercises for advanced, more questions for practice, sql exercises for practice.

Practice SQL questions to enhance our skills in database querying and manipulation. Each question covers a different aspect of SQL , providing a comprehensive learning experience.

SQL-Practice-Questions-with-Sollutions

We have covered a wide range of topics in the sections beginner , intermediate and advanced .

  • Basic Retrieval
  • Arithmetic Operations and Comparisons:
  • Aggregation Functions
  • Group By and Having
  • Window Functions
  • Conditional Statements
  • DateTime Operations
  • Creating and Aliasing
  • Constraints
  • Stored Procedures:
  • Transactions

let’s create the table schemas and insert some sample data into them.

Create Sales table

sales_table

Create Products table

Product_Table

This hands-on approach provides a practical environment for beginners to experiment with various SQL commands, gaining confidence through real-world scenarios. By working through these exercises, newcomers can solidify their understanding of fundamental concepts like data retrieval, filtering, and manipulation, laying a strong foundation for their SQL journey.

1. Retrieve all columns from the Sales table.

Explanation: This SQL query selects all columns from the Sales table, denoted by the asterisk (*) wildcard. It retrieves every row and all associated columns from the Sales table.

2. Retrieve the product_name and unit_price from the Products table.

Explanation:

This SQL query selects the product_name and unit_price columns from the Products table. It retrieves every row but only the specified columns, which are product_name and unit_price.

3. Retrieve the sale_id and sale_date from the Sales table.

This SQL query selects the sale_id and sale_date columns from the Sales table. It retrieves every row but only the specified columns, which are sale_id and sale_date.

4. Filter the Sales table to show only sales with a total_price greater than $100.

This SQL query selects all columns from the Sales table but only returns rows where the total_price column is greater than 100. It filters out sales with a total_price less than or equal to $100.

5. Filter the Products table to show only products in the ‘Electronics’ category.

This SQL query selects all columns from the Products table but only returns rows where the category column equals ‘Electronics’. It filters out products that do not belong to the ‘Electronics’ category.

6. Retrieve the sale_id and total_price from the Sales table for sales made on January 3, 2024.

This SQL query selects the sale_id and total_price columns from the Sales table but only returns rows where the sale_date is equal to ‘2024-01-03’. It filters out sales made on any other date.

7. Retrieve the product_id and product_name from the Products table for products with a unit_price greater than $100.

This SQL query selects the product_id and product_name columns from the Products table but only returns rows where the unit_price is greater than $100. It filters out products with a unit_price less than or equal to $100.

8. Calculate the total revenue generated from all sales in the Sales table.

This SQL query calculates the total revenue generated from all sales by summing up the total_price column in the Sales table using the SUM() function.

9. Calculate the average unit_price of products in the Products table.

This SQL query calculates the average unit_price of products by averaging the values in the unit_price column in the Products table using the AVG() function.

10. Calculate the total quantity_sold from the Sales table.

This SQL query calculates the total quantity_sold by summing up the quantity_sold column in the Sales table using the SUM() function.

11. Retrieve the sale_id, product_id, and total_price from the Sales table for sales with a quantity_sold greater than 4.

This SQL query selects the sale_id, product_id, and total_price columns from the Sales table but only returns rows where the quantity_sold is greater than 4.

12. Retrieve the product_name and unit_price from the Products table, ordering the results by unit_price in descending order.

This SQL query selects the product_name and unit_price columns from the Products table and orders the results by unit_price in descending order using the ORDER BY clause with the DESC keyword.

13. Retrieve the total_price of all sales, rounding the values to two decimal places.

This SQL query calculates the total sales revenu by summing up the total_price column in the Sales table and rounds the result to two decimal places using the ROUND() function.

14. Calculate the average total_price of sales in the Sales table.

This SQL query calculates the average total_price of sales by averaging the values in the total_price column in the Sales table using the AVG() function.

15. Retrieve the sale_id and sale_date from the Sales table, formatting the sale_date as ‘YYYY-MM-DD’.

This SQL query selects the sale_id and sale_date columns from the Sales table and formats the sale_date using the DATE_FORMAT() function to display it in ‘YYYY-MM-DD’ format.

16. Calculate the total revenue generated from sales of products in the ‘Electronics’ category.

This SQL query calculates the total revenue generated from sales of products in the ‘Electronics’ category by joining the Sales table with the Products table on the product_id column and filtering sales for products in the ‘Electronics’ category.

17. Retrieve the product_name and unit_price from the Products table, filtering the unit_price to show only values between $20 and $600.

This SQL query selects the product_name and unit_price columns from the Products table but only returns rows where the unit_price falls within the range of $50 and $200 using the BETWEEN operator.

18. Retrieve the product_name and category from the Products table, ordering the results by category in ascending order.

This SQL query selects the product_name and category columns from the Products table and orders the results by category in ascending order using the ORDER BY clause with the ASC keyword.

19. Calculate the total quantity_sold of products in the ‘Electronics’ category.

This SQL query calculates the total quantity_sold of products in the ‘Electronics’ category by joining the Sales table with the Products table on the product_id column and filtering sales for products in the ‘Electronics’ category.

20. Retrieve the product_name and total_price from the Sales table, calculating the total_price as quantity_sold multiplied by unit_price.

This SQL query retrieves the product_name from the Sales table and calculates the total_price by multiplying quantity_sold by unit_price, joining the Sales table with the Products table on the product_id column.

These exercises are designed to challenge you beyond basic queries, delving into more complex data manipulation and analysis. By tackling these problems, you’ll solidify your understanding of advanced SQL concepts like joins, subqueries, functions, and window functions, ultimately boosting your ability to work with real-world data scenarios effectively.

1. Calculate the total revenue generated from sales for each product category.

This query joins the Sales and Products tables on the product_id column, groups the results by product category, and calculates the total revenue for each category by summing up the total_price.

2. Find the product category with the highest average unit price.

This query groups products by category, calculates the average unit price for each category, orders the results by the average unit price in descending order, and selects the top category with the highest average unit price using the LIMIT clause.

3. Identify products with total sales exceeding $500.

This query joins the Sales and Products tables on the product_id column, groups the results by product name, calculates the total sales revenue for each product, and selects products with total sales exceeding 30 using the HAVING clause.

4. Count the number of sales made in each month.

This query formats the sale_date column to extract the month and year, groups the results by month, and counts the number of sales made in each month.

5. Determine the average quantity sold for products with a unit price greater than $100.

This query joins the Sales and Products tables on the product_id column, filters products with a unit price greater than $100, and calculates the average quantity sold for those products.

6. Retrieve the product name and total sales revenue for each product.

This query joins the Sales and Products tables on the product_id column, groups the results by product name, and calculates the total sales revenue for each product.

7. List all sales along with the corresponding product names.

This query joins the Sales and Products tables on the product_id column and retrieves the sale_id and product_name for each sale.

8. Retrieve the product name and total sales revenue for each product.

This query will give you the top three product categories contributing to the highest percentage of total revenue generated from sales. However, if you only have one category (Electronics) as in the provided sample data, it will be the only result.

9. Rank products based on total sales revenue.

This query joins the Sales and Products tables on the product_id column, groups the results by product name, calculates the total sales revenue for each product, and ranks products based on total sales revenue using the RANK () window function.

10. Calculate the running total revenue for each product category.

This query joins the Sales and Products tables on the product_id column, partitions the results by product category, orders the results by sale date, and calculates the running total revenue for each product category using the SUM() window function.

11. Categorize sales as “High”, “Medium”, or “Low” based on total price (e.g., > $200 is High, $100-$200 is Medium, < $100 is Low).

This query categorizes sales based on total price using a CASE statement. Sales with a total price greater than $200 are categorized as “High”, sales with a total price between $100 and $200 are categorized as “Medium”, and sales with a total price less than $100 are categorized as “Low”.

12. Identify sales where the quantity sold is greater than the average quantity sold.

This query selects all sales where the quantity sold is greater than the average quantity sold across all sales in the Sales table.

13. Extract the month and year from the sale date and count the number of sales for each month.

14. calculate the number of days between the current date and the sale date for each sale..

This query calculates the number of days between the current date and the sale date for each sale using the DATEDIFF function.

15. Identify sales made during weekdays versus weekends.

This query categorizes sales based on the day of the week using the DAYOFWEEK function. Sales made on Sunday (1) or Saturday (7) are categorized as “Weekend”, while sales made on other days are categorized as “Weekday”.

This section likely dives deeper into complex queries, delving into advanced features like window functions, self-joins, and intricate data manipulation techniques. By tackling these challenging exercises, users can refine their SQL skills and tackle real-world data analysis scenarios with greater confidence and efficiency.

1. Write a query to create a view named Total_Sales that displays the total sales amount for each product along with their names and categories.

This query creates a view named Total_Sales that displays the total sales amount for each product along with their names and categories.

2. Retrieve the product details (name, category, unit price) for products that have a quantity sold greater than the average quantity sold across all products.

This query retrieves the product details (name, category, unit price) for products that have a quantity sold greater than the average quantity sold across all products.

3. Explain the significance of indexing in SQL databases and provide an example scenario where indexing could significantly improve query performance in the given schema.

With an index on the sale_date column, the database can quickly locate the rows that match the specified date without scanning the entire table. The index allows for efficient lookup of rows based on the sale_date value, resulting in improved query performance.

4. Add a foreign key constraint to the Sales table that references the product_id column in the Products table.

This query adds a foreign key constraint to the Sales table that references the product_id column in the Products table, ensuring referential integrity between the two tables.

5. Create a view named Top_Products that lists the top 3 products based on the total quantity sold.

This query creates a view named Top_Products that lists the top 3 products based on the total quantity sold.

6. Implement a transaction that deducts the quantity sold from the Products table when a sale is made in the Sales table, ensuring that both operations are either committed or rolled back together.

The quantity in stock for product with product_id 101 should be updated to 5.The transaction should be committed successfully.

7. Create a query that lists the product names along with their corresponding sales count.

This query selects the product names from the Products table and counts the number of sales (using the COUNT() function) for each product by joining the Sales table on the product_id. The results are grouped by product name using the GROUP BY clause.

8. Write a query to find all sales where the total price is greater than the average total price of all sales.

The subquery (SELECT AVG(total_price) FROM Sales) calculates the average total price of all sales. The main query selects all columns from the Sales table where the total price is greater than the average total price obtained from the subquery.

9. Analyze the performance implications of indexing the sale_date column in the Sales table, considering the types of queries commonly executed against this column.

By comparing the execution plans and analysis results of these queries, we can evaluate the performance implications of indexing the sale_date column. We’ll be able to observe differences in factors such as the query execution time, the type of scan used (sequential scan vs. index scan), and any additional costs associated with using the index.

10. Add a check constraint to the quantity_sold column in the Sales table to ensure that the quantity sold is always greater than zero.

All rows in the Sales table meet the condition of the check constraint, as each quantity_sold value is greater than zero.

11. Create a view named Product_Sales_Info that displays product details along with the total number of sales made for each product.

This view provides a concise and organized way to view product details alongside their respective sales information, facilitating analysis and reporting tasks.

12. Develop a stored procedure named Update_Unit_Price that updates the unit price of a product in the Products table based on the provided product_id.

The above SQL code creates a stored procedure named Update_Unit_Price. This stored procedure takes two parameters: p_product_id (the product ID for which the unit price needs to be updated) and p_new_price (the new unit price to set).

13. Implement a transaction that inserts a new product into the Products table and then adds a corresponding sale record into the Sales table, ensuring that both operations are either fully completed or fully rolled back.

This will update the unit price of the product with product_id 101 to 550.00 in the Products table.

14. Write a query that calculates the total revenue generated from each category of products for the year 2024.

When you execute this query, you will get the total revenue generated from each category of products for the year 2024.

If you’re looking to sharpen your SQL skills and gain more confidence in querying database s, consider delving into these articles. They’re packed with query-based SQL questions designed to enhance your understanding and proficiency in SQL .

By practicing with these exercises, you’ll not only improve your SQL abilities but also boost your confidence in tackling various database-related tasks. The Questions are as follows:

  • How to Insert a Value that Contains an Apostrophe in SQL?
  • How to Select Row With Max Value in SQL?
  • How to Efficiently Convert Rows to Columns in SQL?
  • How To Use Nested Select Queries in SQL
  • How to Select Row With Max Value on a Column in SQL?
  • How to Specify Condition in Count() in SQL?
  • How to Find the Maximum of Multiple Columns in SQL?
  • How to Update Top 100 Records in SQL?
  • How to Select the Last Records in a One-To-Many Relationship Using SQL Join
  • How to Join First Row in SQL?
  • How to Insert Row If Not Exists in SQL?
  • How to Use GROUP BY to Concatenate Strings in SQL?
  • How Inner Join works in LINQ to SQL
  • How to Get the Identity of an Inserted Row in SQL
  • How to Declare a Variable in SQL?

Mastering SQL requires consistent practice and hands-on experience. By working through these SQL practice exercises , you’ll strengthen your skills and gain confidence in querying relational databases.

Whether you’re just starting or looking to refine your expertise, these exercises provide valuable opportunities to hone your SQL abilities. Keep practicing , and you’ll be well-equipped to tackle real-world data challenges with SQL.

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

To log in and use all the features of Khan Academy, please enable JavaScript in your browser.

Unit 3: Intro to SQL: Querying and managing data

About this unit.

Learn how to use SQL to store, query, and manipulate data. SQL is a special-purpose programming language designed for managing data in a relational database, and is used by a huge number of apps and organizations.

  • Welcome to SQL (Opens a modal)
  • Creating a table and inserting data (Opens a modal)
  • Challenge: Book list database (Opens a modal)
  • Querying the table (Opens a modal)
  • Challenge: Box office hits database (Opens a modal)
  • Aggregating data (Opens a modal)
  • Challenge: TODO list database stats (Opens a modal)
  • S-Q-L or SEQUEL? (Opens a modal)
  • Project: Design a store database (Opens a modal)

More advanced SQL queries

  • More complex queries with AND/OR (Opens a modal)
  • Challenge: Karaoke song selector (Opens a modal)
  • Querying IN subqueries (Opens a modal)
  • Challenge: Playlist maker (Opens a modal)
  • Restricting grouped results with HAVING (Opens a modal)
  • Challenge: The wordiest author (Opens a modal)
  • Who issues SQL queries? (Opens a modal)
  • Calculating results with CASE (Opens a modal)
  • Challenge: Gradebook (Opens a modal)
  • Project: Data dig (Opens a modal)

Relational queries in SQL

  • Splitting data into related tables (Opens a modal)
  • JOINing related tables (Opens a modal)
  • Challenge: Bobby's Hobbies (Opens a modal)
  • Joining related tables with left outer joins (Opens a modal)
  • Challenge: Customer's orders (Opens a modal)
  • Joining tables to themselves with self-joins (Opens a modal)
  • Challenge: Sequels in SQL (Opens a modal)
  • Combining multiple joins (Opens a modal)
  • Challenge: FriendBook (Opens a modal)
  • Project: Famous people (Opens a modal)
  • More efficient SQL with query planning and optimization (Opens a modal)

Modifying databases with SQL

  • Using SQL to update a database (Opens a modal)
  • Changing rows with UPDATE and DELETE (Opens a modal)
  • Challenge: Dynamic Documents (Opens a modal)
  • Altering tables after creation (Opens a modal)
  • Challenge: Clothing alterations (Opens a modal)
  • Make your SQL safer (Opens a modal)
  • Project: App impersonator (Opens a modal)

Further learning in SQL

  • What to learn next (Opens a modal)
  • SQL Server training
  • Write for us!

Emil Drkusic

Learn SQL: Practice SQL Queries

Today is the day for SQL practice #1. In this series, so far, we’ve covered most important SQL commands ( CREATE DATABASE & CREATE TABLE , INSERT , SELECT ) and some concepts ( primary key , foreign key ) and theory ( stored procedures , user-defined functions , views ). Now it’s time to discuss some interesting SQL queries.

Let’s take a quick look at the model we’ll use in this practice.

SQL Practice - the data model we'll use in the article

You can expect that in real-life situations (e.g., interview), you’ll have a data model at your disposal. If not, then you’ll have the description of the database (tables and data types + additional description of what is stored where and how the tables are related).

The worst option is that you have to check all the tables first. E.g., you should run a SELECT statement on each table and conclude what is where and how the tables are related. This won’t probably happen at the interview but could happen in the real-life, e.g., when you continue working on an existing project.

Before We Start

The goal of this SQL practice is to analyze some typical assignments you could run into at the interview. Other places where this might help you are college assignments or completing tasks related to online courses.

The focus shall be on understanding what is required and what is the learning goal behind such a question. Before you continue, feel free to refresh your knowledge on INNER JOIN and LEFT JOIN , how to join multiple tables , SQL aggregate functions , and the approach to how to write complex queries . If you feel ready, let’s take a look at the first 2 queries (we’ll have some more in upcoming articles). For each query, we’ll describe the result we need, take a look at the query, analyze what is important for that query, and take a look at the result.

SQL Practice #1 – Aggregating & LEFT JOIN

Create a report that returns a list of all country names (in English), together with the number of related cities we have in the database. You need to show all countries as well as give a reasonable name to the aggregate column. Order the result by country name ascending.

Let’s analyze the most important parts of this query:

  • We’ve used LEFT JOIN ( LEFT JOIN city ON country.id = city.country_id ) because we need to include all countries, even those without any related city
  • We must use COUNT(city.id) AS number_of_cities and not only COUNT(*) AS number_of_cities because COUNT(*) would count if there is a row in the result (LEFT JOIN creates a row no matter if there is related data in other table or not). If we count the city.id , we’ll get the number of related cities
  • The last important thing is that we’ve used GROUP BY country.id, country.country_name_eng instead of using only GROUP BY country.country_name_eng . In theory (and most cases), grouping by name should be enough. This will work OK if the name is defined as UNIQUE. Still, including a primary key from the dictionary, in cases similar to this one, is more than desired

You can see the result returned in the picture below.

combining LEFT JOIN with aggregate function

SQL Practice #2 – Combining Subquery & Aggregate Function

Write a query that returns customer id and name and the number of calls related to that customer. Return only customers that have more than the average number of calls of all customers.

The important things I would like to emphasize here are:

  • Please notice that we’ve used aggregate functions twice, once in the “main” query, and once in the subquery. This is expected because we need to calculate these two aggregate values separately – once for all customers (subquery) and for each customer separately (“main” query)
  • The aggregate function in the “main” query is COUNT(call.id) . It’s used in the SELECT part of the query, but we also need it in the HAVING part of the query (Note: HAVING clause is playing the role of the WHERE clause but for aggregate values)
  • Group is created by id and customer name. These values are the ones we need to have in the result
  • In the subquery, we’ve divided the total number of rows ( COUNT(*) ) by the number of distinct customers these calls were related to ( COUNT(DISTINCT customer_id) ). This gave us the average number of calls per customer
  • The last important thing here is that we used the CAST operator ( CAST(… AS DECIMAL(5,2)) ). This is needed because the final result would probably be a decimal number. Since both COUNTs are integers, SQL Server would also return an integer result. To prevent this from happening, we need to CAST both divider and the divisor as decimal numbers

Let’s take a look at what the query actually returned.

SQL Practice - the result returned by the subquery using aggregate function

In today’s SQL practice, we’ve analyzed only two examples. Still, these two contain some parts you’ll often meet at assignments – either in your work, either in a testing (job interview, college assignments, online courses, etc.). In the next part, we’ll continue with a few more interesting queries that should help you solve problems you might run into.

Table of contents

  • Recent Posts

Emil Drkusic

  • Learn SQL: How to prevent SQL Injection attacks - May 17, 2021
  • Learn SQL: Dynamic SQL - March 3, 2021
  • Learn SQL: SQL Injection - November 2, 2020

Related posts:

  • Learn SQL: How to Write a Complex SELECT Query
  • Learn SQL: Join multiple tables
  • Learn SQL: Aggregate Functions
  • Learn SQL: Set Theory
  • Top SQL Server Books

Basic SQL Practice Grounds

Last modified: December 09, 2019

You’re through the basics of SQL! This is a great place to stop and get more practice on what you’ve learned so far. Here we’ve constructed a list of challenges to give you that practice. Take some time to go through these before moving on to the Mid-Level SQL section.

A few things to keep in mind when going through

  • If no specific columns or values are called out to return, assume that it’s asking for all the columns (splat * ).
  • If it does ask for specific information like “names”, only return that column. If you return other things as well it won’t be able to match the correct answer.
  • If you’re having trouble with a question use the ‘Hint’ button. If you’re really having trouble or think that the answer might be wrong, send us a note at [email protected] .
  • We check if things are correct not by the query you wrote, but by the results that are returned. This is the best way as there are often a few different ways to get the same result.

Q. Fetch the first 8 rows of the albums table. references: select limit

Q. fetch the 12th through 32nd (21 total) rows of the tracks table. references: select limit, q. fetch the 9th through 49th (41 total) rows of the artists table. references: limit, q. get the name s of all of the artists . references: from, q. get the name s of all of the artists in reverse alphabetical order. (z to a) references: order-by, q. get only the last 4 names of the artists sorted alphabetically. references: order-by limit, q. get the rows of the 20 longest tracks. references: order-by limit.

If you’ve completed all of these CONGRATULATIONS! You’re proficient and fluent enough in SQL now to complete a significant portion of analytic and transactional queries.

Written by: Dave Fowler Reviewed by: Matt David

  • Contributors
  • Data Conversations
  • Cloud Data Management
  • How to Design a Dashboard
  • How to Teach People SQL
  • Avoid Misrepresenting Data
  • SQL Optimization
  • Fundamentals of Analysis

©2019 All Rights Reserved • Terms

This is CS50 SQL 2023, an older version of the course. See cs50.harvard.edu/sql/2024 for the latest!

This is CS50’s introduction to databases using a language called SQL. Learn how to create, read, update, and delete data with relational databases, which store data in rows and columns. Learn how to model real-world entities and relationships among them using tables with appropriate types, triggers, and constraints. Learn how to normalize data to eliminate redundancies and reduce potential for errors. Learn how to join tables together using primary and foreign keys. Learn how to automate searches with views and expedite searches with indexes. Learn how to connect SQL with other languages like Python and Java. Course begins with SQLite for portability’s sake and ends with introductions to PostgreSQL and MySQL for scalability’s sake as well. Assignments inspired by real-world datasets.

Whereas CS50x itself focuses on computer science more generally as well as programming with C, Python, SQL, and JavaScript, this course, aka CS50 SQL, is entirely focused on SQL. You can take CS50 SQL before CS50x, during CS50x, or after CS50x. But for an introduction to computer science itself, you should still take CS50x!

How to Take this Course

Even if you are not a student at Harvard, you are welcome to “take” this course for free via this OpenCourseWare by working your way through the course’s seven weeks of material. If you’d like to submit the course’s problem sets and final project for feedback, be sure to create an edX account , if you haven’t already. Ask questions along the way via any of the course’s communities !

  • If interested in a verified certificate from edX , enroll at cs50.edx.org/sql instead.
  • If interested in transfer credit and accreditation from Harvard Extension School , register at web.dce.harvard.edu/extension/csci/e/151 instead.
  • If interested in transfer credit and accreditation from Harvard Summer School , register at web.dce.harvard.edu/summer/csci/s/151 instead.

How to Teach this Course

If you are a teacher, you are welcome to adopt or adapt these materials for your own course, per the license .

Revising the Select Query I Easy SQL (Basic) Max Score: 10 Success Rate: 95.95%

Revising the select query ii easy sql (basic) max score: 10 success rate: 98.68%, select all easy sql (basic) max score: 10 success rate: 99.54%, select by id easy sql (basic) max score: 10 success rate: 99.66%, japanese cities' attributes easy sql (basic) max score: 10 success rate: 99.59%, japanese cities' names easy sql (basic) max score: 10 success rate: 99.52%, weather observation station 1 easy sql (basic) max score: 15 success rate: 99.42%, weather observation station 3 easy sql (basic) max score: 10 success rate: 97.99%, weather observation station 4 easy sql (basic) max score: 10 success rate: 98.72%, weather observation station 5 easy sql (intermediate) max score: 30 success rate: 94.36%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

The TPT Blog

Fun Last-Day-of-School Activities to Wrap Up the Year

Happy kids middle school students group giving high five together in classroom.

Hooray, you’ve made it to the end of the school year! With all testing and grading out of the way, it’s time to think about planning some fun last-day-of-school activities. The final days of school are a time to reflect on the year’s accomplishments, celebrate, and say goodbyes. Make your last day together extra special with one of these fun activities that are sure to send your students off to summer vacation with a smile on their faces.

Fun Last-Day-of-School Activities to Kick off Summer Break

Here are some engaging last-day-of-school activities you can consider adding to your repertoire.

Write letters to next year’s students

Are you looking for a last-day-of-school activity that will engage students in a productive writing task and meaningful reflections? Try having them write a letter to next year’s class! In these letters, current students can share their memories from the past year, give a sneak peek of what next year’s class will learn, and give them advice for the school year ahead. Your students will love being able to share their thoughts and advice from their own experiences in your class.

Clickable TPT resource cover image

Words of Wisdom – Letters to Future Students by Life with Mrs Wasik Grades: 1-6

Clickable TPT resource cover image

End of Year Activity – Letter to A Future Student – End of Year Writing Project by The Creative Classroom Grades 5-9

Create a memory book

End-of-year memory books are a great activity for students of all ages to reflect on their progress and memories from the past school year. Plus, they make for a great keepsake to take home on the last day of school. Check out one of these fun, no-prep memory book activities to get you started. 

Clickable TPT resource cover image

End of the Year Memory Book {Kindergarten, First, and Second Grade } by Haley O’Connor Grades: K-2

Clickable TPT resource cover image

End of the Year Memory Book {Not Grade Specific} by Michael Friermood – The Thinker Builder Grades: 2-6

Clickable TPT resource cover image

END OF YEAR ESL Memory Book Activities PRINT and EASEL by Diana Bailey Grades: 5-8

Clickable TPT resource cover image

End of the Year Writing Activities and Memory Book EDITABLE Distance Learning by Tracee Orman Grades: 7-12

Set goals for the summer

With summer vacation (literally) right around the corner, you can use the final day of school to get students thinking about some of the goals and activities they’d like to accomplish this summer.

Clickable TPT resource cover image

Summer Bucket List: Last Day of School & End of the Year Fun Activity by Enhance SEL Grades: 1-8

Clickable TPT resource cover image

Summer Bucket List End of the Year Activities by The Scholar’s Source Grade: 3-11

Clickable TPT resource cover image

End of School Year Reflection Pages and Goal Setting for Summer and Next Year by Success in Special Ed Grades: 7-10

When the tests are all taken, and the assignments all handed in, it’s time to get crafty! These end-of-school year craftivities are a great way to engage students and to sneak a little more writing and fine motor skill practice into the last day of the year.

Clickable TPT resource cover image

End of the Year Sunglasses Bulletin Board Craft and Writing Activity | Last Day by Sweet for Kindergarten- Kristina Harrill Grades: PreK-5

Clickable TPT resource cover image

Last Day of School Activities | Last Day of School Crown Craft | End of Year by Second Grade Smiles Grades: K-3

Activities for the Last Week of School

Need activities to cover the entire last week of school? We’ve got you covered. To make your life a little easier as the school year comes to a close, check out these low-prep activities to help you get through the last week!

Clickable TPT resource cover image

Last Week of School Activities for Second Grade (2nd) by Cara’s Creative Playground Grades: 2

Clickable TPT resource cover image

End of The Year Activities – Last Week of School Resource by Addie Williams Grades: 6-8

Clickable TPT resource cover image

End of the Year Activities – Last Week of School Fun for Middle and High School by Cara McLeod Grades: 5-10

Clickable TPT resource cover image

End of the Year Activities for Seniors High School Playlist Last Week of School by The Supported Teacher Grades: 11-12

Other Ideas for End of the Year

For more ways to end the school year on a high note, browse end-of-year resources on TPT or check out these posts for more ideas:

  • End-of-Year Review Activities for Elementary and High School Students
  • Celebrating Student Success: End of the Year Awards for Students
  • Escape Room Ideas and Templates for Every Classroom

The TPT Blog

  • Middle School
  • High School
  • Social Studies
  • Social-Emotional Learning
  • Back-to-School
  • Asian Pacific American Heritage Month
  • Autism Acceptance Month
  • Black History Month
  • Hispanic Heritage Month
  • Pride Month
  • Indigenous Peoples’ Month
  • Women’s History Month

SQL Statement:

Edit the SQL Statement, and click "Run SQL" to see the result.

The Try-SQL Editor ? × --> at w3schools.com

This SQL-Statement is not supported in the WebSQL Database.

The example still works, because it uses a modified version of SQL.

Your browser does not support WebSQL.

You are now using a light-version of the Try-SQL Editor, with a read-only Database.

If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.

Our Try-SQL Editor uses WebSQL to demonstrate SQL.

A Database-object is created in your browser, for testing purposes.

You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.

WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.

WebSQL Browser Support

WebSQL is supported in Chrome, Safari, Opera, and Edge(79).

If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.

sql assignment for school

6 ways to use Microsoft Copilot for end-of-school-year tasks

May 14, 2024.

By Microsoft Education Team

sql assignment for school

Share this article

The end of the school year is a hectic time for educators everywhere. Between reviewing content, completing assessments, and maintaining classroom management, it’s easy to feel the pressure of too many responsibilities and not enough time to accomplish everything.

Whether closing out the academic year in the northern hemisphere or preparing for the next one in the southern hemisphere, Microsoft Copilot offers innovative and efficient ways to complete many of the tasks that occupy these transitional times of year. From drafting student feedback to composing newsletters and offering planning suggestions for events, Copilot adapts to whatever task it’s asked. To get started, all you need is a basic understanding of how to access and use Copilot.

Start using Copilot for your end-of-school-year tasks

You can learn how to use Copilot by visiting Meet your AI assistant for education: Microsoft Copilot .

When you’re ready to get started, go to copilot.microsoft.com or download the iOS or Android mobile app.

Writing prompts for the end of the school year

Prompting Copilot to generate content requires practice. Including specific information in your prompt helps produce more relevant responses.

An effective Copilot prompt:

  • Asks the tool to take on a role called a persona .
  • Provides an objective  that tells the tool what to do or produce.
  • Defines the audience  who will be using whatever Copilot generates.
  • Includes context  that gives the tool background information.
  • Sets boundaries  that limit or constrain responses.

sql assignment for school

Elements of a Good Prompt infographic which includes tips for writing prompts that produce more relevant responses.

Throughout this post, you’ll find sample prompts that include these components. We recommend borrowing inspiration from them and adjusting to make them fit your own classroom, or you can copy and paste the examples without modifications if you are just beginning.

Now let’s learn how Copilot can help you complete six common end-of-school-year tasks.

1. Craft student feedback at the end of the school year

Copilot can help you write end-of-school-year feedback in a style and tone that all students can understand. Simply craft a prompt that includes the subject area and details about the feedback you want to provide, and Copilot can draft a constructive, supportive statement written specifically for students. For example:

You are a fourth-grade teacher who is writing feedback on a student’s current reading skills. The student uses details to explain what text means but is unable to draw inferences in fiction. The student can identify in-text examples that illustrate a given theme but is unable to independently produce a theme without guidance. Write a short statement that explains this feedback to a student. Include a description about why using details is important and 1-2 ways to develop this skill. The paragraph should be written with plain text so that a fourth-grade student will understand.

You can always refine your prompt if the response is not what you expected. Simply include something like, “Re-write this feedback in Spanish” without selecting New topic , and Copilot will continue where you left off. Give it a try.

2. Write end-of-school-year reflections

Educators often write end-of-school-year newsletters for families, update class blogs with a final post, and draft reflections on school year goals. Copilot can assist with all these tasks and can help you create personalized, engaging visuals for your content. For example, you can use the following prompt to produce a summer newsletter for families.

You are the science department leader for a middle school in New York City. Draft a summer newsletter for families that includes an introduction that talks about the past year and 5 sections: Science Books for Young Adults, Science at Home, Science Summer Camps, Science Events in NYC, and NY Science Museums. Only include information that can be linked to a website to learn more. The newsletter should be written in plain text using an informal tone.

You can also share your experiences, memorable moments, and insights from the school year and Copilot will help you find creative ways to share this information with colleagues, families, and students.

3. Organize classroom materials at the end of the school year

The last few weeks of a school year includes packing up classrooms for the summer, collecting books and devices, and organizing materials for the next year. Copilot can create checklists or reminders for end-of-school-year tasks like these and offer suggestions that you might not even consider. For example:

You are a high school media specialist who checks out technology to administrators and educators. Write a checklist of the 3 most important things to do before returning each of the following devices: document camera, tablet, digital projector, games, and wires. Make each device a section heading and use bulleted lists for the content. Write the checklists so that the content is easily understood by people with varying levels of technological expertise.

Another way to use Copilot when you are organizing classroom materials is to ask for suggestions for efficient ways to declutter and prepare your classroom for the next school year.

4. Plan an end-of-school-year celebration

Many schools celebrate major milestones like the start of summer or moving from lower grades to higher grades with a party or ceremony. Copilot can be your personal planner and assist with brainstorming ideas for end-of-school-year events, awards ceremonies, or virtual gatherings. It can even suggest ways to be more inclusive in areas you might not have considered, like food options in the prompt below.

You are a guidance counselor in charge of helping rising eighth-grade students transition from middle school to high school. Draft a letter to middle school teachers that shares the biggest differences between middle school and high school. Include paragraphs on class schedules, touring the high school, meeting educators, extracurricular activities, and summer reading books. The letter should be written in a formal, conversational tone.

Whether you are creating invitations, planning activities, or drafting speeches, Copilot can be your creative collaborator.

5. Develop transition materials at the end of the school year

When students enter elementary school or move to middle or high school, everyone involved in the transition needs to know how to prepare for this change. Students need to know what to expect, families need to know how to support their children, and current educators need to provide relevant information. Copilot can help create transition materials so that everyone stays informed using a prompt like this example:

You can also use Copilot to write welcome letters, tips for success, or information about what to expect in the upcoming year.

6. Streamline parent communication at the end of the school year

Copilot can help you create templates for parent-teacher conferences at the end of the school year, as well as student progress updates, and letters to families. For example, you can ask Copilot to create a message to families about signing up for conferences with the following prompt.

You are a high school math teacher who teaches introductory algebra. Write a letter to families about parent-teacher conferences. Include an introductory paragraph that thanks families for their ongoing support and paragraphs about what will happen during the conferences, why conferences are important, who should attend, and how to prepare for the meeting. Conclude the letter with a paragraph about how to sign up for a conference slot. Write the letter using an approachable, informal tone.

Microsoft Copilot is a versatile AI tool for educators that adapts to your specific needs. To learn more about Microsoft’s AI solutions and resources, check out Smart learning: AI resources every educator should know and the  AI for educators learning path on Microsoft Learn. Most importantly, enjoy the end of the school year with your students and the time you saved by using Copilot. 

Related stories

sql assignment for school

Explore insights from the AI in Education Report

The swift rise of generative AI is reshaping how schools approach creation, problem-solving, learning, and communication. Your schools are in a pivotal moment when critical thinking and metacognitive skills are more important than ever as new technology develops

sql assignment for school

How to celebrate Earth Day 2024 with your students

Spark your students' curiosity with Earth Day activities and more from Microsoft. From video games to projects, try these fun Earth Day activities for your class.

sql assignment for school

Kickstart your school’s AI journey with the Microsoft Education AI Toolkit

AI is igniting enthusiasm in classrooms, department meetings, board rooms, and administrative offices across the country. For many, generative AI is changing what it means to create, solve problems, communicate, and even learn. It’s not just teachers and students embracing this new technology; education leaders are also turning to AI to improve operational processes and provide equitable access to resources among other opportunities.

  • SCHOOL STORIES
  • MICROSOFT EDUCATOR CENTER
  • CONTACT SALES

Read the Latest on Page Six

  • Sports Betting
  • Sports Entertainment
  • New York Yankees
  • New York Mets
  • Transactions

Recommended

Mets ace kodai senga ‘making some strides’ during injury recovery.

  • View Author Archive
  • Email the Author
  • Follow on Twitter
  • Get author RSS feed

Contact The Author

Thanks for contacting us. We've received your submission.

Thanks for contacting us. We've received your submission.

PHILADELPHIA — Mets officials have begun to receive a positive vibe about Kodai Senga’s rehab.

The right-hander had backed off his throwing progression from a shoulder strain in the last week to focus on mechanics, but president of baseball operations David Stearns said Thursday that Senga is feeling better about the situation following a recent bullpen session and trending toward a minor league rehab assignment.

“I think we’ve had a good bullpen where he felt he was making some strides,” Stearns said before the Mets beat the Phillies, 6-5 , in 11 innings at Citizens Bank Park. “I don’t know exactly when we’ll get him out on a rehab assignment — that’s the next big step here — but I think we all feel better about it, maybe here than we did five or six days ago.”

Kodai Senga

Senga this week said he wanted to focus on mechanics before pitching in minor league games because he believes a change in his delivery at least partially led to the shoulder strain that shut him down early in spring training.“I think Step 1 is let’s get him to a point where he feels comfortable mechanically, and I think we took a real positive step forward in that direction,” Stearns said.

Senga will need about a month of buildup in the minor leagues, once he begins his rehab assignment, before he can join the Mets’ rotation.

Team owner Steve Cohen told SNY he still believes in the Mets for this season , a day after responding to a tweet from a fan who wondered about blowing up the roster.

Delivering insights on all things Amazin's

Sign up for Inside the Mets by Mike Puma, exclusively on Sports+

Please provide a valid email address.

By clicking above you agree to the Terms of Use and Privacy Policy .

Enjoy this Post Sports+ exclusive newsletter!

Cohen responded to the fan: “All in the future, not much we can do before the trade deadline.

The tweet was soon deleted.

But Cohen told the team’s TV rights holder he hasn’t given up on the season.

“I believe in this team,” Cohen told the outlet. “I believe in the back of the baseball card. It’s way too early to speculate on anything. It’s May 16. I expect to make the playoffs. I know the fan base is frustrated, but it’s still early. We’re still very capable of making the playoffs…. I fully expect to make the playoffs.”

Steve Cohen may have wanted to keep that tweet in draft.

Brandon Nimmo was scratched from the starting lineup with a stomach bug.

Tyrone Taylor replaced Nimmo in the leadoff spot and DJ Stewart started in left field.

Joey Lucchesi was optioned to Triple-A Syracuse following his Wednesday start, and the Mets recalled lefty reliever Josh Walker.

Tylor Megill’s return to the starting rotation is scheduled for Monday in Cleveland.

The right-hander was placed on the injured list with a right shoulder strain following his first start of the season March 31.

Drew Smith played catch and was feeling better after reporting discomfort behind his right shoulder earlier in the week, according to manager Carlos Mendoza.

The right-hander will throw a bullpen Monday, but likely need at least one minor league rehab appearance before he’s considered for activation.

Share this article:

Ga. school retracts controversial class assignment on Hitler

ATLANTA, Ga. (Atlanta News First) - A metro Atlanta school is responding to backlash to a controversial assignment.

Parents are fuming and questioning the Mount Vernon School in Sandy Springs after their kids were asked about Hitler’s leadership.

The assignment asked students to rate the attributes of the former Nazi dictator. The school now acknowledges this caused distress and the assignment has now been removed from the curriculum.

MORE | Biden’s speech roils Morehouse College, a center of Black politics and culture

When he gives the commencement address at Morehouse College, President Joe Biden will have his most direct engagement with college students since the start of the Israel-Hamas war at a center of Black politics and culture.

Morehouse College

Head of School Kristy Lundstrom sent the following statement to Mount Vernon parents:

Dear Mount Vernon Family,

I am aware that a screenshot is being circulated on social media and has caused concern and distress. The screenshot is a snapshot taken out of context from a classroom assignment from March 2024. We do not condone positive labels for Adolf Hitler. The intent of the assignment was an exploration of World War II designed to boost student knowledge of factual events and understand the manipulation of fear leveraged by Adolf Hitler in connection to the Treaty of Versailles. When leadership was made aware of how the assignment was written it was removed from the curriculum.

Immediately following this incident, I met with the School’s Chief of Inclusion, Diversity, Equity, and Action, Head of Middle School, and a concerned Rabbi and friend of the School who shared the perspective of some of our families and supported us in a thorough review of the assignment and community impact. We worked to understand the balance of holding a safe environment for students while doing the important work of sharing history to prevent deniers and to be clear about the atrocities committed. Adolf Hitler and the events of this time period are difficult and traumatic to discuss.

In this very heavy time, when our Jewish students and families have the added stress of world events, we want to be clear that The Mount Vernon School wholeheartedly denounces antisemitism.

Our commitment is to embrace a diverse community where every individual is seen, valued, and heard. Please know that we are here to care for and support your children. We have counselors, faith leaders, and school leaders who have been and will continue to be here to talk to, listen to, and lift up your children.

Copyright 2024 WRDW/WAGT. All rights reserved.

A dozen people gathered In North Myrtle Beach to say goodbye to Andy's Angel

DHEC forces S.C. family to remove beach memorial to lost loved one

Aiken County Sheriff's Office

3-year-old girl ‘crushed’ by birdbath in Warrenville

Georgia Department of Juvenile Justice

How inmates ran wild in uprising at Augusta youth detention center

North Augusta Department of Public Safety

Shooting victim shows up to North Augusta emergency room

Cameron Levert Williams, 19

3rd suspect arrested in November murder near Paine College

Latest news.

sql assignment for school

I-TEAM: Unlawful torture lawsuits filed against Richmond County Sheriff’s Office

Lawsuits filed against Richmond County Sheriff's Office

Augusta Christian baseball team wins back-to-back state championships

sql assignment for school

Via Cognitive Health to open new building in Augusta

sql assignment for school

Harlem baseball team gets special send-off before state championship

sql assignment for school

  • Court rejects parents’ attempt to opt kids out of LGBTQ-inclusive reading assignments

( The Hill ) — A federal appeals court rejected a bid from a group of Maryland parents to require Montgomery County Public Schools to allow them to opt their children out of lessons that involve LGBTQ-inclusive material.

A divided three-judge panel of the 4th U.S. Circuit Court of Appeals affirmed a  lower court decision  denying a preliminary injunction on the basis that the parents had not yet demonstrated how the country’s board of education book policy would infringe on their right to free expression of religion.

Three sets of parents – who are Muslim, Jewish and Christian – along with a parental rights organization, sued the Maryland school district after it said it would no longer allow parents to opt their children out of lessons that used a slate of newly approved LGBTQ-inclusive books.

The parents argued that the books “contradict their sincerely held religious beliefs about marriage, human sexuality, and gender” and that the lack of an opt-out policy violates their children’s First Amendment right to free exercise of religion.

U.S. Circuit Judge G. Steven Agee, writing for the majority in the opinion, said there was not enough evidence on the record to assess how the books were being used in the classroom and, therefore, to assess the likelihood of the case succeeding.

“We take no view on whether the Parents will be able to present evidence sufficient to support any of their various theories once they have the opportunity to develop a record as to the circumstances surrounding the Board’s decision and how the challenged texts are actually being used in schools,” Agee, appointed by former President George W. Bush, wrote.

“At this early stage, however, given the Parents’ broad claims, the very high burden required to obtain a preliminary injunction, and the scant record before us, we are constrained to affirm the district court’s order denying a preliminary injunction,” he continued, in the opinion, which was joined by U.S. Circuit Judge DeAndrea Benjamin, an appointee of President Biden’s.

U.S. Circuit Judge A. Marvin Quattlebaum, Jr., an appointee of former President Trump’s, dissented, arguing the board violated parents’ right to influence their children’s religious upbringing.

Eric Baxter – vice president and senior counsel at the Becket Fund for Religious Liberty, which is representing the parents – pledged to appeal the ruling on Wednesday, in an emailed statement to The Hill.

“The court just told thousands of Maryland parents they have no say in what their children are taught in public schools,” Baxter said in his statement. “That runs contrary to the First Amendment, Maryland law, the School Board’s own policies, and basic human decency.”

“Parents should have the right to receive notice and opt their children out of classroom material that violates their faith. We will appeal this ruling,” he added.

In August 2023, U.S. District Judge Deborah Boardman found that the parents were unlikely to succeed on the merits and denied their request to keep the policy in place while the case proceeds. She found that they failed to show that the lack of an opt-out policy would result in the “indoctrination of their children” or “coerce their children to violate or change their religious beliefs.”

“The parents still may instruct their children on their religious beliefs regarding sexuality, marriage, and gender, and each family may place contrary views in its religious context,” Boardman wrote in the order last year.

“No government action prevents the parents from freely discussing the topics raised in the storybooks with their children or teaching their children as they wish,” she added.

Latest News

  • Major changes coming to Visa: How will it affect you?
  • North Carolina could ban face masks in public, even when used for medical reasons
  • After another rain-soaked session, Indy 500 drivers give it another try Thursday
  • Here are the prominent Republicans backing Biden over Trump

For the latest news, weather, sports, and streaming video, head to BRProud.com.

Court rejects parents’ attempt to opt kids out of LGBTQ-inclusive reading assignments

20 Basic SQL Query Examples for Beginners

Author's photo

  • sql queries

Table of Contents

What Is SQL?

Explanation, from basic sql queries to sql master.

These 20 basic queries are a must in a starter pack for every SQL beginner. These examples will get you going on your journey to mastering SQL.

You’ve set your mind on learning SQL, googled ‘basic sql query examples’ or something similar, and here you are staring at this article. Now what? All learning starts with the basics, so let’s start with the most basic question:

The first thing is to know what SQL is. SQL, or Structured Query Language, is a programming language. Like any language – programming or natural – it is used to communicate, to talk. SQL is designed to talk to a database. We do that using sentences that we call queries, which are SQL commands for retrieving data from the database.

We’ll soon show you 20 basic SQL query examples to start talking with the database. All these queries are taught in our SQL Basics course; this course will give you even more structure, examples, and challenges to solve. It has 129 interactive exercises on querying one or more tables, aggregating and grouping data, JOINs, subqueries, and set operations. Even with the 20 upcoming examples, we won’t show all the details or even all the basic-level queries. That’s why we recommend using the course as a platform for practicing the fundamentals we’ll discuss here.

Also, most of our examples are nicely presented in our SQL Basics Cheat Sheet . Feel free to have it by your side – it might help you better understand what follows next.

Let’s not lose any time! We’ll introduce the dataset, and then we’re off to writing and explaining basic SQL queries.

The dataset consists of two tables. The first one is shown below; you can create this table by copying and running this query from GitHub .

Like any table, it has a name: employees . Each table has columns which also have names. They describe what data each column contains.

The columns and data in the above table are:

  • id – The unique ID of the employee and the table’s primary key.
  • first_name – The employee’s first name.
  • last_name – The employee’s last name.
  • department – The employee’s department.
  • salary – The employee’s monthly salary, in USD.

All this tells us that this table is a list of a company’s employees and their salaries. There is also data on the employees’ departments. All employees work in the sales division, where the department can be either Corporate or Private Individuals. In other words, the employees sell the company’s products to companies and private individuals.

The other table in the dataset is named quarterly_sales . It is shown below, and the query for creating it is here .

The columns are:

  • employee_id – The unique ID of the employee. Also, a foreign key referencing the column id from the table employees .
  • q1_2022 – The sales made by that employee in the first quarter of 2022.
  • q2_2022 – The sales made by that employee in the second quarter of 2022.
  • q3_2022 – The sales made by that employee in the third quarter of 2022.
  • q4_2022 – The sales made by that employee in the fourth quarter of 2022.

In general, this table is a list of each quarter’s sales made by every employee shown in the first table.

Now, let’s start writing SQL queries.

1. Selecting All Columns From One Table

This query is useful when you want to quickly get all the columns from a table without writing every column in the SELECT statement .

Whenever you want to select any number of columns from any table, you need to use the SELECT statement. You write it, rather obviously, by using the SELECT keyword.

After the keyword comes an asterisk ( * ), which is shorthand for “all the columns in the table”.

To specify the table, use the FROM clause and write the table’s name afterward.

The query’s output is the whole table employees , as shown below.

2. Selecting One Column From One Table

You can use this query when you only need one column from the table..

The approach is similar to the previous query. However, this time, instead of an asterisk, we write the specific column name in SELECT . In this case, it’s the column first_name .

The second line of the query is the same: it references the table in the FROM clause.

The query returns the list of employees’ first names.

3. Selecting Two Columns From One Table

This query is useful when selecting two (or more) columns from one table.

Again, the approach is similar to earlier examples. To select two columns, you need to write their names in SELECT . The important thing is that the columns need to be separated by a comma. You can see in the example that there’s a comma between the columns first_name and last_name .

Then, as usual, reference the table employees in FROM .

Now the query shows the employees’ full names.

4. Selecting Two (or More) Columns From One Table and Filtering Using Numeric Comparison in WHERE

Knowing this SQL query will allow you to filter data according to numeric values. You can do that using comparison operators in the WHERE clause .

Here’s the overview of the SQL comparison operators.

The query actually selects three, not two columns.  It’s the same as with two columns: simply write them in SELECT and separate them with commas.

Then we reference the table in FROM .

Now, we need to show only employees with a salary above 3,800. To do this, you need to use WHERE . It’s a clause that accepts conditions and is used for filtering the output. It goes through the table and returns only the data that satisfies the condition.

In our case, we’re looking for salaries ‘greater than’ a certain number. In other words, a condition using the > comparison operator.

To set the condition, we write the column name in WHERE . Then comes the comparison operator, and after that, the value that the data has to be greater than. This condition will now return all the salaries that are above 3,800.

The query returns four employees and their salaries. As you can see, they all have salaries above 3,800.

5. Selecting Two Columns and Filtering Using an Equality Condition in WHERE

Once again, this basic SQL query example is useful when you want to select several columns but not all the rows from the table. Now you want to find the values that are the same as the value from the condition. For that, you need the equality condition ( = ).

The query selects employees’ first and last names.

However, we want to show only employees whose name is Luca. For this, we again use WHERE . The approach is similar to the previous example: we use WHERE, write the column name, and use the comparison operator. This time, our condition uses the equal sign ( = ).

In other words, the values in the column first_name have to be equal to Luca. Also, when the condition is not a number but a text or a date/time, it has to be written in single quotes ( '' ). That’s why our condition is written as ' Luca ', not simply Luca .

The output shows there’s only one employee named Luca, and his full name is Luca Pavarotti.

6. Selecting Two Columns and Ordering by One Column

Here’s another basic SQL query example that you’ll find useful. It can be used whenever you have to order the output in a certain way to make it more readable.

Ordering or sorting the output is done using the ORDER BY clause. By default, it orders the output in ascending order.  This works alphabetically (for text data), from the lowest to the highest number (for numerical data), or from the oldest to the newest date or time (for dates and times).

We again select employees’ first and last names. But now we want to sort the output in a specific way. In this example, it’s by employees’ surname. To do that, we use ORDER BY . In it, we simply write the column name.

We might add the keyword ASC after that to sort the output ascendingly. However, that’s not mandatory, as ascending sorting is a default in SQL.

The query returns a list of employees ordered alphabetically by their last names.

7. Selecting Two Columns and Ordering Descendingly by One Column

This example is similar to the previous one and has the same purpose: sorting your SQL query output. However, in this case, the data is ordered in descending order (Z to A, 10 to 1).

The query is almost exactly the same as in the previous example. The only difference is we’re ordering the output by the employee’s name descendingly.

To do that, put the keyword DESC after the last_name column in the ORDER BY clause.

You can see that the output is ordered the way we wanted.

8. Selecting Two Columns From One Table and Ordering Descendingly by Two Columns

Sorting an SQL query can get more sophisticated. It’s common to sort data by two or more columns, which you’re probably already familiar with as an Excel or Google Sheets user. The same can be done in SQL.

With this query, we’re building on the previous example; we want to sort the output by the employee’s salary and their last name. This time, we sort by salary descending and then by last name ascendingly.

We reference the column salary in ORDER BY and follow it with the keyword DESC . The DESC keyword indicates descending order. Before the second ordering criteria, we need to put a comma. After it comes the second criteria/column, which is last_name in this case. You can add or omit the keyword ASC to sort the output in ascending order.

Note: The order of the columns in ORDER BY is important! The query written as it is above will first sort by salary descendingly and then by the last name ascendingly. If you wrote ORDER BY last_name ASC, salary DESC , it would sort by last name first and then by salary in descending order.

The output is ordered by salary. When the salary is the same (green rows), the data is ordered alphabetically by last name.

9. Selecting Two Columns With a Complex Logical Condition in WHERE

This example will again demonstrate how to filter output using WHERE. It will be a bit more advanced this time, as we’ll use a logical operator. In SQL,  logical operators allow you to test if the filtering condition is true or not. They also allow you to set multiple conditions.

The three basic logical operators in SQL are AND, OR, and NOT . In the query below, we’ll  use OR to get salaries below 3,000 or above 5,000.

We use this query to select the employee’s first name, last name, and salary from the table employees .

However, we want to show only those employees whose salaries are either above $5,000 or below $3,000. We do that by using the logical operator OR and the comparison operators in WHERE .

We write the first condition in WHERE , where we reference the salary column and set the condition that the values must be above 5,000. Then we use the OR operator, followed by the second condition. The second condition again references the salary column and uses the ‘less than’ operator to return the values below 3,000.

The query returns only three employees and their salaries, as they are the only ones that satisfy the conditions.

10. Simple Computations on Columns

In this example, we’ll show how you can perform simple mathematical operations on the table’s columns.

We’ll use one of SQL’s arithmetic operators.

In the above query, we want to find the sales in the first half of 2022 for each employee.

We do it by first selecting the column employee_id from the table quarterly_sales .

Then we select the column q1_2022 and use the addition arithmetic operator to add the q2_2022 column. We also give this new calculated column an alias of h1_2022 using the AS keyword.

The output shows all the employees’ IDs and their respective sales in the first half of 2022.

11. Using SUM() and GROUP BY

This query uses the aggregate function SUM() with GROUP BY . In SQL, aggregate functions work on groups of data; for example, SUM(sales) shows the total of all the values in the sales column.  It’s useful to know about this function when you want to put data into groups and show the total for each group.

The purpose of the above query is to find the total salary amount for each department. This is achieved in the following way.

First, select the column department from the table employees . Then, use the SUM() function. As we want to add the salary values, we specify the column salary in the function. Also, we give this calculated column the alias total_salaries .

Finally, the output is grouped by the column department.

Note: Any non-aggregated column appearing in SELECT must also appear in GROUP BY . But this is logical – the whole purpose is to group data by department, so of course we’ll put it in GROUP BY .

The output shows all the departments and the sum of total monthly salary costs by department.

12. Using COUNT() and GROUP BY

Here’s another basic SQL query that uses an aggregate function. This time, it’s COUNT() . You can use it if you want to group data and show the number of occurrences in each group.

We want to show the number of employees by department.

Select the department from the table employees . Then, use the COUNT() aggregate function. In this case, we use the COUNT(*) version, which counts all the rows. We give the column the alias employees_by_department .

As a final step, we group the output by the department.

Note: COUNT(*) counts all the rows, including those with the NULL values. If you don’t want to include the possible NULL values in your output, use the COUNT(column_name) version of the function. We can use COUNT(*) here because we know no NULL values are in the table.

There are two departments, each with five employees.

13. Using AVG() and GROUP BY

The AVG() function calculates the average value. You can use this query whenever you want to group data and show the average value for each group.

The query is the same as the last one, only this time we use the AVG() function, as we want to calculate the average salary by department.

We select the department, use AVG() with the salary column, and group the output by department.

The output shows two departments and their average salaries.

14. Using MIN() and GROUP BY

This is another query that combines an aggregate function with GROUP BY . Use it whenever you want to find the minimum values for each group.

Again, we use the same query and change only the aggregate function.

The query calculates the minimum salary by department.

The output shows the departments and the lowest salary in each department.

15. Using MAX() and GROUP BY

This example shows how to use the MAX() aggregate function to show the highest value within each group.

We use the query to show the highest salary in each department, together with the department’s name.

You already know how this works. The query is the same as in the previous example, but now it uses the MAX() function.

The output shows us the highest salaries in the Corporate and Private Individuals department.

16. Using SUM(), WHERE, and GROUP BY

This one might seem more complicated, but it’s still a basic SQL query. It is used when you want to show the total values for each group but you want to include only specific rows in the sum.

The query will show the total salary by department, but it will include only individual salaries above $3,500 in the sum. Here’s how it works.

First, of course, select the departments and use SUM() with the salary column from the table employees . You learned that already.

Then use the WHERE clause to specify the values you want included in the sum. In this case, it’s where the column salary is higher than 3,500. In other words, the query will now sum only values above 3,500.

Finally, group by department.

These totals now include only salaries above $3,500. Compare this to the output from the eleventh example (shown below; mind the different sorting), and you’ll see that the totals are lower. It’s logical, as the below output also includes salaries equal to or less than $3,500.

17. Using COUNT(), WHERE, and GROUP BY

This is also one of the queries we advise you to include in your SQL toolbox. It’s similar to the previous one, as it uses an aggregate function. This type of query can be used when you want to show the number of occurrences for each group.

This is similar to the previous query, only it uses the COUNT() aggregate function. Its goal is to show the department name and the number of employees in that department, but it counts only the employees with a salary above $3,500.

To achieve that, first select the department. Then use COUNT(*) to count all the rows within each department. Each row equals one employee. We are free to use this version of the COUNT() function because we know there are no NULL rows.

Now, use WHERE to include only employees with salaries higher than $3500 in the counting.

In the end, you only need to group data by department.

The output shows there are three employees in the Private Individuals department paid above $3,500 and there are four such employees in the Corporate department.

Some employees are obviously missing, as they should be. We learned in one of the previous examples that there are five employees in each department.

18. Accessing Data in Two Tables Using INNER JOIN

This type of query is used whenever you want to access data from two or more tables. We’ll show you INNER JOIN , but it’s not the only join type you can use.

Here’s a short overview of join types in SQL. These are the full join names. What’s shown in the brackets can be omitted in the query and the join will work without it.

This query wants to show each employee’s ID and name, together with their total sales in 2022.

For that, it uses JOIN , as the required data is in both tables of our dataset.

Let’s start explaining the query with the FROM clause. This is familiar: to use the data from the table employees , you need to reference it in FROM . We also give this table an alias (‘e’), so that we don’t have to write the table’s full name later on.

After that, we use the JOIN keyword to join the second table. We do that by referencing the table quarterly_sales in JOIN and giving it the alias ‘qs’.

Now comes the ON condition. It is used to specify the columns on which the two tables will be joined. Usually, those are the columns that store the same data in both tables. In other words, we join the tables on the primary and foreign keys. A primary key is a column (or columns) that uniquely defines each row in the table. A foreign key is a column in the second table that refers to the first table. In our example, the column id from the table employees is its primary key. The column employee_id from the table quarterly_sales is the foreign key, as it contains the value of the column id from the first table.

So we’ll use these columns in ON , but we also need to specify which table each column is from. Remember, we gave our tables aliases. This will come in handy here, as we won’t need to write the tables’ full names – only one letter for each table. We write the first table’s alias (instead of its full name), separate them with a dot, and then the column name. We put the equal sign, the second table’s alias, and the column name.

Now that we have two tables joined, we are free to select any column from both tables.  We select id , first_name , and last_name from employees . Then we add each column from the table quarterly_sales showing the quarterly sales and name it total_sales_2022 . Each column in SELECT also has the table alias before it, with the alias and the column name separated by a dot.

Note: When joining tables, using the table names in front of the column names in SELECT is advisable. This will make it easier to determine which column comes from which table. Also, the tables can have columns of the same name. However,  table names can become wordy, so giving them aliases in JOIN is also advisable. That way, you can use much shorter aliases (instead of the full table names) in front of the column names.

The output lists each employee and shows their total sales in 2022.

19. Accessing Data in Two Tables Using INNER JOIN and Filtering Using WHERE

Of course, you can filter data in joined tables the same way as you can with only one table. You’ll again need the WHERE clause.

We tweaked the previous query to show the decrease in sales between the third and the fourth quarter.

Here’s how we did it. Just as we did earlier, we selected the employee’s ID and name.

We subtracted one quarter from another to calculate the change between the quarters. In this case, it’s the column with the fourth quarter sales minus the third quarter sales. This new column is named sales_change .

The tables are joined exactly the same way as in the previous example.

To show only the sales decrease, we use the WHERE clause. In it, we again subtract the third quarter from the fourth and set the condition that the result has to be below zero, i.e. a decrease. As you noticed, WHERE comes after the tables are joined.

The output shows all the employees who had a sales decrease in the last quarter and the amount of that decrease.

20. Accessing Data in Two Tables Using INNER JOIN, Filtering Using WHERE, and Sorting With ORDER BY

You probably noticed that outputs in our two latest examples are sorted a bit randomly. This is not something you have to put up with – you can order data with ORDER BY even when using two tables.

The query is not much different from the previous one. We again select the employee’s ID and name. We also add the sales in the last quarter of the year. The tables are then joined the same way as earlier. We use the WHERE clause to show only quarterly sales above $5,000.

Also, we want to sort the output. This is not different from what we learned earlier: simply write the column name in ORDER BY and sort it the way you want. In our example, we are sorting from the highest to the lowest quarterly sales.

The output shows all five employees whose sales were above $5,000 in the last three months of 2022.

If you want to master SQL, you must be comfortable using these 20 basic SQL queries. These are the fundamentals that will allow you to build solid SQL knowledge.

This kind of knowledge is achieved by a lot of practice and experience. In other words, you simply need to write the queries on your own. That way, you’ll consolidate all the concepts you learned here. Along the way, you’ll probably make a lot of mistakes. This is desirable, as there’s no better way of learning than trying to correct your own mistakes.

You’ll need lots of query examples for that. No, there’s no need to make your own examples, like we did here. You can if you want. But we already did that for you in our SQL Basics course.

It’s brimming with basic SQL query examples! Try it, and we’re sure you won’t regret it!

You may also like

sql assignment for school

How Do You Write a SELECT Statement in SQL?

sql assignment for school

What Is a Foreign Key in SQL?

sql assignment for school

Enumerate and Explain All the Basic Elements of an SQL Query

IMAGES

  1. SQL Assignment 1 With Solution

    sql assignment for school

  2. SQL Assignment 2.doc

    sql assignment for school

  3. Solved PL/SQL Assignment-1 Instructions 1. For each table,

    sql assignment for school

  4. SQL Practice Problems(3)

    sql assignment for school

  5. SQL-Assignment 3

    sql assignment for school

  6. SQL Assignment

    sql assignment for school

VIDEO

  1. SQL (Structured Query Language) Class13

  2. School Management System C# and SQL Server

  3. All Courses Schedules

  4. #MS SQL & TSQL #Training #sqlschool

  5. SQL with Oracle 10g XE #1 Creating Student Table

  6. #short #sqlschool #SQL #AzureDataEngineer #PowerBI New batch alert @ March 3, 2024

COMMENTS

  1. SQL Exercises

    Exercises. We have gathered a variety of SQL exercises (with answers) for each SQL Chapter. Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong.

  2. SQL Practice for Students: 11 Exercises with Solutions

    11 Basic SQL Practice Exercises. Exercise 1: List All Students. Exercise 2: List All Student Names. Exercise 3: Select a Specific Lecturer by ID. Exercise 4: Select Students by Last Name. Exercise 5: Select Students Whose Last Name Starts with D. Exercise 6: Use Multiple Conditions to Select an Academic Semester.

  3. SQL Exercises

    SQL (Structured Query Language) is a powerful tool used for managing and manipulating relational databases.Whether we are beginners or experienced professionals, practicing SQL exercises is essential for our skills and language mastery. In this article, we'll cover a series of SQL practice exercises covering a wide range of topics suitable for beginners, intermediate, and advanced learners.

  4. 10 Beginner SQL Practice Exercises With Solutions

    Speaking of practice, let's start with our exercises! The Dataset. Exercise 1: Selecting All Columns From a Table. Exercise 2: Selecting a Few Columns From a Table. Exercise 3: Selecting a Few Columns and Filtering Numeric Data in WHERE. Exercise 4: Selecting a Few Columns and Filtering Text Data in WHERE.

  5. Basic SQL Query Practice Online: 20 Exercises for Beginners

    SQL Query Practice. Dataset. Exercise #1: Show the Final Dates of All Events and the Wind Points. Exercise #2: Show All Finals Where the Wind Was Above .5 Points. Exercise #3: Show All Data for All Marathons. Exercise #4: Show All Final Results for Non-Placing Runners. Exercise #5: Show All the Result Data for Non-Starting Runners.

  6. Free SQL exercises

    Use an inner join to link two tables together in a query. Create an inner join in a query, then change it to an outer join to show categories having no events. Join two tables together in SQL, using alias table names. Link the continent, country and event tables with inner joins, and then filter by fields from 2 tables.

  7. Intro to SQL: Querying and managing data

    Learn how to use SQL to store, query, and manipulate data. SQL is a special-purpose programming language designed for managing data in a relational database, and is used by a huge number of apps and organizations.

  8. Learn SQL: Practice SQL Queries

    Learn SQL: Practice SQL Queries. Today is the day for SQL practice #1. In this series, so far, we've covered most important SQL commands ( CREATE DATABASE & CREATE TABLE, INSERT, SELECT) and some concepts ( primary key, foreign key) and theory ( stored procedures, user-defined functions, views ). Now it's time to discuss some interesting ...

  9. Practice Projects in SQL

    Practice Project Building an Inventory Database with PostgreSQL SQL • Computer Science • Data Science This project is an overview of all material covered in the PostgreSQL constraints lesson and asks learners to apply different datatypes, nullability constraints, check constraints, unique constraints, and primary and foreign key constraints on new and existing tables.

  10. SQL Exercises, Practice, Solution

    What is SQL? SQL stands for Structured Query Language and it is an ANSI standard computer language for accessing and manipulating database systems. It is used for managing data in relational database management system which stores data in the form of tables and relationship between data is also stored in the form of tables. SQL statements are ...

  11. Twenty-five SQL practice exercises

    Introduction. S tructured query language (SQL) is used to retrieve and manipulate data stored in relational databases. Gaining working proficiency in SQL is an important prerequisite for many technology jobs and requires a bit of practice. To complement SQL training resources ( PGExercises, LeetCode, HackerRank, Mode) available on the web, I ...

  12. Practice Basic SQL Commands

    Basic SQL Practice Grounds. You're through the basics of SQL! This is a great place to stop and get more practice on what you've learned so far. Here we've constructed a list of challenges to give you that practice. Take some time to go through these before moving on to the Mid-Level SQL section. A few things to keep in mind when going ...

  13. Exercise v3.0

    SQL Join . Exercise 1 Exercise 2 Exercise 3 Go to SQL Join Tutorial. SQL Group By . Exercise 1 Exercise 2 Go to SQL Group By Tutorial. SQL Database . Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5 Exercise 6 Exercise 7 Go to SQL Database Tutorial.

  14. 18 SQL Questions for Beginners: Theory and Practice

    Single Table Queries. Question 1: Elements of an SQL Query. Question 2: Filtering Data in an SQL Query. Data for Questions 3 - 6. Question 3: Select Cats of a Given Age and Breed. Question 4: List Cats Whose Favorite Toy Is a Ball. Question 5: Find the Most Bored Cat.

  15. CS50's Introduction to Databases with SQL

    Welcome. This is CS50's introduction to databases using a language called SQL. Learn how to create, read, update, and delete data with relational databases, which store data in rows and columns. Learn how to model real-world entities and relationships among them using tables with appropriate types, triggers, and constraints.

  16. Solve SQL

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  17. MySQL Exercises

    Start MySQL Exercises. Good luck! If you don't know MySQL, we suggest that you read our MySQL Tutorial from scratch. Track your progress - it's free! Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  18. SCHOOL MANAGEMENT SYSTEM DATABASE PROJECT (SQL)

    1. April 30th, 2021. Database management system plays a major role in holding, securing, storing and managing data. For this school database, we will be able to store information digitally. The ...

  19. sql

    Need schema for school grading system. I'm new to SQL and am attempting to create a DB schema usable with Hibernate but am worried about scaling issues, data access and best way to query data. Project: School grading system. Background: Want to store all assignments, but if we project a school having 4000 students each with ~182 days of class.

  20. Fun Last-Day-of-School Activities to Wrap Up the Year

    Grades: K-2. End of the Year Memory Book {Not Grade Specific} by Michael Friermood - The Thinker Builder. Grades: 2-6. END OF YEAR ESL Memory Book Activities PRINT and EASEL by Diana Bailey. Grades: 5-8. End of the Year Writing Activities and Memory Book EDITABLE Distance Learning by Tracee Orman. Grades: 7-12.

  21. SQL Tryit Editor v1.6

    Click "Run SQL" to execute the SQL statement above. W3Schools has created an SQL database in your browser. The menu to the right displays the database, and will reflect any changes. Feel free to experiment with any SQL statement. You can restore the database at any time. The Try-SQL Editor.

  22. Hitler-themed assignment at Atlanta private school asked students to

    An Adolf Hitler-themed question-and-answer assignment given to students at a private school in Atlanta has sparked outrage among parents over its suspected antisemitic nature. Eighth-grade ...

  23. 6 ways to use Microsoft Copilot for end-of-school-year tasks

    Give it a try. 2. Write end-of-school-year reflections. Educators often write end-of-school-year newsletters for families, update class blogs with a final post, and draft reflections on school year goals. Copilot can assist with all these tasks and can help you create personalized, engaging visuals for your content.

  24. SQL for Data Analysis: 15 Practical Exercises with Solutions

    Store Database Overview. Data Analysis SQL Exercises. Single Table Queries. Exercise 1: All Products. Exercise 2: Products with the Unit Price Greater Than 3.5. Exercise 3: Products with Specific Conditions for Category and Price. JOIN Queries. Exercise 4: Products and Categories. Exercise 5: Purchases and Products.

  25. Kodai Senga 'making some strides' but no date yet for rehab assignment

    Senga will need about a month of buildup in the minor leagues, once he begins his rehab assignment, before he can join the Mets' rotation. Team owner Steve Cohen told SNY he still believes in ...

  26. Ga. school issues statement after controversial Hitler assignment

    Published: May. 16, 2024 at 5:13 AM PDT | Updated: moments ago. ATLANTA, Ga. (Atlanta News First) - A metro Atlanta school is responding to backlash to a controversial assignment. Parents are ...

  27. PDF This document was created by Dr. Jennifer Bratyanski of Providence Day

    This document was created by Dr. Jennifer Bratyanski of Providence Day School as part of the 2023-2024 UNC World View Global Fellows Program. For more information about the program, please visit ... Annotated Bibliography Assignment Template Assign a number of primary sources for your students to research: information from the era of your topic.

  28. SQL Joins: 12 Practice Questions with Detailed Answers

    Yes, SQL joins allow for joining more than two tables. We'll see how to do that in this part of the SQL joins practice. You can find a more detailed explanation of multiple joins here. We also need a new dataset, so let's introduce it. Dataset 2. The first table in the dataset is department. Its columns are: id - The unique ID of the ...

  29. Court rejects parents' attempt to opt kids out of LGBTQ ...

    A federal appeals court rejected a bid from a group of Maryland parents to require Montgomery County Public Schools to allow them to opt their children out of lessons that involve LGBTQ-inclusive ...

  30. 20 Basic SQL Query Examples for Beginners

    Output. 20. Accessing Data in Two Tables Using INNER JOIN, Filtering Using WHERE, and Sorting With ORDER BY. Query. Explanation. Output. From Basic SQL Queries to SQL Master. These 20 basic queries are a must in a starter pack for every SQL beginner. These examples will get you going on your journey to mastering SQL.