• 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

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.

  • 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)

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

Revising the select query ii easy sql (basic) max score: 10 success rate: 98.69%, select all easy sql (basic) max score: 10 success rate: 99.55%, 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.60%, japanese cities' names easy sql (basic) max score: 10 success rate: 99.54%, weather observation station 1 easy sql (basic) max score: 15 success rate: 99.43%, weather observation station 3 easy sql (basic) max score: 10 success rate: 97.98%, weather observation station 4 easy sql (basic) max score: 10 success rate: 98.73%, weather observation station 5 easy sql (intermediate) max score: 30 success rate: 94.33%.

SQL & Databases: Download Practice Datasets

Published by SuperDataScience Team

Welcome to the data repository for the SQL Databases course by Kirill Eremenko and Ilya Eremenko. The datasets and other supplementary materials are below. Enjoy!

Section 1: Introduction

  • No dataset required

Section 2: It's Super Easy to Get Started

Section 3: preparation.

  • Section 3 – The Challenge
  • Section 3 – PostgreSQL Upload Code
  • Section 3 – MS SQL Upload Code
  • Consumer Complaints (csv file 14.7 MB)
  • Consumer Complaints (zip file 2.5 MB)
  • Data Source: http://www.consumerfinance.gov/data-research/consumer-complaints/

Section 4: Basics of SQL

  • Here we will continue working with the Dataset from the previous section.

Section 5: Working with Data

  • Section 5 The Challenge
  • Section 5 – PostgreSQL Upload Code
  • Section 5 – MS SQL Upload Code
  • Console Games Sales
  • Console Dates

Section 6: Fundamentals of Database Theory

  • Will be added soon.

Section 7: Joining Tables in SQL

  • Section 7 – The Challenge
  • Section 7 – PostgreSQL Upload Code
  • Section 7 – MS SQL Upload Code
  • Procedures History (Updated)
  • Procedures Details

Section 8: Creating Tables in SQL

Section 9: database design.

  • Section 9 – The Challenge
  • Section 9 – PostgreSQL Upload Code
  • Section 9 – MS SQL Upload Code
  • Online Store Sales (OLTP database example)

20 Basic SQL Query Examples for Beginners: A Complete Overview

Author's photo

  • sql queries

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:

What Is SQL?

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 .

Explanation

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.

From Basic SQL Queries to SQL Master

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

SQL Tutorial

Sql database, sql references, sql examples, sql insert into statement, the sql insert into statement.

The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted:

INSERT INTO table_name ( column1 , column2 , column3 , ...) VALUES ( value1 , value2 , value3 , ...);

2. If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query. However, make sure the order of the values is in the same order as the columns in the table. Here, the INSERT INTO syntax would be as follows:

INSERT INTO table_name VALUES ( value1 , value2 , value3 , ...);

Demo Database

Below is a selection from the Customers table used in the examples:

Advertisement

INSERT INTO Example

The following SQL statement inserts a new record in the "Customers" table:

The selection from the "Customers" table will now look like this:

Did you notice that we did not insert any number into the CustomerID field? The CustomerID column is an auto-increment field and will be generated automatically when a new record is inserted into the table.

Insert Data Only in Specified Columns

It is also possible to only insert data in specific columns.

The following SQL statement will insert a new record, but only insert data in the "CustomerName", "City", and "Country" columns (CustomerID will be updated automatically):

Insert Multiple Rows

It is also possible to insert multiple rows in one statement.

To insert multiple rows of data, we use the same INSERT INTO statement, but with multiple values:

Make sure you separate each set of values with a comma , .

Test Yourself With Exercises

