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

SQL Tutorial

Sql database, sql references, sql examples, sql exercises.

You can test your SQL skills with W3Schools' 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. Your score and total score will always be displayed.

Start SQL Exercises

Start SQL Exercises ❯

If you don't know SQL, we suggest that you read our SQL Tutorial from scratch.

Kickstart your career

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Mastering Database Assignments: Your Comprehensive Guide

Navigating Database Assignments: A Step-by-Step Guide for Success

David Rodriguez

Embarking on the journey of database assignments is a dynamic venture that presents both challenges and rewards. Regardless of whether you find yourself navigating the academic realm as a student or seeking to elevate your professional expertise, this comprehensive guide serves as an invaluable companion throughout the entire process. From laying the groundwork by understanding fundamental concepts to the practical application of UML diagrams in database design, this guide is crafted to provide a seamless and insightful experience. As you progress, the guide will aid in deciphering complex assignment instructions, establishing a strategic framework, and delving into the principles of database design. With a spotlight on essential aspects like normalization techniques and relationship mapping, you'll gain a nuanced understanding of structuring databases for optimal performance. The journey further unfolds into the practical implementation phase, where you'll delve into the intricacies of writing SQL queries and employing data modeling techniques with tools like MySQL Workbench. The guide extends its support into troubleshooting common issues and optimizing database performance, ensuring a well-rounded comprehension of the entire database assignment landscape. Testing and validation, crucial components of the process, are explored extensively, emphasizing rigorous testing protocols and the importance of user feedback for iterative improvement. Whether you're a novice seeking to grasp the basics or a seasoned professional aiming to refine your skills, this guide is tailored to offer actionable insights and tips at each juncture. As you navigate the intricate world of database assignments, this guide stands as a beacon, illuminating the path to success with its comprehensive approach, ensuring that you emerge well-equipped and confident in your ability to tackle any database assignment that comes your way.

Navigating Database Assignments

The guide encourages a proactive mindset, fostering an understanding that every database assignment is an opportunity for growth and skill refinement. It recognizes the importance of aligning theoretical knowledge with practical implementation, emphasizing the mastery of SQL queries, data modeling techniques, and troubleshooting strategies. By unraveling the complexities of common issues that may arise during assignments, such as schema errors and performance challenges, the guide empowers you to approach problem-solving with confidence and precision. Furthermore, it underscores the significance of performance optimization strategies, from indexing to query optimization, ensuring that your database not only meets the assignment requirements but operates at peak efficiency. As the journey concludes, the focus shifts to testing and validation, guiding you through a comprehensive testing strategy that encompasses unit testing, integration testing, and validation against real-world scenarios. The iterative improvement process is highlighted, recognizing the value of user feedback in refining your database design to meet evolving requirements.

Are you struggling to solve your Database homework ? This guide encapsulates the entire spectrum of navigating database assignments. Whether you are entering this realm with curiosity or experience, the guide serves as a reliable companion, providing practical wisdom and insights that transcend the theoretical. By the time you reach the conclusion, you'll find yourself well-versed in the intricacies of database assignments, armed with the knowledge to tackle challenges and contribute meaningfully to the dynamic field of database management. The journey, though demanding, is undeniably rewarding, and this comprehensive guide ensures that you traverse it with competence, resilience, and a deep understanding of the intricate world of databases.

Understanding the Basics

Before embarking on database assignments, establishing a robust foundation in database fundamentals is imperative. This involves delving into essential concepts like data models, relational databases, and normalization. A thorough grasp of these fundamentals not only facilitates a deeper understanding of database structures but also serves as the cornerstone for successful assignment completion. Additionally, recognizing the pivotal role of Unified Modeling Language (UML) diagrams is essential in the realm of database assignments. These diagrams, particularly entity-relationship diagrams (ERDs), hold significant weight in visualizing and conceptualizing database structures. Learning to create UML diagrams enables effective communication of database designs and contributes to a clearer representation of relationships among data entities. In essence, the synergy between comprehending database fundamentals and harnessing the power of UML diagrams sets the stage for a more informed and structured approach to tackling intricate database assignments.

Moreover, a nuanced understanding of data models lays the groundwork for effective communication between stakeholders involved in the assignment process. By comprehending the intricacies of relational databases, individuals can navigate the complexities of data storage and retrieval, essential components of any successful database assignment. The significance of normalization, a process to eliminate data redundancy and ensure data integrity, cannot be overstated. It establishes the guidelines for organizing data efficiently, contributing to the overall effectiveness of a database system.

Simultaneously, delving into the importance of UML diagrams unveils a visual language that transcends the limitations of text-based explanations. ERDs, a specific type of UML diagram, provide a graphical representation of entities and their relationships, offering a holistic view of the database structure. Proficiency in creating UML diagrams empowers individuals to convey complex database designs in a comprehensible manner, fostering collaboration and understanding among team members.

Analyzing Assignment Requirements

Embarking on a database assignment demands the twin capabilities of decoding assignment instructions and establishing a robust framework, both integral to ensuring triumph in the intricate landscape of database design. In the decoding phase, a meticulous breakdown of instructions is paramount – an analytical dissection where key requirements, constraints, and objectives are identified. This process, akin to deciphering a complex code, is the keystone for comprehending the assignment's scope, laying the foundation for subsequent strategic decisions. Simultaneously, the establishment of a framework involves the creation of a comprehensive roadmap. This entails defining the assignment's scope, functionalities, and data entities, fostering a structured approach that transforms the assignment into a navigable journey. These dual processes, decoding and establishing, synergistically shape the entire trajectory of the database assignment, guaranteeing not just completion, but success through clarity, coherence, and operational efficiency in every phase of the intricate database design process

Beyond being procedural necessities, decoding assignment instructions and establishing a framework serve as proactive measures that significantly impact the overall quality of the database solution. By meticulously decoding instructions, one gains a nuanced understanding of the assignment's nuances, fostering an awareness that goes beyond the surface requirements. This depth of comprehension becomes the fulcrum upon which creative and innovative solutions can be built. Similarly, the framework-setting phase is not merely a logistical exercise; it is a strategic endeavor that shapes the assignment's trajectory. The defined scope becomes a boundary for creativity, functionalities are crafted with purpose, and data entities are chosen with foresight. This intentional approach ensures that every subsequent step aligns with the overarching objectives, preventing missteps and ensuring a cohesive, well-integrated database design.

Moreover, the iterative nature of these processes becomes apparent as the assignment progresses. As challenges emerge, the initial decoding of instructions provides a reference point, enabling dynamic adjustments to the evolving understanding of the assignment. The established framework serves as a flexible guide, allowing for adaptations and refinements based on newfound insights or changing requirements. In essence, decoding instructions and establishing a framework are not isolated actions; they are continuous threads woven into the fabric of the entire database assignment lifecycle.

Database Design Principles

Delve into the critical aspects of database design with a focus on normalization techniques and relationship mapping. Normalization serves as a fundamental principle in eliminating data redundancy, promoting a well-organized database structure. In this section, gain insights into the various normal forms and learn how to apply them judiciously to enhance data integrity. Uncover the intricacies of relationship mapping, where you'll master the art of defining connections between entities. Understand the nuances of one-to-one, one-to-many, and many-to-many relationships, pivotal for designing a database that accurately mirrors real-world scenarios. This exploration ensures not only the efficiency of your database but also its alignment with the complexities of the environments it aims to represent.

As you navigate normalization, consider the journey towards a database that not only stores data but does so with optimal efficiency and accuracy. Normalization not only streamlines your data structure but also minimizes the chances of anomalies, ensuring that your database remains a reliable source of information. Additionally, the mastery of relationship mapping goes beyond theoretical knowledge, empowering you to translate real-world connections into a digital format seamlessly. By understanding the dynamics of different relationships, you pave the way for a database that not only functions well internally but also accurately represents the intricate web of connections found in diverse scenarios. This dual focus on normalization and relationship mapping is the cornerstone of building databases that stand the test of practical implementation and real-world demands.

Writing SQL Queries: Navigating the World of Structured Query Language (SQL)

Embark on an enriching journey into the dynamic realm of SQL (Structured Query Language), the heartbeat of seamless database interactions. This section serves as your comprehensive guide to mastering the intricacies of SQL, providing you with the adept skills needed to navigate databases with finesse. Beginning with the fundamentals of SELECT statements and advancing into the intricacies of JOIN operations, you will develop the proficiency required to retrieve and manipulate data with surgical precision. Beyond being a mere skill, SQL proficiency emerges as the bedrock of successful database management, bestowing upon you the power to unlock and leverage the full potential of data within your assignments. Embrace SQL mastery, and chart a course toward elevated excellence in the realm of database dynamics..