Insert a new record in the Customers table.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. SQL-Assignment 3

    sql assignment for school

  2. SQL Assignment Answers

    sql assignment for school

  3. Solved: SQL Assignment Use The W3School's Sample Database ...

    sql assignment for school

  4. SQL Assignment 1 With Solution

    sql assignment for school

  5. (DOC) SQL Programming Assignment 3 (DDL& DML

    sql assignment for school

  6. sql assignment 1

    sql assignment for school

VIDEO

  1. Intro for SQL course

  2. SQL Introduction

  3. SQL (Structured Query Language) Class13

  4. Lecture

  5. SQL Live Session

  6. #MS SQL & TSQL #Training from #sqlschool

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. Count Your Score You will get 1 point for each correct answer.

  2. SQL Practice for Students: 11 Basic SQL Practice Exercises with Solutions

    online practice Calling all students! Are you SQL-curious? Want to learn or improve your SQL skills? This article has 11 SQL practice exercises with detailed solutions. Have you ever heard that "Practice makes perfect"? You probably have - that's why you're looking for SQL practice resources.

  3. SQL Exercises, Practice, Solution

    Happy Coding! You may read our SQL tutorial before solving the following exercises. List of SQL Exercises SQL Retrieve data from tables [33 Exercises] SQL Boolean and Relational operators [12 Exercises] SQL Wildcard and Special operators [22 Exercises] SQL Aggregate Functions [25 Exercises] SQL Formatting query output [10 Exercises]

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

    Tihomir Babic sql practice sql basics These 20 exercises are just what beginners need for SQL query practice. Try to solve each of them, and then look at the solutions. If something needs to be clarified, there are explanations for each solution. In this article, there'll be less talking than usual.

  5. 10 Beginner SQL Practice Exercises With Solutions

    online practice sql practice Solve these ten SQL practice problems and test where you stand with your SQL knowledge! This article is all about SQL practice. It's the best way to learn SQL. We show you ten SQL practice exercises where you need to apply essential SQL concepts.

  6. 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 ...

  7. Intro to SQL: Querying and managing 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. SQL basics We'll show you the basics of creating tables and selecting data in various different ways. Learn Welcome to SQL Creating a table and inserting data Challenge: Book list database

  8. Twenty-five SQL practice exercises

    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've compiled a list of my favorite questions that you can tackle by hand or solve with a PostgreSQL instance.

  9. Free SQL exercises

    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. Use inner joins to link four tables to show Dr Who enemies by author.

  10. Learn SQL

    What is SQL? SQL (Structured Query Language) is a programming language used to manage data stored in relational databases, which store structured data in tables. Its syntax is easy to read, so it's easy to pick up on even if you're completely new to programming, and it's even useful for non-technical careers.

  11. Solve SQL

    Prepare SQL SQL Revising the Select Query I EasySQL (Basic)Max Score: 10Success Rate: 95.98% Solve Challenge Revising the Select Query II EasySQL (Basic)Max Score: 10Success Rate: 98.69% Solve Challenge Select All EasySQL (Basic)Max Score: 10Success Rate: 99.55% Solve Challenge Select By ID EasySQL (Basic)Max Score: 10Success Rate: 99.66%

  12. SQL & Databases: Download Practice Datasets

    Welcome to the data repository for the SQL Databases course by Kirill Eremenko and Ilya Eremenko. The datasets and other supplementary materials are below. Enjoy! Section 1: Introduction. No dataset required; Section 2: It's Super Easy to Get Started. No dataset required;

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

    In this article, we'll improve our SQL skills through 15 practical, hands-on exercises designed specifically for beginners. Because when it comes to SQL, practice truly makes perfect! We're going to shine a spotlight on the critical domain of data analysis, where SQL takes center stage.

  14. SQL Programming Study Resources

    Find sQL Programming course notes, answered questions, and sQL Programming tutors 24/7. AI Homework Help. Expert Help. Study Resources. Log in Join ... SQL Programming Assignment. School: New York University . Course: Database Systems 31 Pages. Oracle SQL; Register Now; Oracle SQL. School ...

  15. Best SQL Courses Online with Certificates [2024]

    In summary, here are 10 of our most popular sql courses. Databases and SQL for Data Science with Python: IBM. Learn SQL Basics for Data Science: University of California, Davis. SQL for Data Science: University of California, Davis. Google Data Analytics: Google. SQL: A Practical Introduction for Querying Databases: IBM.

  16. Exercise v3.0

    Show Answer. Hide Answer. Go to w3schools.com. Reset Score. Close This Menu. SQL Select. Exercise 1 Exercise 2 Exercise 3 Go to SQL Select Tutorial. SQL Where. Exercise 1 Exercise 2 Go to SQL Where Tutorial.

  17. SQL Tutorial

    SQL is a standard language for storing, manipulating and retrieving data in databases. Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other database systems. Start learning SQL now ».

  18. SQL Introduction

    What Can SQL do? SQL can execute queries against a database. SQL can retrieve data from a database. SQL can insert records in a database. SQL can update records in a database. SQL can delete records from a database. SQL can create new databases. SQL can create new tables in a database. SQL can create stored procedures in a database.

  19. PDF Sql Practical Assignment

    Step 1: Open MySQL, Open Database and create table as: CREATE TABLE Student ( StdID INT(4) PRIMARY KEY, StdName VARCHAR(30) NOT NULL, Sex VARCHAR(1), Percentage DECIMAL(5,2), SClass INT , Sec VARCHAR(1), Stream VARCHAR(10), DOB DATE ); Step 2: Press Enter key to complete create table: Step 3: Insert records into STUDENT table.

  20. SCHOOL MANAGEMENT SYSTEM DATABASE PROJECT (SQL)

    SCHOOL MANAGEMENT SYSTEM DATABASE PROJECT (SQL) Fatimah Alanazi · Follow 7 min read · Oct 6, 2022 April 30th, 2021 Database management system plays a major role in holding, securing, storing...

  21. 20 Basic SQL Query Examples for Beginners: A Complete Overview

    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 ...

  22. Oregon (OSAA) wrestling state championships: Meet the 12 'unbeatable

    One of my first big assignments as a sportswriter was covering Mat Classic, the wrestling extravaganza that is Washington's high school state championships.. Nothing could quite prepare me for the moment I walked into the press area at the Tacoma Dome and was awash in the sights and sounds — the sensory overload that overcomes you upon first experiencing it.

  23. SQL Operators

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  24. SQL INSERT INTO Statement

    INSERT INTO Syntax. It is possible to write the INSERT INTO statement in two ways: 1. Specify both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...); 2. If you are adding values for all the columns of the table, you do not need to specify the column names ...