Data Modeling Techniques: Crafting Intuitive Database Designs

In this segment, we explore the art and science of practical data modeling techniques, transforming abstract ideas into tangible, well-designed databases. Employing tools such as MySQL Workbench or Oracle SQL Developer, you'll gain hands-on experience in visualizing your database architecture. Visualization is not only about creating aesthetically pleasing diagrams; it's a strategic approach to conceptualizing the relationships between data entities. As you delve into data modeling, you'll discover its pivotal role in ensuring your database design aligns seamlessly with user feedback and evolving project requirements. These techniques are the bedrock of creating databases that not only meet specifications but also adapt and evolve with the dynamic nature of real-world applications.

Troubleshooting and Optimization

Navigating the intricate realm of database assignments demands a meticulous understanding of potential challenges and the adept application of optimization strategies. Beyond merely identifying schema errors and performance bottlenecks, this section of the guide immerses you in a deeper exploration of solutions that go beyond the conventional. Gain insights into advanced indexing techniques that go beyond the basics, strategically enhancing the efficiency of your database. Uncover the art of query optimization, a nuanced skill that distinguishes a proficient database designer from the rest. By honing these techniques, you not only mitigate risks but also elevate the overall performance of your database to unprecedented levels.

This comprehensive approach not only addresses common issues but fosters a strategic mindset towards problem-solving. It emphasizes the symbiotic relationship between potential challenges and optimization, reinforcing your ability to design databases that stand resilient against the complexities of real-world scenarios. In mastering this segment, you not only troubleshoot effectively but cultivate an expertise that transcends the ordinary, positioning yourself as a proficient navigator in the ever-evolving landscape of database assignments.

Rigorous Testing Protocols

In the realm of database assignments, the significance of implementing rigorous testing protocols cannot be overstated. A robust testing strategy serves as the linchpin for ensuring the flawless functionality and unwavering reliability of your database. This involves a meticulous approach to various testing methodologies, including the critical steps of unit testing, where individual components are scrutinized for accuracy, integrity, and functionality. Integration testing becomes equally pivotal, examining the seamless interaction between different components to ensure their harmonious collaboration within the larger system. Yet, the testing journey doesn't conclude there; it extends to the validation against real-world scenarios, where the practical application of the database is scrutinized under diverse conditions. Each testing phase contributes to fortifying the database's resilience, identifying potential vulnerabilities, and refining its performance. In essence, a well-executed testing protocol is the bedrock upon which a robust and dependable database stands.

User Feedback and Iterative Improvement

The symbiotic relationship between user feedback and iterative improvement is a cornerstone in the evolutionary process of database assignments. Beyond the realms of coding and design, the incorporation of user perspectives and stakeholder insights becomes paramount. Gathering feedback from end-users provides invaluable insights into the usability and functionality of the database in real-world scenarios. This iterative approach extends beyond mere bug fixes; it entails a profound commitment to continuous improvement. Embracing a mindset that perceives each feedback loop as an opportunity for enhancement, database designers iterate on their designs accordingly. This iterative improvement process is not only about fixing issues but also about adapting to evolving requirements and expectations. It is a dynamic cycle where user feedback fuels design refinements, creating a symbiotic relationship that fosters an ever-improving user experience. In essence, the database becomes a living entity, evolving in response to the needs and experiences of those who interact with it.

In conclusion, successfully navigating the intricate landscape of database assignments demands a harmonious blend of theoretical acumen and hands-on practical skills. This step-by-step guide serves as a beacon, illuminating the path to confidently tackle assignments, thereby ensuring triumph in your ventures within the realm of databases. Offering a holistic perspective, this comprehensive guide delves into the depths of database assignments, guiding you seamlessly from the conceptualization phase to the intricacies of implementation.

Mastering the principles of database design is paramount in establishing a solid foundation for your assignments. It involves understanding data models, normalization techniques, and the art of relationship mapping. With these skills in your arsenal, you can create well-structured databases that accurately represent real-world scenarios, minimizing data redundancy and ensuring data integrity.

Equally important is the proficiency in SQL queries, a powerful language for interacting with databases. From crafting basic SELECT statements to executing complex JOIN operations, acquiring these skills empowers you to retrieve and manipulate data with precision. The guide further extends into the realm of practical implementation, introducing data modeling techniques using tools like MySQL Workbench or Oracle SQL Developer.

Troubleshooting and optimization strategies are indispensable components of the database journey. As you explore common issues and delve into performance optimization techniques, you gain the ability to identify and rectify challenges, ensuring the efficiency and responsiveness of your databases.

Testing and validation emerge as crucial steps in the database assignment lifecycle. Implementing rigorous testing protocols and soliciting user feedback allow you to refine and iterate on your designs. Embracing a continuous improvement mindset positions you to adapt to evolving requirements, contributing to a dynamic and resilient database system.

In essence, each assignment becomes more than a task—it transforms into an opportunity for skill refinement and meaningful contribution to the dynamic field of database management. Armed with this comprehensive guide, you not only navigate the complexities of database assignments but also elevate your academic and professional pursuits, leaving an indelible mark in the ever-evolving landscape of data management.

Post a comment...

Mastering database assignments: your comprehensive guide submit your homework, attached files.

  • 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
  • Course Material

Assignments

  • Piazza Q&A

CS 338: Computer Applications in Business: Databases

Note that the assignments are not going to be marked. We will provide the solutions and you are encoruaged to do them since they will help you check your understanding of the material, practice with the ideas, and prepare for the exams.

Assignment 1

This assignment will focus on basic SQL queries. You will write a number of SQL queries and execute them on DB2. Assignment 1 Assignment 1 Solution

Assignment 2

This assignment will focus on more advanced features of SQL . Again, you will write a number of SQL queries and execute them on DB2. Assignment 2 Solution

Assignment 3

This assignment is on conceptual and logical database design. You will be given a spec and asked to create an ER model, which you will then map to a relational model Assignment 3 Sample Solution

Assignment 4

This assignment will cover a number of topics: views, transactions, and query processing.
Assignment 4 Solution

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

Learn SQL practically and Get Certified .

Popular tutorials, learn sql interactively.

Learn Python practically and Get Certified .

Popular Examples

Introduction.

  • Getting Started with SQL

Introduction to Databases and SQL

Sql select(i).

  • SQL AND, OR, and NOT Operators
  • SQL SELECT DISTINCT
  • SQL SELECT AS Alias
  • SQL SELECT LIMIT, TOP, FETCH FIRST
  • SQL IN and NOT IN Operators
  • SQL BETWEEN Operator
  • SQL IS NULL and IS NOT NULL
  • SQL MAX() and MIN()
  • SQL COUNT()
  • SQL SUM() AND AVG()

SQL SELECT(II)

  • SQL ORDER BY Clause
  • SQL GROUP BY
  • SQL LIKE and NOT LIKE Operators
  • SQL Wildcards
  • SQL Subquery
  • SQL CTE (Common Table Expressions)
  • SQL ANY and ALL
  • SQL HAVING Clause
  • SQL EXISTS Operator
  • SQL INNER JOIN
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL FULL OUTER JOIN
  • SQL CROSS JOIN
  • SQL Self JOIN

SQL Database and Table

SQL CREATE DATABASE Statement

  • SQL CREATE TABLE

SQL DROP DATABASE Statement

  • SQL DROP TABLE Statement
  • SQL ALTER TABLE Statement
  • SQL BACKUP DATABASE Statement

SQL Insert, Update and Delete

  • SQL INSERT INTO
  • SQL SELECT INTO (Copy Table)
  • SQL INSERT INTO SELECT Statement
  • SQL DELETE and TRUNCATE
  • SQL Constraints
  • SQL NOT NULL Constraint
  • SQL UNIQUE Constraint
  • SQL PRIMARY KEY Constraint
  • SQL FOREIGN KEY Constraint
  • SQL CHECK Constraint
  • SQL DEFAULT Constraint
  • SQL CREATE INDEX
  • SQL Composite Key

SQL Additional Topics

  • SQL Comments
  • SQL Data Types
  • SQL Operators
  • SQL Date and Time
  • SQL JOIN Three Tables
  • SQL SUBSTRING()
  • SQL Commands
  • SQL REPLACE()
  • SQL Stored Procedures
  • SQL Injection

SQL Tutorials

SQL Commands: DDL, DML, DQL, DCL, TCL

In the previous tutorial you learnt to install SQL on your device. Now, let's learn about SQL and databases.

  • Introduction to Databases

A database is an organized collection of data.

  • Types of Databases

In general, there are two common types of databases:

  • Non-Relational
  • Non-Relational Database

In a non-relational database, data is stored in key-value pairs. For example:

How is data stored in non-relational database?

Here, customers' data are stored in key-value pairs.

Commonly used non-relational database management systems (Non-RDBMS) are MongoDB, Amazon DynamoDB, Redis, etc.

  • Relational Database

In a relational database, data is stored in tabular format. For example,

How is data stored in a relational database system?

Here, customers is a table inside the database.

The first row is the attributes of the table. Each row after that contains the data of a customer.

In a relational database, two or more tables may be related to each other. Hence the term " Relational ". For example,

Relationship between two tables in a relational database

Here, orders and customers are related through customer_id .

Commonly used relational database management systems (RDBMS) are MySQL, PostgreSQL, MSSQL, Oracle etc.

Note : To access data from these relational databases, SQL (Structured Query Language) is used.

  • Introduction to SQL

Structured Query Language (SQL) is a standard query language that is used to work with relational databases.

We use SQL to perform CRUD (create, read, update, and delete) operations on relational databases.

  • Create: create databases or tables in a database
  • Read: read data from a table
  • Update: insert or update data in a table
  • Delete: delete tables or databases
  • SQL Example: Read Data From a Table

Here, this SQL command selects the first name and last name of all customers from the Customers table using the SQL SELECT statement.

Example: SQL SELECT Statement

SQL is used in all relational databases such as MySQL, Oracle, MSSQL, PostgreSQL etc.

Note : The major SQL commands are similar in all relational databases. However, in some cases, SQL commands may differ.

In this SQL tutorial series, we will learn about SQL in detail. We will cover any SQL command differences among MySQL, Oracle, SQL Server, Postgres, and other commonly used database systems.

Table of Contents

Sorry about that.

Related Tutorials

Programming

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Database-level roles

  • 23 contributors

To easily manage the permissions in your databases, SQL Server provides several roles that are security principals that group other principals. They are like groups in the Microsoft Windows operating system. Database-level roles are database-wide in their permissions scope.

To add and remove users to a database role, use the ADD MEMBER and DROP MEMBER options of the ALTER ROLE statement. Analytics Platform System (PDW) and Azure Synapse Analytics doesn't support the use of ALTER ROLE . Use the older sp_addrolemember and sp_droprolemember procedures instead.

There are two types of database-level roles: fixed-database roles that are predefined in the database and user-defined database roles that you can create.

Fixed-database roles are defined at the database level and exist in each database. Members of the db_owner database role can manage fixed-database role membership. There are also some special-purpose database roles in the msdb database.

You can add any database account and other SQL Server roles into database-level roles.

Do not add user-defined database roles as members of fixed roles. This could enable unintended privilege escalation.

The permissions of user-defined database roles can be customized by using the GRANT , DENY , and REVOKE statements. For more information, see Permissions (Database Engine) .

For a list of all the permissions, see the Database Engine Permissions poster. Server-level permissions can't be granted to database roles. Logins and other server-level principals (such as server roles) can't be added to database roles. For server-level security in SQL Server, use server roles instead. Server-level permissions can't be granted through roles in Azure SQL Database and Azure Synapse Analytics.

Fixed-database roles

The following table shows the fixed-database roles and their capabilities. These roles exist in all databases. Except for the public database role, the permissions assigned to the fixed-database roles can't be changed.

The permissions assigned to the fixed-database roles can't be changed. The following figure shows the permissions assigned to the fixed-database roles:

fixed_database_role_permissions

Special roles for SQL Database and Azure Synapse

These database roles exist only in the virtual master database. Their permissions are restricted to actions performed in master . Only database users in master can be added to these roles. Logins can't be added to these roles, but users can be created based on logins and then those users can be added to the roles. Contained database users in master can also be added to these roles. However, contained database users added to the dbmanager role in master can't be used to create new databases.

The server-level principal and the Microsoft Entra administrator (if configured) have all permissions in SQL Database and Azure Synapse Analytics without needing to be members of any roles. For more information, see SQL Database Authentication and Authorization: Granting Access .

Some database roles aren't applicable to Azure SQL or Azure Synapse:

  • db_backupoperator isn't applicable in Azure SQL Database (not Azure SQL Managed Instance) and Azure Synapse Analytics serverless pool because backup and restore T-SQL commands aren't available.
  • db_datawriter and db_denydatawriter aren't applicable to Azure Synapse Analytics serverless because it just reads external data.

The msdb database contains the special-purpose roles that are shown in the following table.

Members of the db_ssisadmin role and the dc_admin role may be able to elevate their privileges to sysadmin. This elevation of privilege can occur because these roles can modify Integration Services packages and Integration Services packages can be executed by SQL Server using the sysadmin security context of SQL Server Agent. To guard against this elevation of privilege when running maintenance plans, data collection sets, and other Integration Services packages, configure SQL Server Agent jobs that run packages to use a proxy account with limited privileges or only add sysadmin members to the db_ssisadmin and dc_admin roles.

Working with database-level roles

The following table explains the commands, views, and functions for working with database-level roles.

Public database role

Every database user belongs to the public database role. When a user hasn't been granted or denied specific permissions on a securable object, the user inherits the permissions granted to public on that object. Database users can't be removed from the public role.

The examples in this section show how to work with database-level roles.

A. Adding a User to a database-level role

The following example adds the User 'Ben' to the fixed database-level role db_datareader .

B. Listing all database-principals that are members of a database-level role

The following statement returns all members of any database role.

Related content

  • Security Catalog Views (Transact-SQL)
  • Security Stored Procedures (Transact-SQL)
  • Security Functions (Transact-SQL)
  • Securing SQL Server
  • sp_helprotect (Transact-SQL)
  • Server roles in Azure SQL Database

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

BwireC/SQL-DATABASE-DESIGN-WEEK-4-ASSIGNMENT

Folders and files.

  • HTML 100.0%

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 database assignment

How Do You Write a SELECT Statement in SQL?

sql database assignment

What Is a Foreign Key in SQL?

sql database assignment

Enumerate and Explain All the Basic Elements of an SQL Query

IMAGES

  1. Creating a database in Microsoft SQL Server

    sql database assignment

  2. SQL Assignment

    sql database assignment

  3. SQL Assignment 2

    sql database assignment

  4. Create an Azure SQL Database with built-in sample data

    sql database assignment

  5. SQL Practice Problems

    sql database assignment

  6. SQL-assignment

    sql database assignment

VIDEO

  1. Deploy Database Projects Manually in Azure Data Studio

  2. SQL Tutorial

  3. NPTEL Introduction to Database Systems Week 4 Assignment February 2024

  4. ASSIGNMENT 1: SQL Basics

  5. Oracle Database 21c Tutorial: Step-by-Step Guide to Add Sample HR Schema

  6. Database and SQL assignment answer Infosys springboard #infosysspringboard #database #sql

COMMENTS

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

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

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

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

  5. How to Create Your Own Database to Practice SQL

    Practice SQL on Your Own Database! So, there you have it! Your own SQL database setup for practice is not only possible but incredibly beneficial. You get customization, privacy, and the ability to simulate real-world scenarios. If you're looking to upskill further, remember to check out the extensive courses offered by LearnSQL.com.

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

  7. SQL: A Practical Introduction for Querying Databases

    There are 5 modules in this course. Much of the world's data lives in databases. SQL (or Structured Query Language) is a powerful programming language that is used for communicating with and manipulating data in databases. A working knowledge of databases and SQL is a must for anyone who wants to start a career in Data Engineering, Data ...

  8. Mastering Database Assignments: Your Comprehensive Guide

    Navigating the intricate realm of database assignments demands a meticulous understanding of potential challenges and the adept application of optimization strategies. Beyond merely identifying schema errors and performance bottlenecks, this section of the guide immerses you in a deeper exploration of solutions that go beyond the conventional.

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

  10. Introduction to Structured Query Language (SQL)

    Learn about the basic syntax of the SQL language, as well as database design with multiple tables, foreign keys, and the JOIN operation. ... All the course was very good but the last assignment is showing different things in assingment page and in grader submission page due to which it is difficult to submit that json file. A. AK. 4.

  11. CS338 Assignments

    This assignment will focus on more advanced features of SQL . Again, you will write a number of SQL queries and execute them on DB2. Assignment 2 Solution. Assignment 3. This assignment is on conceptual and logical database design. You will be given a spec and asked to create an ER model, which you will then map to a relational model. Assignment 3

  12. Adventureworks Database

    SQL Queries of AdventureWorks Database: The AdventureWorks Database is a Microsoft product sample that provides an example of an online transaction processing (OLTP) database. Adventure Works Cycles is a fictitious multinational manufacturing company that is supported by the AdventureWorks Database. Exercises: Part-I [ 100 exercises with solution]

  13. PDF SQL Assignment (20 points)

    SQL Assignment (20 points) Use the Access database "SQLAssignment.accdb" to complete the following exercises using SQL (this file is linked to the Blackboard assignment). You are required to submit the SQL you used in solving each of the exercises. To submit your SQL cut and paste the SQL from Access into Microsoft Word (or an application ...

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

  15. Solve SQL

    A special-purpose language designed for managing data held in a relational database.

  16. Introduction to SQL and Database

    Introduction to SQL. Structured Query Language (SQL) is a standard query language that is used to work with relational databases. We use SQL to perform CRUD (create, read, update, and delete) operations on relational databases. Create: create databases or tables in a database. Read: read data from a table. Update: insert or update data in a table.

  17. Assignment Operator in SQL Server

    The assignment operator (=) in SQL Server is used to assign the values to a variable. The equal sign (=) is the only Transact-SQL assignment operator. In the following example, we create the @MyCounter variable, and then the assignment operator sets the @MyCounter variable to a value i.e. 1. The assignment operator can also be used to establish ...

  18. Database Management Essentials

    When you're done, you'll understand the objectives for the course and know what topics and assignments to expect. Keeping these course objectives in mind will help you succeed throughout the course! ... (DBMS), either the Oracle Cloud database server with the SQL Developer client or the PostgreSQL database server with the pgAdmin client ...

  19. = (Assignment Operator) (Transact-SQL)

    In this article. Applies to: SQL Server Azure SQL Database Azure SQL Managed Instance Azure Synapse Analytics Analytics Platform System (PDW) SQL analytics endpoint in Microsoft Fabric Warehouse in Microsoft Fabric The equal sign (=) is the only Transact-SQL assignment operator. In the following example, the @MyCounter variable is created, and then the assignment operator sets @MyCounter to a ...

  20. CREATE DATABASE (Transact-SQL)

    To create a new database in an elastic database pool, set the SERVICE_OBJECTIVE of the database to ELASTIC_POOL and provide the name of the pool. For more information, see Create and manage a SQL Database elastic pool. AS COPY OF [source_server_name.]source_database_name. Applies to: Single and pooled databases only.

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

  22. Database-Level Roles

    Fixed-Database role name Description; db_owner: Members of the db_owner fixed database role can perform all configuration and maintenance activities on the database, and can also drop the database in SQL Server. (In SQL Database and Azure Synapse, some maintenance activities require server-level permissions and can't be performed by db_owners.): db_securityadmin

  23. BwireC/SQL-DATABASE-DESIGN-WEEK-4-ASSIGNMENT

    ASSIGNMENT. Contribute to BwireC/SQL-DATABASE-DESIGN-WEEK-4-ASSIGNMENT development by creating an account on GitHub.

  24. Advanced SQL Practice: 10 Exercises with Solutions

    The RANK() function assigns the same rank if multiple consecutive rows have the same value. Then, the next row gets the next rank as if the previous rows had distinct values. Here, the ranks 1,1,1 are followed by 4 (as if it was 1,2,3 instead of 1,1,1).. The DENSE_RANK() function also assigns the same rank if multiple consecutive rows have the same value.

  25. How to connect from pgadmin to postgreSQL server with private endpoint

    -Verify IP Address Assignments: Check that the private endpoint has the correct IP address assigned and that there are no conflicts with other resources. -Check Network Security Groups (NSGs): Review the NSG rules for the private endpoint's subnet to ensure the necessary traffic is allowed and doesn't have conflicting rules.

  26. 20 Basic SQL Query Examples for Beginners

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