The provided texts offer a comprehensive introduction to databases and SQL, covering fundamental concepts like tables, columns, and records, alongside essential SQL commands for data manipulation and querying. They further explore the role of SQL in data analysis, outlining necessary skills, qualifications, project work, portfolios, and internships for aspiring data analysts. Advanced SQL topics such as joins, subqueries, stored procedures, triggers, views, and window functions are examined in detail through explanations and practical examples using MySQL. Finally, the material transitions to PostgreSQL, demonstrating similar SQL functionalities and introducing more advanced features like case statements, aggregate functions, and user-defined functions, while also discussing the importance and top certifications in the field of data analytics.
SQL Fundamentals Study Guide
Quiz
- What is the purpose of the GROUP BY clause in SQL? Provide a brief example of its syntax. The GROUP BY clause in SQL is used to group rows that have the same values in one or more columns into summary rows. It is often used with aggregate functions to calculate metrics for each group. For example: SELECT department, COUNT(*) FROM employees GROUP BY department;
- Explain the difference between the WHERE clause and the HAVING clause in SQL. When would you use each? The WHERE clause filters individual rows based on a specified condition before any grouping occurs. The HAVING clause filters groups based on a specified condition after grouping has been performed by the GROUP BY clause. You use WHERE to filter individual records and HAVING to filter groups of records.
- Describe the main categories of SQL data types discussed in the source material. Give one example for each category. The source material outlines several main categories of SQL data types: exact numeric (e.g., INTEGER), approximate numeric (e.g., FLOAT), date and time (e.g., DATE), string (e.g., VARCHAR), and binary (e.g., BINARY).
- List three types of SQL operators and provide a brief explanation of what each type is used for. Three types of SQL operators are: arithmetic operators (used for mathematical calculations like addition: +), logical operators (used to combine or modify conditions, like AND), and comparison operators (used to compare values, like equal to: =).
- What are SQL joins used for? Briefly explain the purpose of an INNER JOIN. SQL joins are used to combine rows from two or more tables based on a related column between them. An INNER JOIN returns only the rows where there is a match in both tables based on the join condition; rows with no match in either table are excluded.
- What is a subquery in SQL? Provide a simple example of how a subquery might be used. A subquery is a query nested inside another SQL query (such as SELECT, FROM, or WHERE). It is often used to retrieve data that will be used in the main query’s conditions. For example: SELECT * FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
- Explain the concept of a stored procedure in SQL. What are some potential benefits of using stored procedures? A stored procedure is a set of SQL statements with an assigned name, which is stored in the database. Benefits include reusability of code, improved performance (as they are pre-compiled), and enhanced security by granting access only to the procedure rather than the underlying tables.
- What is a trigger in SQL? Describe a scenario where a trigger might be useful. A trigger is a stored program that automatically executes in response to certain events (e.g., INSERT, UPDATE, DELETE) on a particular table. A trigger could be useful for automatically updating a timestamp field whenever a row in a table is modified, ensuring data integrity or auditing changes.
- Describe what a view is in SQL. How does it differ from a regular table? A view is a virtual table based on the result of an SQL statement. Unlike regular tables, views do not store data themselves; instead, they provide a customized perspective of data from one or more underlying tables. Changes made through a simple view might affect the base tables, but complex views are often read-only.
- What is the purpose of the ORDER BY clause in SQL? Explain how to sort results in descending order. The ORDER BY clause is used to sort the result set of a SQL query based on one or more columns. To sort results in descending order, you specify the column(s) to sort by and append the DESC keyword after the column name(s). For example: SELECT * FROM products ORDER BY price DESC;
Answer Key
- The GROUP BY clause in SQL groups rows with the same values in specified columns, often used with aggregate functions for summarized data. Example: SELECT department, COUNT(*) FROM employees GROUP BY department;
- WHERE filters rows before grouping, while HAVING filters groups after GROUP BY. Use WHERE for record-level conditions and HAVING for group-level conditions on aggregated results.
- The main categories are exact numeric (e.g., INTEGER), approximate numeric (e.g., FLOAT), date and time (e.g., DATE), string (e.g., VARCHAR), and binary (e.g., BINARY).
- Arithmetic operators perform calculations (+, -, *, /, MOD). Logical operators combine conditions (AND, OR, NOT). Comparison operators evaluate relationships between values (=, <>, >, <, >=, <=).
- SQL joins combine rows from multiple tables based on related columns. INNER JOIN returns only matching rows from both tables based on the join condition.
- A subquery is a query nested within another query, often used to provide values for conditions in the outer query. Example: SELECT * FROM products WHERE price > (SELECT AVG(price) FROM products WHERE category = ‘Electronics’);
- A stored procedure is a pre-compiled set of SQL statements stored in the database, offering benefits like code reuse, improved performance, and enhanced security.
- A trigger is a database object that automatically executes SQL code in response to specific events on a table. Useful for auditing changes by logging every update to a separate history table.
- A view is a virtual table based on the result of a query, providing a specific perspective on the data without storing it directly. It differs from a regular table by not holding persistent data.
- The ORDER BY clause sorts the query result set. To sort in descending order, use the DESC keyword after the column name in the ORDER BY clause (e.g., ORDER BY salary DESC).
Essay Format Questions
- Discuss the importance of data types in SQL. Explain how choosing the appropriate data type for a column can impact database performance and data integrity. Provide specific examples of scenarios where different data types would be most suitable.
- Elaborate on the different types of SQL joins (INNER, LEFT, RIGHT, FULL). Explain the conditions under which each type of join is most useful and provide conceptual examples illustrating the results of each join type using sample tables.
- Analyze the benefits and drawbacks of using stored procedures and triggers in SQL database design. Consider aspects such as performance, maintainability, security, and complexity. Provide scenarios where each would be a particularly advantageous or disadvantageous choice.
- Explain the concept and benefits of using views in SQL. Discuss how views can contribute to data security, query simplification, and data abstraction. Describe different types of views and their specific use cases.
- Compare and contrast the use of subqueries and joins in SQL for retrieving data from multiple tables. Discuss the scenarios where one approach might be preferred over the other, considering factors such as readability, performance, and the complexity of the relationships between tables.
Glossary of Key Terms
- Clause: A component of an SQL statement that performs a specific function (e.g., SELECT, FROM, WHERE, GROUP BY, ORDER BY).
- Data Type: The attribute that specifies the type of data that a column can hold (e.g., numeric, string, date).
- Operator: Symbols or keywords used to perform operations in SQL expressions (e.g., arithmetic, logical, comparison).
- Join: An SQL operation that combines rows from two or more tables based on a related column.
- Inner Join: Returns rows only when there is a match in both tables based on the join condition.
- Outer Join (Left, Right, Full): Returns all rows from one table and the matching rows from the other; if no match, NULLs are used for the non-matching table.
- Subquery (Nested Query): A query embedded inside another SQL query.
- Stored Procedure: A pre-compiled collection of SQL statements stored in the database.
- Trigger: A database object that automatically executes a block of SQL code in response to certain events on a table.
- View: A virtual table based on the result of an SQL SELECT statement.
- Aggregate Function: A function that performs a calculation on a set of values and returns a single summary value (e.g., COUNT, SUM, AVG, MIN, MAX).
- GROUP BY Clause: Groups rows with the same values in one or more columns.
- HAVING Clause: Filters the results of a GROUP BY clause based on specified conditions.
- WHERE Clause: Filters rows based on specified conditions before grouping.
- ORDER BY Clause: Sorts the result set of a query based on specified columns.
- DESC: Keyword used with ORDER BY to sort in descending order.
- ASC: Keyword used with ORDER BY to sort in ascending order (default).
- Alias: A temporary name given to a table or column in a SQL query for brevity or clarity.
Briefing Document: Review of SQL Concepts and MySQL/PostgreSQL Usage
This briefing document summarizes the main themes, important ideas, and facts presented across the provided sources, which primarily focus on introducing and demonstrating various aspects of SQL using MySQL and PostgreSQL.
Main Themes:
- Fundamentals of SQL: The sources cover core SQL concepts, including data manipulation language (DML) commands (SELECT, INSERT, UPDATE, DELETE), data definition language (DDL) commands (CREATE TABLE, ALTER TABLE, DROP TABLE, CREATE DATABASE, DROP DATABASE, CREATE VIEW, DROP VIEW), clauses (WHERE, GROUP BY, HAVING, ORDER BY, JOIN, LIMIT), data types, operators, and basic SQL functions.
- Database Management Systems: The documents illustrate the practical application of SQL within two popular database management systems: MySQL and PostgreSQL. This includes installation (for MySQL), connecting to servers, and executing SQL commands within their respective interfaces (MySQL Workbench, command-line interface, and online compilers for PostgreSQL).
- Data Filtering and Sorting: A significant portion of the content focuses on how to effectively filter data using the WHERE and HAVING clauses and how to sort results using the ORDER BY clause. The use of comparison operators, logical operators (AND, OR, BETWEEN, LIKE, NOT LIKE), and pattern matching is highlighted.
- Data Aggregation: The GROUP BY and HAVING clauses are explained and demonstrated for summarizing data based on groups, along with aggregate functions like COUNT, SUM, AVG, MAX, and MIN.
- Joining Tables: The concept of joining data from multiple tables is introduced, with a focus on INNER JOIN and the importance of common fields for linking tables.
- Advanced SQL Concepts: The sources delve into more advanced topics such as subqueries (nested queries), views (virtual tables), stored procedures (reusable SQL code), triggers (actions performed automatically in response to database events), Common Table Expressions (CTEs/WITH expressions), and window functions (for analytical queries).
- SQL Functions: Various built-in SQL functions are explained and demonstrated, including mathematical functions (ABS, GREATEST, LEAST, MOD, POWER, SQRT, SIN, COS, TAN, CEILING, FLOOR) and string functions (CHARACTER_LENGTH, CONCAT, LEFT, RIGHT, SUBSTRING/MID, REPEAT, REVERSE, LTRIM, RTRIM, TRIM, POSITION, ASCII).
- Practical Application and Examples: The sources heavily rely on practical examples and demonstrations within MySQL Workbench and online PostgreSQL environments to illustrate the usage and benefits of different SQL concepts and commands.
- Database Connectivity with Python: One source provides a basic introduction to connecting to a MySQL database using Python, creating databases and tables, inserting data, and executing queries.
- Common Interview Questions: One section focuses on typical SQL interview questions, covering topics like INDEX, GROUP BY, ALIAS, ORDER BY, differences between WHERE and HAVING, VIEW, and STORED PROCEDURE.
Most Important Ideas and Facts (with Quotes):
- SQL Clauses for Data Manipulation:“we condition one condition two and so on then we have the group by Clause that takes various column names so you can write Group by column 1 column 2 and so on next we have the having Clause to filter out tables based on groups finally we have the order by Clause to filter out the result in ascending or descending order” (01.pdf) – This outlines the basic structure and purpose of key SQL clauses.
- The WHERE clause filters rows before grouping, while the HAVING clause filters groups after they are formed.
- SQL Data Types: The document lists various SQL data types, categorizing them as exact numeric (integer, small int, bit, decimal), approximate numeric (float, real), date and time (date, time, timestamp), string (char, varchar, text), and binary (binary, varbinary, image).
- SQL Operators: Basic arithmetic, logical (all, and, any, or, between, exists), and comparison operators (=, !=, >, <, >=, <=, NOT <, NOT >) are fundamental for constructing SQL queries.
- MySQL Workbench Installation: The source provides a step-by-step guide to installing MySQL Workbench on Windows, including downloading the installer from the official Oracle website (myql.com), choosing a custom setup, and selecting components like MySQL Server, MySQL Shell, and MySQL Workbench. The importance of setting a password for the root user is emphasized: “now here set the password for your root user by the way root is the default user this user will have access to everything” (01.pdf).
- Basic MySQL Commands: Commands like SHOW DATABASES, USE <database_name>, SHOW TABLES, SELECT * FROM <table_name>, and DESCRIBE <table_name> are introduced as essential for navigating and inspecting database structures.
- Creating Tables: The CREATE TABLE command syntax is explained, including defining column names and their data types, and specifying constraints like PRIMARY KEY and NOT NULL.
- Inserting Data: The INSERT INTO command is used to add new rows into a table, specifying the table name and the values for each column.
- String Functions:“there’s also a function called position in MySQL the position function Returns the position of the first occurrence of a substring in a string” (01.pdf)
- “the asky function Returns the asky value for a specific character” (01.pdf)
- PostgreSQL’s string functions like CHARACTER_LENGTH, CONCAT, LEFT, RIGHT, REPEAT, and REVERSE provide powerful text manipulation capabilities.
- GROUP BY and Aggregate Functions: The GROUP BY clause groups rows with the same values in specified columns, allowing the application of aggregate functions to each group.
- HAVING Clause for Filtering Groups: “the having Clause works like the wear Clause the difference is that wear Clause cannot be used with aggregate functions the having Clause is used with a group by Clause to return those rows that meet a condition” (Source 17.pdf).
- JOIN Operations: SQL joins (INNER JOIN is primarily discussed) are used to combine rows from two or more tables based on related columns.
- Subqueries (Nested Queries): A subquery is a query embedded within another SQL query, used to retrieve data that will be used in the main query’s conditions.
- Views (Virtual Tables):“views are actually virtual tables that do not store any data of their own but display data stood in other tables views are created by joining one or more tables” (01.pdf).
- Views simplify complex queries and can enhance data security. The CREATE VIEW, RENAME TABLE (for renaming views), and DROP VIEW commands are used to manage views.
- Stored Procedures:“a stored procedure is an SQL code that you can save so that the code can be reused over and over again” (01.pdf).
- Stored procedures can take input parameters (IN parameters) and help in encapsulating and reusing SQL logic.
- Triggers: Triggers are SQL code that automatically executes in response to certain events (e.g., BEFORE INSERT, AFTER UPDATE) on a table.
- Window Functions: Introduced in MySQL 8.0, window functions perform calculations across a set of table rows that are related to the current row, allowing for analytical queries (e.g., calculating total salary per department using SUM() OVER (PARTITION BY)). The RANK(), DENSE_RANK(), and FIRST_VALUE() functions are examples of window functions.
- Common Table Expressions (CTEs): CTEs, defined using the WITH keyword, are temporary, named result sets defined within the scope of a single query, improving readability and allowing for recursive queries.
- Database Connectivity with Python: The mysql.connector library in Python can be used to connect to MySQL databases, execute SQL queries, and retrieve results. The basic steps involve creating a server connection, creating databases, connecting to specific databases, and executing queries using cursors.
- PostgreSQL Specifics: The sources also demonstrate SQL concepts within a PostgreSQL environment using online compilers, highlighting similar SQL syntax and the availability of functions like BETWEEN, LIKE for pattern matching (% for any sequence of characters, _ for a single character), and various mathematical and string functions. The ALTER TABLE … RENAME COLUMN command is shown for modifying table schema. The LIMIT clause in PostgreSQL restricts the number of rows returned by a query.
- SQL Interview Preparedness: The final source provides insights into common SQL interview questions, emphasizing understanding of fundamental concepts and practical application.
Overall Significance:
The provided sources offer a comprehensive introduction to fundamental and advanced SQL concepts, demonstrating their application in both MySQL and PostgreSQL. They emphasize practical learning through examples and hands-on exercises, making them valuable resources for individuals learning SQL or preparing for database-related tasks and interviews. The inclusion of database connectivity with Python further highlights the role of SQL in broader data management and application development contexts.
Understanding Fundamental SQL Concepts and Operations
1. What are the fundamental components of a SQL query?
A fundamental SQL query typically involves the SELECT statement to specify the columns you want to retrieve, the FROM clause to indicate the table(s) you are querying, and optionally, the WHERE clause to filter rows based on specific conditions. Additionally, you might use GROUP BY to group rows with the same values, HAVING to filter groups, and ORDER BY to sort the result set in ascending (ASC) or descending (DESC) order.
2. What are the common data types available in SQL?
SQL supports various data types to define the kind of data a column can hold. These include exact numeric types like INT, SMALLINT, BIT, and DECIMAL; approximate numeric types such as FLOAT and REAL; date and time types like DATE, DATETIME, and TIMESTAMP; string data types including CHAR, VARCHAR, and TEXT; and binary data types such as BINARY, VARBINARY, and IMAGE.
3. What are the different categories of operators used in SQL?
SQL uses several categories of operators. Arithmetic operators perform mathematical operations (+, -, *, /, MOD). Logical operators (ALL, ANY, OR, BETWEEN, EXISTS, etc.) are used to combine or negate conditions. Comparison operators (=, !=, >, <, >=, <=, NOT <, NOT >) are used to compare values.
4. How can you set up and connect to a MySQL database using MySQL Workbench and the command line?
To set up MySQL, you typically download the MySQL Installer from the official Oracle website. During the installation, you can choose to install MySQL Server, MySQL Shell, and MySQL Workbench. You’ll need to configure the server instance, set a password for the root user, and execute the configuration.
To connect via MySQL Workbench, you open the application, click on the local instance connection, and enter your root password.
To connect via the command line, you need to navigate to the bin directory of your MySQL installation using the cd command in the command prompt. Then, you can use the command mysql -u root -p, and upon entering your password, you’ll be connected to the MySQL server.
5. What are some basic SQL commands for database and table manipulation?
Some basic SQL commands include:
- SHOW DATABASES; to list the existing databases.
- USE database_name; to select a specific database to work with.
- SHOW TABLES; to list the tables within the selected database.
- SELECT * FROM table_name; to view all rows and columns in a table.
- DESCRIBE table_name; or DESC table_name; to show the structure of a table (column names, data types, etc.).
- CREATE DATABASE database_name; to create a new database.
- CREATE TABLE table_name (column1 datatype, column2 datatype, …); to create a new table with specified columns and data types.
- DROP TABLE table_name; to delete a table.
- DROP DATABASE database_name; to delete a database.
6. How do GROUP BY and HAVING clauses work in SQL?
The GROUP BY clause in SQL is used to group rows in a table that have the same values in one or more columns into summary rows. It is often used with aggregate functions (like COUNT, MAX, MIN, AVG, SUM) to compute values for each group.
The HAVING clause is used to filter the results of a GROUP BY clause. It allows you to specify conditions that must be met by the groups. The key difference from the WHERE clause is that WHERE filters individual rows before grouping, while HAVING filters groups after they have been formed.
7. What are SQL JOINs and what are some common types?
SQL JOINs are used to combine rows from two or more tables based on a related column between them. This allows you to retrieve data from multiple tables in a single query. Common types of JOINs include:
- INNER JOIN: Returns rows only when there is a match in both tables.
- LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table and the matching rows from the right table. If there’s no match in the right table, NULLs are used for the right table’s columns.
- RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table and the matching rows from the left table. If there’s no match in the left table, NULLs are used for the left table’s columns.
- FULL OUTER JOIN: Returns all rows when there is a match in either the left or right table. If there is no match in one of the tables, NULLs are used for the columns of the table without a match. (Note: MySQL does not directly support FULL OUTER JOIN, but it can be simulated using UNION ALL with LEFT JOIN and RIGHT JOIN).
JOIN conditions are typically specified using the ON keyword, indicating which columns should be compared for equality.
8. What are subqueries and stored procedures in SQL?
A subquery (or inner query) is a query nested inside another SQL query. Subqueries can be used in the SELECT, FROM, WHERE, and HAVING clauses. They are often used to retrieve data that will be used in the conditions or selections of the outer query. Subqueries can return single values, lists of values, or even entire tables.
A stored procedure is a set of SQL statements with an assigned name, which is stored in the database. Stored procedures can be executed by calling their name. They offer several benefits, such as code reusability, improved performance (as the code is pre-compiled and stored on the server), and enhanced security by granting execute permissions without direct table access. Stored procedures can also accept input parameters and return output parameters.
Understanding Relational Database Tables
In relational databases, data is stored in the form of tables. These tables are the fundamental structure for organizing and managing data. You can think of a table as a grid composed of rows and columns.
Here’s a breakdown of the structure of a database table:
- Table Name: Each table has a name that identifies the data it holds, for example, “players”, “employees”, “customers”, or “orders”.
- Columns (or Fields or Attributes):
- Columns are the vertical structures in a table.
- Each column represents a specific attribute or category of information about the items stored in the table.
- At the top of each column is a column name (also known as a field name) that describes the data in that column, such as “player ID”, “player name”, “country”, and “goals scored” in a “players” table. Other examples include “employee_ID”, “employee_name”, “age”, “gender”, “date of join”, “department”, “city”, and “salary” in an “employees” table.
- Each column is associated with a specific data type that defines the kind of values it can hold. Examples of data types in SQL include integer, smallint, decimal, float, real, date, time, varchar, char, text, binary, etc.. The data type ensures that all values stored in a specific column are of the same type or domain.
- Columns are also sometimes referred to as fields in a database.
- Rows (or Records or Tuples):
- Rows are the horizontal structures in a table.
- Each row represents a single instance or record (also called a tuple) of the entity that the table describes.
- For example, in a “players” table, each row would contain the information for one specific player. In an “employees” table, each row would contain the details of a single employee.
- Cells: The intersection of a row and a column forms a cell, which holds a single piece of data. Each column in a row will contain only one value per row, which is a rule for the first normal form of normalization.
- Primary Key: A primary key is a special column or a set of columns that uniquely identifies each row in a table. It ensures that no two rows have the same primary key value, and it cannot contain null or empty values. Primary keys are crucial for linking tables together and maintaining data integrity. For instance, “employee_ID” could serve as a primary key in an “employees” table.
- Index: Tables can be indexed on one or more columns to speed up the process of finding relevant information. An index creates a sorted structure that allows the database to locate specific rows more efficiently without having to scan the entire table.
SQL (Structured Query Language) commands are used to interact with these tables. You can use SQL to query (retrieve), update, insert, and delete records in a table. The SELECT statement is used to retrieve data by specifying the columns you want to see and optionally filtering the rows based on certain conditions using the WHERE clause. INSERT is used to add new rows to a table, UPDATE to modify existing rows, and DELETE to remove rows.
The logical structure of a database, including its tables and their relationships, can be visually represented using an Entity-Relationship (ER) diagram. An ER diagram shows entities (which often correspond to tables) and their attributes (which correspond to columns) and the relationships between these entities. This helps in understanding the information to be stored in a database and serves as a blueprint for database design.
Understanding SQL: Core Concepts and Commands
SQL (Structured Query Language) is a domain-specific language that serves as the backbone of data management and analysis for relational databases. It is the standard language used by most databases to communicate with and manipulate data. Initially developed by IBM, SQL allows users to interact with databases to store, process, analyze, and manage data effectively. As businesses become increasingly data-driven, proficiency in SQL is a crucial skill for data analysts, developers, and database administrators.
Here are key aspects of the SQL query language based on the sources:
- Core Functionality: SQL queries enable you to access any information stored in a relational database. This includes retrieving specific data, updating existing records, inserting new data, and deleting unwanted information.
- Efficiency: SQL is designed to extract data from databases in a very efficient way. By specifying precisely what data you need and the conditions it must meet, you can minimize the amount of data processed and transferred.
- Compatibility: The Structured Query Language is compatible with all major database systems, ranging from Oracle and IBM to Microsoft SQL Server and open-source options like MySQL and PostgreSQL.
- Ease of Use: SQL is designed to manage databases without requiring extensive coding. Its syntax is relatively straightforward, focusing on declarative statements that specify what data should be retrieved or modified, rather than how to perform the operation.
- Applications of SQL: SQL has a wide range of applications, including:
- Creating databases and defining their structure (e.g., creating tables with specific columns and data types).
- Implementing and maintaining existing databases.
- Entering, modifying, and extracting data within a database. For instance, you can use INSERT to add new records, UPDATE to change existing ones, and SELECT to retrieve data.
- Serving as a client-server language to connect the front-end of applications with the back-end databases that store the application’s data.
- Protecting databases from unauthorized access when deployed as Data Control Language (DCL).
- Types of SQL Commands: SQL commands are broadly categorized into four main types:
- Data Definition Language (DDL): These commands are used to change the structure of the database objects such as tables. Examples include CREATE (to create tables), ALTER (to modify table structure), DROP (to delete tables), and TRUNCATE (to remove all rows from a table). DDL commands are auto-committed, meaning changes are permanently saved.
- Data Manipulation Language (DML): These commands are used to modify the data within the database. Examples include SELECT (to retrieve data), INSERT (to add new rows), UPDATE (to modify existing rows), and DELETE (to remove rows). DML commands are not auto-committed, allowing for rollback of changes. The SELECT command is also referred to as Data Query Language (DQL).
- Data Control Language (DCL): These commands control access to data within the database, managing user privileges and permissions. Examples include GRANT (to give users access rights) and REVOKE (to remove access rights).
- Transaction Control Language (TCL): These commands manage database transactions. Examples include COMMIT (to save changes permanently) and ROLLBACK (to undo changes).
- Basic SQL Command Structure: A typical SQL query follows a basic structure:
- SELECT column1, column2, …
- FROM table_name
- WHERE condition(s)
- GROUP BY column(s)
- HAVING group_condition(s)
- ORDER BY column(s) ASC|DESC;
- The SELECT statement specifies the columns you want to retrieve. You can use SELECT * to select all columns.
- The FROM statement indicates the table from which to retrieve the data.
- The optional WHERE clause filters rows based on specified conditions. You can use comparison operators (e.g., >, =, <), logical operators (AND, OR, NOT), BETWEEN to select within a range, and IN to specify multiple values.
- The optional GROUP BY clause groups rows that have the same values in one or more columns into summary rows, often used with aggregate functions.
- The optional HAVING clause filters groups based on specified conditions (used with GROUP BY).
- The optional ORDER BY clause sorts the result set in ascending (ASC) or descending (DESC) order based on one or more columns.
- Data Types: SQL supports various data types to define the kind of data each column can hold, including exact numeric (integer, smallint, decimal), approximate numeric (float, real), date and time (date, time, timestamp), string (char, varchar, text), and binary data types (binary, varbinary, image).
- Operators: SQL uses different types of operators to perform operations in queries, such as arithmetic operators (+, -, *, /), logical operators (ALL, ANY, BETWEEN, EXISTS, IN, LIKE, NOT, OR), and comparison operators (=, !=, >, <, >=, <=).
- Functions: SQL provides built-in functions to perform various operations on data, including:
- Aggregate functions: Calculate a single value from a set of rows (e.g., COUNT, SUM, AVG, MIN, MAX).
- String functions: Manipulate text data (e.g., LENGTH, UPPER, LOWER, SUBSTRING, CONCAT, TRIM, POSITION, LEFT, RIGHT, REPEAT, REVERSE).
- Date and time functions: Work with date and time values (e.g., CURDATE, DAY, NOW).
- Mathematical functions: Perform mathematical calculations (e.g., ABS, GREATEST, LEAST, ROUND).
- Joins: SQL allows you to combine data from two or more tables based on a related column. Different types of joins include INNER JOIN (returns rows only when there is a match in both tables), LEFT JOIN (returns all rows from the left table and matching rows from the right), RIGHT JOIN (returns all rows from the right table and matching rows from the left), and FULL OUTER JOIN (returns all rows when there is a match in either left or right table). UNION operator can also be used to combine the result sets of two or more SELECT statements.
- Subqueries: A subquery (or inner query) is a query nested inside another SQL query. Subqueries can be used in the WHERE, SELECT, and FROM clauses to retrieve data that will be used by the outer query.
- Stored Procedures: These are pre-compiled SQL statements that can be executed as a single unit. They can take parameters and return values, helping to encapsulate business logic and improve performance.
- Triggers: Triggers are special types of stored procedures that automatically run when a specific event occurs in the database server (e.g., before or after an INSERT, UPDATE, or DELETE operation on a table).
In summary, SQL is a powerful and versatile language essential for interacting with relational databases. It provides a structured way to define, manipulate, and retrieve data, making it a cornerstone of modern data management and analysis.
Essential Skills for Aspiring Data Analysts
Based on the sources, becoming a data analyst requires a combination of technical and soft skills. The document “01.pdf” outlines several key skill areas for aspiring data analysts.
According to the source, the steps to become a data analyst include focusing on skills as the first crucial step. These skills are categorized into six main areas:
- Microsoft Excel Proficiency: While advanced tools exist, proficiency in Excel remains vital for data analysts. Its versatility in data manipulation, visualization, and modeling is unmatched, making it a foundational tool for initial data exploration and basic analysis.
- Data Management and Database Management Skills: This is indispensable for data analysts as the volume of data grows. Efficient management and retrieval from databases are critical. Proficiency in DBMS systems and querying languages like SQL ensures analysts can access and manipulate data seamlessly. As we discussed previously, SQL is the backbone of data management and analysis. It allows data analysts to access any information stored in a relational database with SQL queries. This includes writing queries, joining tables, and using subqueries.
- Statistical Analysis: This skill allows analysts to uncover hidden trends, patterns, and correlations within data, facilitating evidence-based decision-making. It empowers analysts to identify the significance of findings, validate hypotheses, and make reliable predictions.
- Programming Languages (e.g., Python, R): Proficiency in programming languages like Python is essential for data analysis. These languages enable data manipulation, advanced statistical analysis, and machine learning implementations. The source also mentions R programming language as one of the tools a data analyst should be familiar with.
- Data Storytelling and Data Visualization: This skill is paramount for data analysts. Data storytelling bridges the gap between data analysis and actionable insights, ensuring that the value of data is fully realized. The ability to present insights clearly and persuasively is crucial as data complexity grows. Tools like Tableau and Power BI are mentioned as data visualization tools.
- Problem Solving and Soft Skills: Strong problem-solving skills are important for data analysts when dealing with complex data challenges and evolving analytical methodologies. Analysts must excel in identifying issues, formulating hypotheses, and devising innovative solutions. In addition to technical skills, data analysts in 2025 will require strong soft skills to excel. These include:
- Communication: Data analysts must effectively communicate their findings to both technical and non-technical stakeholders, presenting complex data in a clear and understandable manner.
- Teamwork and Collaboration: Data analysts often work with multidisciplinary teams alongside data scientists, data engineers, and business professionals. Collaborative skills are essential for sharing insights, brainstorming solutions, and working cohesively towards common goals.
- Domain Knowledge: Knowledge of the domain in which the analyst is working (e.g., pharmaceutical, banking, automotive) is really important. Without a basic foundational domain knowledge, it can be difficult to provide accurate results.
In summary, a data analyst needs a blend of technical skills in data manipulation (including SQL and Excel), statistical analysis, programming, and data visualization, along with crucial soft skills in communication, teamwork, and problem-solving, complemented by domain knowledge. Our earlier discussions highlight the fundamental role of SQL in a data analyst’s toolkit for interacting with databases [1, Your previous turn].
Understanding Database Management and SQL
Based on the sources, database management encompasses the organized collection of structured information or data, typically stored electronically in a computer system. This data is managed using a Database Management System (DBMS), which acts as a storage system for the collection of data.
Here are key aspects of database management as discussed in the sources:
- Role of a DBMS: A DBMS is crucial for controlling and managing databases. It provides the necessary tools and functionalities to ensure data is easily retrieved, managed, and updated.
- Relational Databases: A significant aspect of database management discussed in the source is relational databases. These systems store data in the form of tables. This tabular structure allows for organizing data into tables, rows (records or tuples), and columns (fields).
- Organization and Indexing: In relational databases, data can be organized into tables with specific structures. Furthermore, data can be indexed to make it easier to find relevant information. An index helps speed up data retrieval operations. A table consists of:
- Column Names (Fields): These are the attributes of the data stored in the table (e.g., player ID, player name, country, goals scored). Each column should have a unique name. All values within a specific column should be of the same data type or domain.
- Rows (Records or Tuples): Each row represents a single instance of the entity being described by the table (e.g., information about a specific player).
- SQL for Database Management: As highlighted in our previous conversation, SQL (Structured Query Language) is a domain-specific language used to communicate with databases [1, Your previous turn]. It plays a vital role in database management by allowing users to:
- Query databases to retrieve specific information.
- Update databases to modify existing data.
- Insert records to add new data.
- Perform many other tasks related to managing and manipulating data.
- Store, process, analyze, and manipulate databases.
- Create a database and define its structure.
- Maintain an already existing database.
- Popular Databases: The source lists several popular database systems, including:
- MySQL.
- Oracle Database.
- MongoDB (a NoSQL database).
- Microsoft SQL Server.
- Apache Cassandra (a free and open-source NoSQL database).
- PostgreSQL.
- Database Management Skills for Data Analysts: Our previous discussion on data analyst skills emphasized that data management and database management skills are indispensable for data analysts [Your previous turn, 3]. The increasing volume of data necessitates efficient management and retrieval from databases, making proficiency in DBMS systems and querying languages like SQL critical. Data analysts need to be able to access and manipulate data seamlessly using SQL.
In essence, database management involves the strategic organization, storage, retrieval, and manipulation of data using a DBMS. Relational databases, structured in tables, are a common model, and SQL is the primary language used to interact with these systems for various management tasks. These skills are fundamental for professionals like data analysts who work with data to derive insights and support decision-making.
SQL for Data Analysis Functions
Based on the sources and our conversation history, data analysis functions involve the process of inspecting, cleaning, transforming, and modeling data with the goal of discovering useful information, informing conclusions, and supporting decision-making. SQL plays a crucial role in performing many of these functions when the data resides in relational databases [1, Your previous turn, Your previous turn].
Here are some key data analysis functions that can be performed using SQL, as supported by the sources:
- Data Retrieval and Selection: SQL’s SELECT statement is fundamental for retrieving specific data required for analysis. You can choose particular columns from one or more tables. For example, to analyze player performance, you might select player name and goals scored from a players table.
- Filtering Data: To focus on relevant subsets of data, the WHERE clause in SQL allows you to filter records based on specified conditions. For instance, you might analyze data only for players from a specific country.
- Sorting Data: The ORDER BY clause enables you to sort the retrieved data based on one or more columns, which can help in identifying trends or outliers. You could sort players by the number of goals scored in descending order to see the top performers.
- Removing Duplicates: The DISTINCT keyword is used to retrieve only unique values from a column, which can be important for accurate analysis, such as finding the number of unique cities represented in a dataset.
- Aggregation: SQL provides aggregate functions that perform calculations on a set of rows and return a single summary value. These are essential for summarizing data:
- COUNT(): To count the number of rows or non-null values. For example, counting the total number of employees.
- SUM(): To calculate the total sum of values in a column. For example, finding the total salary of all employees.
- AVG(): To calculate the average of values in a column. For example, finding the average age of employees.
- MIN(): To find the minimum value in a column. For example, identifying the lowest salary.
- MAX(): To find the maximum value in a column. For example, determining the highest salary.
- Grouping Data: The GROUP BY clause allows you to group rows that have the same values in one or more columns into summary rows. This is often used in conjunction with aggregate functions to perform analysis on different categories. For instance, finding the average salary for each department.
- Filtering Groups: The HAVING clause is used to filter groups created by the GROUP BY clause based on specified conditions, often involving aggregate functions. For example, identifying countries where the average salary is greater than a certain threshold.
- Joining Tables: When data for analysis is spread across multiple related tables, JOIN operations in SQL are used to combine data from these tables based on common columns. This allows you to bring together relevant information for a comprehensive analysis, such as combining customer information with their order details. As mentioned in the source, you can even join three or more tables.
- Using Inbuilt Functions: SQL provides various inbuilt functions that can be used for data manipulation and analysis. These include:
- Mathematical Functions: For performing calculations (e.g., ABS(), MOD(), SQRT(), POWER()).
- String Functions: For manipulating text data (e.g., LENGTH(), CONCAT(), UPPER(), LOWER(), SUBSTRING(), REPLACE()).
- Date and Time Functions: For working with temporal data (e.g., CURRENT_DATE(), NOW(), extracting day, year).
- Creating Calculated Fields: Using SQL, you can create new columns based on existing data through calculations or conditional logic. The CASE statement allows you to define different values for a new column based on conditions evaluated on other columns, enabling the categorization of data (e.g., creating a salary range category based on salary values).
- Subqueries (Nested Queries): SQL allows you to write queries within other queries, which can be used to perform more complex data retrieval and analysis. For example, selecting employees whose salary is greater than the average salary calculated by a subquery.
- Views: Views are virtual tables based on the result of an SQL statement. They can simplify complex queries and provide a focused perspective on the data, making analysis easier by presenting a subset of data in a more manageable format.
- Common Table Expressions (CTEs): CTEs are temporary, named result sets defined within the scope of a single query. They can break down complex analytical queries into smaller, more readable, and manageable parts.
These data analysis functions, facilitated by SQL, are crucial skills for a data analyst, as highlighted in our earlier discussion about the necessary skills for this role [Your previous turn]. Proficiency in using these SQL features allows data analysts to effectively extract, manipulate, summarize, and analyze data stored in databases to derive meaningful insights.
The Original Text
hello everyone and welcome to SQL fos by simply learn have you ever wondered how apps manage data or how businesses handle massive data sets the answer lies in SQL structured query language is the backbone of data management and Analysis making it a must have skill for data analyst developers and database administrators as well as IND indes become more datadriven the demand for SQL experts is skyrocketed and by 2025 job opportunities in fields like SQL development and data analysis with search with starting salaries reaching around $50,000 in the US and around 4 to8 lakh perom in India and even experienced professionals earn around $100,000 or 20 lakh perom in India this course will take you from a beginner level to see SQL expert you learn how to write queries join tables use subqueries and apply SQL for Hands-On data analysis and by the end you’ll be equipped to manage and manipulate data like a pro so let’s get started but before that if you’re interested to make a current data analytics check out Simply learn’s postgraduate program in data analytics this comprehensive course is designed to transform you into a data analyst export this program covers essential skills such as data visualization statistical analysis machine learning using industry leading tools and Technologies like XLR Python and even tablet the course link is mentioned in description box below and in the pin comment so hurry up and enroll now in this session we are going to learn about databases how data is stored in relational databases and we’ll also look at some of the popular databases finally we’ll understand various SQL commands on my SQL Server now let’s get started with what is a database so according to Oracle a database is an organized collection of structured information or data that is typically stored electronically in a computer system a database is usually controlled by a database management system or dbms so it is a storage system that has a collection of data relational databases store data in the form of tables that can be easily retrieved managed and updated you can organize data into tables rows columns and index it to make it easier to find relevant information now talking about some of the popular databases we have mySQL database we also have Oracle database then we have mongod DV which is a no SQL database next we have Microsoft SQL Server next we have Apache cassendra which is a free and open source nosql database and finally we have postgress SQL now let’s learn what is SQL so SQL is a domain specific language to communicate with databases SQL was initially developed by IBM most databases use structured query language or SQL for writing and querying data SQL commands help you to store process analyze and manipulate databases with this let’s look at what a table is so this is how a table in a database looks like so here you can see the name of the table is players on the top you can see the column names so we have the player ID the player name the country to which the player belongs to and we also have the goals scored by each of the players so these are also known as fields in a database here each row represents a record or a tle so if you have the player ID which is 103 here the name of the player is Daniel he is from England and the number of goals he has scored is seven so you can use SQL commands to query update insert records and do a lot of other tasks now we’ll see what the features of SQL are SQL lets you access any information stored in a relational database with SQL queries data is extracted from the database in a very efficient way the structured query language is compatible with all database systems from Oracle IBM to Microsoft and it doesn’t require much coding to manage databases now we will see applications of SQL SQL is used to create a database Define its structure implement it and let you perform many functions SQL is also used for maintaining an already existing database SQL is a powerful language for entering data modifying data and extracting data in a database SQL is extensively used as a client server language to connect the front end with the back end the supporting the client server architecture SQL when deployed as data control language DCL helps protect your database from unauthorized access if you categor the steps to become a data analyst these are the ones firstly you need to focus on skills followed by that you need to have a proper qualification then test your skills by creating a personal project an individual project followed by that you must focus on building your own portfolio to describe your caliber to your recruiters and then Target to the entry level jobs or internships to get exposure to the real world data problems so these are the five important steps now let’s begin with the step one that is skills so skills are basically categorized into six steps Ed cleaning data analysis data visualization problem solving soft skills and domain knowledge so these are the tools Excel MySQL our programming language Python programming language some data visualization tools like TBL Loop powerbi and next comes the problem solving so these are basically the soft skill Parts problem solving skills domain knowledge the domain in which you’re working maybe a farma domain maybe a banking sector maybe automobile domain Etc and lastly you need to be a good team player so that you can actively work along with the team and solve the problem collaboratively now let’s move ahead and discuss each and every one of these in a bit more detail starting with Microsoft Excel while Advanced tools are prevalent Proficiency in Excel remains vital for data analyst Excel versatility in data manipulation visualization and modeling is Unown Managed IT serves as a foundational tool for initial data exploration and basic analysis data management database management skill is indispensable for data analyst as data volume saw efficient management and retrieval from datab basis is critical Proficiency in ddb systems and querying languages like SQL ensures analyst can access and manipulate data seamlessly followed by that we have statistical analysis statistical analysis allow analyst to uncover hidden Trends pattern and cor relationships within data facilitating evidence-based decision making it empowers analyst to identify the significance of findings validate hypothesis and make reliable predictions next after that we have programming languages Proficiency in programming languages like python is essential for data analysis these languages enable data manipulation Advanced statistical analysis and machine learning implementations next comes data storytelling or also known known as data visualizations data storytelling skill is Paramon for data analyst data storytelling Bridges the gap between data analysis and actionable insights ensuring that the value of data is fully realized in a world where data driven communication is Central to business success data visualization skill is a CornerStore for data analyst as data complexity grows the ability to present insights clearly and persuasively is Paramount next is managing your customers and problem solving managing all your customers data and Company relationships is Paramount strong problem solving skills are important for data analyst with complex data challenges and evolving analytical methodologies analyst must excel in identifying issues formulating hypothesis and devising innovative solutions in addition to the technical skills data analyst in 2025 will require strong soft skills to excel in their roles here are the top ones data analyst must effectively communicate their findings to both Technical and non-technical stakeholders this includes presenting complex data in a clear and understandable manner next soft skill is teamwork and collaboration data analysts often work with multidisciplinary teams alongside data scientists data Engineers business professionals collaborative skills are essential for sharing insights brainstorming Solutions and working cohesively towards common goals and last but not least domain knowledge knowledge on domain in which you’re currently working is really important it might be a formatical domain it can be an automobile domain it can be banking sector and much more unless you have a basic foundational domain knowledge you cannot continue in that domain with accurate results now the next step which was about the qualification to become a data analyst Master’s courses online courses and boot camps provide strong structured learning that helps you gain in-depth knowledge and specialized skills in data analysis masters programs offer comprehensive academically recr training and often include research projects making sure you’re highly competitive in the job market online courses allow flexibility to learn at your own pace while covering essential topics and boot gaps offer immersive Hands-On training in a short period focusing on practical skills all three parts enhance your credibility keeping you updated on industry Trends and make you more attractive to potential employers if you are looking for a well curated allrounder then we have got you covered simply learn offers a wide range of courses on data science and data analytics starting from Masters professional certifications to post graduations and boot camps from globally reputed and recognized universities for more details check out the links in the description box below and comment section now proceeding ahead we have the projects for data analyst data analyst this projects demonstrate practical skills in data cleaning visualization and Analysis they help build a portfolio showcasing your expertise and problem solving abilities projects provide hands-on experience Bridging the Gap between Theory and real world application this show domain knowledge making you more appealing to employees in specific Industries projects enhance your confidence and prepare you to discuss real world challenges in interviews proceeding ahead the next step is about the portfolio for data analysts a portfolio is a testament that demonstrates your skill and expertise through real world projects showcasing your ability to analyze and interpret data effectively it provides tangible proof of your capabilities making you stand out to the employers additionally it highlights your domain knowledge and problem solving skills giving you a Competitive Edge during job applications and interviews last but not the least data analyst internships internships provide hands-on experience with real world sets tools and workflows Bridging the Gap between Theory knowledge and practical application they offer exposure to Industry practices helping you understand how data is used to drive decisions internships also build you Professional Network enhance your resuming and improve chances of securing a full-time data analy role so let’s understand what 10 year diagram is an entity relationship diagram describes the relationship of entities that needs to to be stored in a database ER diagram is mainly a structural design for the database it is a framework made using specializ symbols to define the relationship between entities ER diagrams are created based on the three main components entities attributes and relationships let’s understand the use of ER diagram with the help of a real world example here a school needs all its Student Records to be stored digitally so they approach an IT company to do so a person from the company will meet the school authorities note all their requirements describe them in the form of ear diagram and get it cross checked by the school authorities as the school authorities approve the year diagram the database Engineers would carry further implementation let’s have a view of an ear diagram the following diagram showcases two entities student and course and the relationship the relationship described between student and course is many to many as a course can be opted by several students and a student can opt for more than one course here student is the entity and it processes the attributes that is student ID student name and student age and the course entity has attributes such as course ID and course name now we have an understanding of Y diagram let us see why it has been so popular The Logical structure of the database provided by a diagram communicates the landscape of business to different teams in the company which is eventually needed to support the business year diagram is a GUI representation of The Logical structure of a database which gives a better understanding of the information to be stored in a database database designers can use ER diagrams as a blueprint which reduces complexity and helps them save time to build databases quickly ear diagrams helps you identify the enti ities that exist in a system and the relationships between those entities after knowing its uses now we should get familiar with the symbols used in your diagram the rectangle symbol represents the entities oral symbol represents attributes a rectangle embedded in a rectangle represents a weak entity a dashed toal represents a derived attribute a diamond symbol represents a relationship among entities double all symbol represents multivalued attributes now we should dive in and learn about the components of ER diagram there are three main components of ER diagram entity attribute and relationship entities have weak entity attributes are further classified into key attribute composite attribute multivalued attribute and derived attribute relationships are also classified into one to one relationships one to many relationships many to one relationships and many to many relationships let’s understand these components of V diagram starting with entities an entity can be either a living or a non- living component an entity is showcased as a rectangle in a near diagram let’s understand this with the help of a near diagram here both student and course are in rectangular shape and are called entities and they represent the relationship study in a diamond shape let’s transition to weak entity and an entity that makes Reliance over another entity is called a weak entity the weak entity is showcased as a double rectangle in ER diagram in the example below the school is a strong entity because it has a primary key attribute School number unlike the school the classroom is a weak entity because it does not have any primary key and the room number attribute here acts only as a discriminator and not a primary key now let us know about attributes attribute an attribute exhibits the properties of an entity an attribute is Illustrated with an oval shape in an ER diagram in the example below student is an entity and the properties of student such as address age name and role number are called its attributes let’s see our first classification under attribute that is key attribute the key attribute uniquely identifies an entity from an entity set the text of a key attribute is underlined in the example below we have a student entity and it has attributes name address role number and age but here role number can uniquely identify a student from a set of students that’s why it is termed as a key attribute now we will see composite attribute an attribute that is composed of several other attributes is known as a composite attribute and oval showcases the composite attribute and the composite attribute oval is further connected with other ovals in the example below we can see an attribute name which can have further subparts such as first name middle name and last name these attributes with further classification is known as composite attribute now let’s have a look at multivalued attribute an attribute that can possess more than one value are called multivalued attributes these are represented as double old shape in the example below the student entity has attributes phone number role number name and age out of these attributes phone number can have more than one entry and the attribute with more than one value is called multivalued attribute let’s see derived attribute an attribute that can be derived from other attributes of the entity is known as a derived attribute in the ER diagram the derived attribute is represented by dashed over and in the example below student entity has both date of birth and age as attributes here age is a derived attribute as it can be derived by subtracting current date from the student date of birth now after knowing attributes let’s understand relationship in ER diagram a relationship is showcased by the diamond shape in the year diagram it depicts the relationship between two entities in the below for example student study course here both student and course are entities and study is the relationship between them now let’s go through the type of relationship first is one to one relationship when a single element of an entity is associated with a single element of another entity this is called one to one relationship in the example below we have student and identification card as entities we can see a student has only one identification card and an identification card is given to one student it represents a one to one relationship let’s see the second one one to many relationship when a single element of an entity is associated with more than one element of another entity is called one to many relationship in the below example a customer can place many orders but a particular order cannot be placed by many customers now we will have a look at many to one relationship when more than one element of an entity is related to a single element of another entity it is called many to one relationship for example students have to opt for a single course but a course can be opted by number of students let’s see many to many relationship when more than one element of an entity is associated with more than one element of another entity is called many to many relationship for example an employee can be assigned to many projects and many employees can be assigned to a particular project now after having an understanding of ER diagram let us know the points to keep in mind while creating the year diagram first identify all the entities in the system embed all the entities in a rectangular shape and label them appropriately this could be a customer a manager an order an invoice a schedule Etc identify relationships between entities and connect them using a diamond in the middle illustrating the relationship do not connect relationships connect attributes with entities and label them appropriately and the attribute should be in Old shape assure that each entity only appears a single time and eradicate any redundant entities or relationships in the ear diagram make sure your ER diagram supports all the data provided to design the database make effective use of colors to highlight key areas in your diagrams there are mainly four types of SQL commands so first we have data definition language or ddl so ddl commands change the structure of the table like creating a table deleting a table or altering a table all the commands of ddl are autoc committed which means it permanently save all the changes in the database we have create alter drop and truncate as ddl commands next we have data manipulation language or DML so DML commands are used to modify a database it is responsible for all forms of changes in the database DML commands are not autoc committed which means it can’t permanently save all the changes in the database we have select update delete and insert as DML commands now select command is also referred to as dql or data query language third we have data control language or DCL so DCL commands allow you to control access to data within the database these DCL commands are normally used to create objects related to user access and also control the distribution of privileges among users so we have Grant and revok which are the examples of data control language finally we have something called as transaction control language or TCL so TCL commands allow the user to manage database transactions commit and roll back our example of TCL now let’s see the basic SQL command structure so first we have the select state stat M so here you specify the various column names that you want to fetch from the table we write the table name using the from statement next we have the we Clause to filter out our table based on some conditions so you can see here we condition one condition two and so on then we have the group by Clause that takes various column names so you can write Group by column 1 column 2 and so on next we have the having Clause to filter out tables based on groups finally we have the order by Clause to filter out the result in ascending or descending order now talking about the various data types in SQL so we have exact numeric which has integer small int bit and decimal then we have approximate numeric which are float and real then we have some date and time data types such as date time time stamp and others then we have string data type which includes car the varar car and text finally we have binary data types and binary data types have binary VAR binary and image now let’s see some of the various operators that are present in SQL so first we have our basic arithmetic operators so you have addition the substraction multiplication division and modulus then we have some logical operators like all and any or between exist and so on finally we have some comparison operators such as equal to not equal to that’s greater than less than greater than equal to or less than equal to not less than or not greater than now let me take you to my MySQL workbench where we will learn to write some of the important SQL commands use different statements functions data types and operators that we just learned in this session we will learn how to install MySQL workbench and then we will run some commands firstly we will visit the official Oracle website that is myql.com and now we’ll move to the downloads page now scroll down and click on my SQL GPL downloads now under Community downloads click on my SQL installer for Windows the current versions are available to download I will choose this installer and click the download button now here just click on no thanks just start my download Once the installer has download it open it you may be prompted for permission click yes this opens the installer we will be asked to choose the setup type we will go with custom click next now you have to select the products you want to install we will install only the MySQL server my SQL shell and the MySQL workbench expand my SQL servers by double clicking on it and choose the version you want to install and click on this Arrow now you have to do the same thing for applications expand applications and choose the MySQL workbench version you want to install and click on the arrow and we’ll do the same thing for my SQL shell we’ll choose the latest version click on the Arrow so these are the products that have to be installed in a system now we will click next I’ll click execute to download and install the server this may take a while depending on your internet speed as the download is completed click next now you see the product configuration click next now we’ll configure our SQL Server instance here we will go with the default settings and click next and under authentication select use strong password encryption for authentication which is recommended and click on next now here set the password for your root user by the way root is the default user this user will have access to everything I will set my password now I’ll click on next and here also we’ll keep the default settings and click on next now to apply configuration we will execute the process once Sol the conf ification steps are complete click finish now you will see the installation is complete it will launch my SQL workbench and my SQL shell after clicking on finish now the shell and workbench has started now we’ll connect by clicking on the root user it will ask for a password enter the password and it will connect successfully yeah the workbench has started now we’ll just connect the server so first we’ll open command prompt now we will reach the path where MySQL files are present you go into this PC local d c program files my SQL my SQL Server 8.0 bin and now I’ll copy this path now we’ll open the command prom and write a command CD space and paste the link and press enter now we write another command that will be my SQL minus u space root minus p and enter now it will ask for your password just enter the password and press enter now the server has started and now we’ll see some commands in my SQL workbench first we will open my SQL workbench now we’ll click on the local instance my SQL 80 and enter the password to connect to the Local Host yeah the my SQL workbench has started now we’ll see some commands the First Command we will see is show databases show databases semicolon and now we will select the whole command and click on this execute button and here we will see the result in the result grit these are the databases that are stored already in the database now there are four databases that is information schema MySQL performance schema and SS now we will select one of the database we will use uh my SQL now we have selected the mySQL database and now in this database we will see which tables are stored in this mySQL database to see that we will run a command show tables we’ll select the command and click on the execute button the these are the tables that are stored in this mySQL database that is columns _ PR component DP and much more now let me now go ahead and open my MySQL workbench so in the search bar I’ll search for MySQL workbench you can see I’m using the 8.0 version I’ll click on it and here it says welcome to my SQL workbench and Below under connections you can see I have already created a connection which says local instance then you have the root the local host and the port number let me click on it you can see the service the username is root and I’ll enter my password and hit okay now this will open the SQL editor so this is how the MySQL workbench looks like here we learn some of the basic SQL commands so first let me show you the databases that are already present so the command is so databases you can hit tab to autoc complete I’ll use a semicolon I’ll select this and here on the top you can see the execute button so if I run this below you can see the output it says show databases seven rows are returned which means currently there are seven databases you can see the names all right now let’s say I want to see the T tables that are present inside this database called world so I’ll use the command use World which is the database name now let me run it so currently I’m using the world database so to display the tables that are present in the world database I can use the show command and write show tables give a semicolon and I’ll hit control enter this time to run it all right so you can see the tables that are present inside this world database so we have three tables in total City Country and Country language now if you are to see the rows that are present in one of the tables you can use the select command so I’ll write select star which basically means I want to display all the columns so star here means to display all the columns then I’ll write my from the table name that is City so this command is going to display me all the rules that are present inside the city table so if I hit control enter all right you can see the message here it says th000 rows were returned which means there were total thousand records present inside the city table so here you can see there’s an ID column a name column this country code district and population all right similarly you can check the structure of the table by using the describe command so I’ll write describe and then I’ll give the table name that is City now let’s just run it there you go the field shows the column names so we have ID name country code district population type here shows the data type of each of the columns so district is character 20 ID is an integer population is also integer null says yes or no which means if no then there are no null values if it’s yes which means there are null values in your table key here represents whether you have any primary key or foreign key and these are some extra information now let’s learn how to create a table in my SQL so I’ll use the create table command for this and before that let me create a database and I’ll name it as SQL intro so the command is create database and I’ll give my database name that is SQL intro me give a semicolon and hit control enter so you can see I have created a new database now if I run this command that is show databases you can see this newly created database that is SQL intro if I scroll down there you go you can see the name here SQL intro okay now within this database we’ll create a table called employee details now this will have the details of some employees so let me first show you how to create a table that will be present inside the SQL intro database so I’ll use the command create table and then I’ll give my table name that is going to be employee uncore details next the syntax is to give the column names so my first column would be the name column which is basically the employee name followed by the data type for this column since name is a text column so I’ll use varar and I’ll give a value of 25 so it can hold only 25 characters okay next I also want the age of the employee now age is always an integer so I’ll give int okay then we can have the gender of the employee so gender can be represented as f for m f for female and M for male so I’m using the card data type or character data type and I’ll give the value as one then let’s have the date of join or doj and this is going to be of data type date all right next we’ll have the city name that is the city to which the employee belongs to so again again this is going to be warar 15 finally we’ll have a salary column and salary we’ll keep it as float since salary can be in decimal numbers as well now I’ll give a semicolon all right so let me just quickly run through it so first I wrote my create command then the table which is also a keyword followed by the table name which is employee details here and then we give the column names such as name age this gender date of join City and salary for each of the columns we also give the data type all right so let me just run it okay so here you can see we have successfully created our first table now you can use the describe command to see the structure of the table I’ll write this describe empore details if I run this there you go so under field you can see the column names then you have the data types null represents if the table can accept null values or not and these are basically empty and we haven’t set any default constraint all right moving ahead now let’s learn to add data to our table using the insert command so on a notepad I have already written my insert statement so let me just copy it and then I’ll explain it one by one all right so if you see this so we have used an insert into statement or a command followed by the table name that is EMP details then this is the syntax using values I have passed in all the records so first we have Jimmy which is the name of the employee then we we have 35 it basically represents the age then m means the gender or the sex then we have the date of join next we have the city to which the employee belongs to and finally we have the salary of the employee so this particular information represents one record or a tle similarly the next employee we have is Shane you can see the age and other information then we have Mary this Dwayne Sara and am all right so let me go ahead and run this so this will help you insert the values in the table that you have created you can see we have successfully inserted six records now to display the records let me use the select statement so I’m using select star from empore details if I run this you can see my table here and the values it has so we have the name column the age column the state of join City salary and these are the values that you can see here moving ahead now let’s say you want to see the Unique city names present in the table so in this case you can use the distinct keyword along with the column name in the select statement so let me show you how you can print the distinct city names that are present in our table now if you notice this table clearly we have Chicago Seattle Boston Austin this New York and this Seattle repeated again so I only want to print the unique values so for that I can write my select statement as select distinct then I’ll give my column name which is City from my table name that is EMP details if I run this you can see my query has returned five rows and these are the values so we have Chicago cattl which was repeated twice is just been shown once then we have Boston Austin and New York now let’s see how you can use inbuilt aggregate functions in SQL so suppose you want to count the number of employees in the table in that case you can use the count function in the select statement so let me show you how to do that so I’ll write select I’ll use my function name name that is Count now since I want to know the total number of employees I’m going to use their name inside the brackets from employee _ details now if I run this this will return the total number of employees that are present in the table so we have six employees in total now if you see here in the result it says count name now this column is actually not readable at all so what SQL provides something called as an alas name so you can give an alas to the resultant output so here I can write select count of name and use an alas as as I can give an alas as countor name and run this statement again there you go you can see here in the resultant output we have the column name as count name which was Alias name now suppose you want to get the total sum of salaries you can use another aggregate function called sum so I’ll write my select statement and this time instead of count I’m going to write sum and since I want to find the sum of salaries so inside the bracket I’ll give my salary column from my table name that is employee details if I run this this will result the total sum of salaries so basically it adds up all the salaries that were present in the salary column now let’s say you want to find the average salary so instead of sum you can write the average function which is ABG so this will give you the average salary from the column salary so you can see it here this says average salary now if you want you can give an alas name to this as well now you can select specific columns from the table by using the column names in the select statement so initially we were selecting all the columns for example like you saw here the star represents that we want to see all the columns from the employee details table now suppose you want to see only specific columns you can mention those column names in the select statement so let’s say I want to select just the name age and the city column from my table that is employee details so this will result in displaying only the name age and City column from the table if I run it there you go it has given only three columns to me now SQL has a we Clause to filter rows based on a particular condition so if you want to filter your table based on specific conditions you can use we Clause now we Clause comes after you give your table name so suppose you want to find the employees with age greater than 30 in this case you can use a we Clause so let me show you how to do it I’ll write select star from my table name that is employee details and after this I’ll use my wear Clause so I’ll write where age greater than 30 if I run this it will give me the output where the age is only greater than 30 so it excluded everything that is less than 30 so we have four employees whose age is greater than 30 here now suppose you want to find only female employees from the table you can also use a wear Clause here so I’ll write select let’s say I want only the name the gender which is sex here comma City from my table that is employee details where I’ll give my column name that is sex is equal to since I want only the female employees I’ll give F and run this statement okay you can see here our employee table has three female employees now suppose you want to find the details of the employees who belong to Chicago or Austin in this case you can use the or operator now the or operator in SQL displays a record if any of the condition separated by R is true so let me show you what I mean so since I want the employees who are from Chicago and Austin I can use an or operator so I’ll write select star from EMP details which is my table name then I’ll give my we Clause where City equal to I’ll give my city name as Chicago and then I’m going to use the or operator or city equal to I’ll write Austin I’ll give a semicolon and let me run it there you go so in the output you can see all the employees who belong to the city Chicago and Austin now there is another way to write the same SQL query so you can use an in operator to specify by multiple conditions so let me just copy this and instead of using the r operator this time I’m going to use the in operator so I’ll delete this after the wear Clause I’m going to write where City and use the in operator inside bracket I’ll give my city names as shago and I want Austin so I’ll give a comma and write my my next city name that is Austin so this query is exactly the same that we wrote on top let me run this you will get the same output there you go so we have Jimmy and Dwayne who are from Chicago and Austin respectively now SQL provides the between operator that selects values within a given range the values can be numbers text or dates now suppose you want to find the employees whose date of join was between 1st of Jan 2000 and 31st of December 2010 so let me show you how to do it I’ll write select star from EMP details where my date of join that is doj between I’ll give my two date values that is 1st of Jan 2000 and I’ll give my second value the date value that is 31st of December 2010 so every employee who has joined between these two dates will be displayed in the output if I run it we have two employees who had joined between 2000 and 2010 so we have Jimmy and Mary here who had joined in 2005 and 2009 respectively all right now in we Clause you can use the and operator to specify multiple conditions now the and operator displays a record if all the conditions separated by and are true so let me show you an example I’ll write select star from employee details table where I want the age to be greater than 30 and I want sex to be male all right so here you can see I have specified two conditions so if both the conditions are true only then it will result in an output if I run it you can see there are two employees who are male and their age is greater than 30 now let’s talk about the group by statement in SQL so the group by statement groups rows that have the same values into summary rows like for example you want to find the average salary of customers in each department now the group by statement is often used with aggregate functions such as count sum and average to group the result set into one or more columns let’s say we want to find the total salary of employees based on the gender so in this case you can use the group by Clause so I’ll write select let’s say sex comma I want to find the total sum of salary as I’ll give an alas name let’s say total salary from my table name that is employee details next I’m going to group it by sex okay let me run it there you go so we have two genders male and female and here you can see the total salary so what this SQL statement did was first it grouped all the employees based on the gender and then it found the total salary now SQL provides the order by keyword to sort the result set in ascending or descending order now the order by keyword sorts the records in ascending order by default to sort the records in descending order you can use the dec keyword so let’s say I want to sort my employee details table in terms of salary so I’ll write select star from empore details and I’ll use my order by clause on the salary column so this will sort all the records in ascending order of their salary which is by default you can see the salary column is sorted in ascending order now suppose you want to sort the salary column and display it in descending order you can use this keyword that is DEC let me run it you can see the output now this time the salary is sorted in descending order and you have the other values as well now let me show you some basic operations that you can do using the select statement so suppose I write select and do an addition operation let’s say 10 + 20 and I’ll give an alas name as addition if I run this it will give me the sum of 10 and 20 that is 30 similarly you can use the subtraction operator and you can change the alas name as let’s say subtract let’s run it you get minus 10 now there are some basic inbuilt functions there are a lot of inbuilt functions in SQL but here I’ll show you a few suppose you want to find the length of a text or a string you can use the length L function so I’ll write select and then use the length function I’ll hit tab to autocomplete let’s say I want to find the length of country India and I’ll give an alas as total length if I run it you see here it returns five because there are five letters in India there’s another function called repeat so let me show you how repeat works so I’ll write select repeat let’s say I want to repeat the symbol that is at the rate I’ll put it in single codes because it is a text character and I want to repeat this character for 10 times close the bracket and let’s run it you can see here in the output it has printed at the rate 10 times you can count it all right now let’s say you want to convert a text or a string to upper case or lower case you can do that as well so I’ll write select and use the function called upper let’s say I want to convert my string that is India to uppercase I’m not giving in any alas name if I run this see my input was capital I and everything else was in small letter in the output you can see it has converted my input to all caps similarly you can change this let’s say you want to print something in lower case you can use the lower function let’s say this time everything is in upper case if I run it it converts India to lower case now let’s explore a few date and time functions let’s say you want to find the current date there’s a function called C which stands for current and this is the function I’m talking about which is current date if I run this you will get the current date that is 28th of Jan 2021 and let’s say you want to extract the day from a date value so you can use the D function let’s say I’ll use D and I want to find the D from my current date if I run this you get 28 which is today’s day now similarly you can also display the current date and time so for that you can use a function that is called now so this will return the current date and time you can see this is the date value and then we have the current time all right and this brings us to the end of our demo session so let me just scroll through whatever we have learned so first I showed you how you can see the databases present in my SQL then we use used one of the databases and checked the tables in it then we created another database called SQL intro for our demo purpose we used that database and then we created this table called employee details with column names like name integer the sex date of joints City and salary I showed you the structure of the database let me run this again so you get an idea you can see this was the structure of our table the then we went ahead and inserted a few records so we inserted records for six employees so you have the employee name the age the gender the date of join the city to which the employee belongs to and the salary of the employee then we saw how you can use the select statement and display all the columns present in the table we learned how you can display the Unique city names we learned how to use different aggregate function like count average and sum then we learned how you could display specific columns from the table we learned how to use we Clause then we used an R operator we learned about in operator the between operator then we used an and operator to select multiple conditions finally we learned about group buy order buy and some basic SQL operations now it’s time to explore some string functions in MySQL so I have given a comment string functions first let’s say you want to convert a certain string into upper case so I can write select the function I’ll use is upper and within this function you can pass in the string let’s say I’ll write India if you want you can give an alas name as let’s say uppercase I’ll give a semicolon and let’s run it there you go so my input was in sentence case and using the upper function we have converted everything into uppercase similarly let me just copy this and I’ll show you if you want to convert a string into a lower case you can use the lower function I’ll run this you can see the result everything is in lower case now of course I need to change the alas name to lower case instead of using lower as the function there is another function that MySQL provides which is called the L case so I’ll just edit this and write L case and let’s say I’ll write India in uppercase let’s run it returns me the same result cool moving on let’s say you want to find the length of a string you can use the character length function I’ll write select use the function character length and I’m again going to pass in my string as India as let’s say total length let’s run it this time I’m going to hit control enter to run my SQL command there you go it has given us the right result which is five because India has five characters in it now these functions you can also apply on a table now let me show you how to do it let’s say we already have the students table and you want to find the length of each of the student names so here you can pass sore name and you can give the same alas name let’s say total length and then you can write from table name that is students if I run this you can see the output it has given me total 20 rows of information this not readable actually let me also so display these student names so that we can compare their length all right I’ll run this again and now you can see the result so Joseph has six characters NES has six vipul has five anubhab has seven similarly if you see Aki has six Tanish has seven ragav has six Cummins has seven rabada has six so on and so forth now instead of using this character length you can also use the function car length it will work the same way let’s see the result there you go it has given us the same result you can either use character length or car length there’s another very interesting function called concat so the concat function adds two or more Expressions together let’s say I’ll write select use the function concatenate the function is actually concat and I’m going to pass in my string values let’s say India is in Asia let’s run this and see our result you can see see here it has concatenated everything let us make it more readable I’ll give a space in between so that you can read it clearly now this is much more readable India is in Asia and if you want you can give an alas name as well as let’s say merged there you go now the same concat operation you can also perform on a table I’m going to to use the same students table let’s say I want to return the student ID followed by the student name and then I am going to merge the student name followed by your space followed by the age of the student and I can give an alas as let’s say name _ AG from my table that is students let’s see how this works okay you see here the result is very clear we have the student ID the student name and the concatenated column that we created which was name _ age where we have the student name with a space followed by the age of the student if I scroll down you can see the rest of the results cool now moving ahead let’s see how the reverse function Works in MySQL so the MySQL reverse function returns a string with the characters printed in reverse order so suppose I write select reverse I’ll use the same string again let’s say I have India let’s run it you will see all the characters printed in reverse order again you can perform the same operation on a table as well let’s say I’ll write select reverse and I’ll pass in the column as student name from my table that is students let’s run it it gives you 20 students and all the names have been printed in reverse order okay now let’s see what the replace function does so the replace function replaces all occurrences of a substring within a string within a new substring so let me show you what I mean I’ll write select replace I’ll pass in my input string which is let’s say orange is a vegetable which is ideally incorrect I’m purposely writing this so that I can replace the word vegetable with fruit okay so what this replace function does is it is going to find where my word vegetable is within the string my input string and it is going to replace my word vegetable with fruit let’s run it and see the output there you go now this is correct which is Orange is a fruit all right now MySQL also provides some trim functions you can use the left trim right trim and just the trim function so let me show you how this left trim Works left trim or L trim removes the leading space characters from a string passed as an argument so see I write select I’ll use the left trim function which is L trim and then I’m going to purposely give a few pces in the beginning of the string I’ll give a word let’s say India and then I’ll give some space after the word India and see how the elri works if I run this it gives me India which is fair enough but before that let’s first find the length of my string so I’ll use my length function here and within this function I am going to find the length of my string which has India along with some leading and trailing spaces I’ll paste this here give a semicolon and I’ll run it okay so the entire string is 17 characters long or the length of the string is 17 now say I use lrim on my same string what it returns me is India and if I run length over it you can see the difference as in you can see how many spaces were deleted from the left of the string you can see here now it says 17 and I’m going to use lrim let’s see the difference it gives me 12 the reason being it has deleted five spaces from the left you can count it 1 2 3 4 and 5 so 17 – 5 is 12 which is correct similarly you can use the rri function which removes the trailing spaces from a string trailing spaces are these spaces when you use left Rim it deletes the leading spaces which is this now let me just replace L trim with r trim which stands for right trim and see the result so the length is 10 now the reason being it has deleted seven spaces from the right of the string if you can count it 1 2 3 4 5 6 and 7 cool you can also use the trim function which will delete both the leading and the TR in spaces so here if I just write trim and I’ll run it it gives me five because India is total five characters long and it has deleted all the leading and the trailing spaces all right there’s also a function called position in MySQL the position function Returns the position of the first occurrence of a substring in a string so if the substring is not found with the original string the function will return zero so let’s say I’ll write select position I want to find where fruit is in my string that is Orange is a fruit I’ll give an alas as name there some error here this should be within double quotes now let’s run it and see the result okay it says at the 13th place or at the 13th position we have the word fruit in our string which is Orange is a fruit now the final function we are going to see is called asky so the asky function Returns the asky value for a specific character let’s say I write select ask key of the letter small a if I run this it will give me the ask key value which is 97 let’s say you want to find the ask key value of 4 let’s see the result it gives me 52 all right in this session we are going to learn two important SQL statements or Clauses that are widely used that is Group by and having first we’ll understand the basics of group by and having and then jump into my SQL workbench to implement these statements so let’s begin first what is Group by in SQL so the group by statement or Clause groups records into summary rows and returns one record for each group it groups the rows with the same group by item expressions and computes aggregate functions for the resulting group a group by Clause is a part of Select expression in each group no two rows have the same value for the grouping column or columns now below you can see the syntax of group by so first we have the select statement and Then followed by the column names that we want to select from we have the table name followed by the wear condition and next we have the group by clause and here we include the column names finally we have the order by and the column names now here is an example of the group by Clause so we want to find the average salary of employees for each department so here you can see we have the employees table it has the employee ID the employee name the age of the employee we have the gender the date on which the employeer had joined the company then we have the department to which each of these employees belong to we have the city to which the employees belong to and then we have the salary in dollars so actually we’ll be using this employees table on my SQL workbench as well so if you were to find the average salary of employees in each department so this is how your SQL query with Group by Clause would look like so we have selected department and then we are using an aggregate function that is AVG which is average and we have chosen the salary column and here we have given an alias name which is average uncore salary which appears in the output you can see here from employees and we have grouped it by department so here in the output you can see we have the department names and the average salary of the employees in each department now let me take you to my MySQL workbench where we’ll Implement Group by and solve specific problems okay so I am on my MySQL workbench so let me make my connection first I’ll enter the password so this will open my SQL editor so first of all let me check the databases that I have so I’ll use my query that is show databases let’s run it okay you can see we have a list of databases here I’m going to use my SQL intro database so I’ll write use SQL intro so this will take us inside this database I run it all right now you can check the tables that are present in SQL intro database if I write show tables you can see the list of tables that are already present in this database to do our demo and understand Group by as well as having let me first create an employee table so I’ll write create table employees next I’ll give my column name as employee _ ID which is the ID for each employee I’ll give my data type as integer and I’ll assign employee ID as my primary key next I’ll give employee name and my data type would be varar I’ll give the size as 25 my third column would be the age column age would obviously be an integer then I have my gender column I’ll use character data type and assign a value of one or size of one next we have the date of join and the data type will be date we have the department column as well this is going to be of varar and 20 will be the size next we have the city column which is actually the city to which the employee belongs to and finally we have the salary column which will have the salary for all the employees okay now let me select and run this you can see here we have successfully created our table now to check if our table was created or not you can use the describe command I’ll write describe employees you can see the structure of the table so far all right now it’s time for us to insert a few records into this employees table so I’ll write insert into employees and I’ll copy paste the records which have already written on a notepad so let me show you so this is my EMP notepad and you can see I have already put the information for all the employees so let me just copy this and we’ll paste it here all right let me go to the top and verify if all the records are fine all right so let’s run our insert query okay so you can see here we have inserted 20 rows of information and now let’s check the table information or the records that are present in our employees table I’ll write select star from employees if I run it you can see here I have my employee ID the employee name age gender we have the city salary and in total we have inserted 20 records now let me run a few SQL commands to check how the structure of our table is let’s say I want to see the distant cities that are present in our table so I’ll write select distinct City from employees if I run on this you see here there are total eight different cities present in our employees table so we have Chicago the Seattle Boston we have New York Miami and Detroit as well now let’s see you want to know the total number of departments that are present so you can use distrct Department if I run this all right you can see we have seven rows returned and here are the department names so we have sales marketing product Tech it finance and HR all right now let me show you another SQL command now this is to use an aggregate function so I want to find the average age of all the employees from the table so I can write select AVG which is the aggregate function for average inside that I have passed my age column from employees if I run this so the average age of all the employees in our table is 33.3 now say you want to find the average age of employees in each department so for this you need to use the group by Clause I’ll give a comment here I want to find the average each in each department so I’ll write select Department comma I’ll write average of age from employees Group by department now if I run this you can see here we have our seven departments on the left and on the right you can see the average age of employees in each of these departments now you can see here in the output it says AVG of age which is not readable so I can give an alas name as average age all right I can bring this down and if you want you can round the values also so you can round the decimal places so I’ll use a round function before the average function and the round function takes two parameters one is the variable and the decimal place you want to round it to so if I run this there you go you can see here we have the average age of all the employees in each of these departments all right now suppose you want to find the total salary of all the employees for each department so you can write select Department comma Now I want the total salary so I’ll use the sum function and I’ll pass my column as salary from employees Group by Department let’s run this query you can see here in the output we have the different departments and on the right you can see the total salary of all the employees in each of these departments now here also you can give an alas name as total underscore salary let’s run it again and you can see the output here all right now moving ahead you can also use the aut by Clause along with the group by Clause let’s say you want to find the total number of employees in each City and group it in the order of employee ID so to do this I can use my select query I’ll write select count of let’s say employee ID and I want to know the city as well from employees Group by City And next you can use the order by Clause I’ll write order by count of employee ID and I’ll write DEC which stands for descending if I run this query you can see here on the left you have the count of employees and on the right you can see the city names so in Chicago we had the highest number of employees working that was four then we had Seattle Houston Boston Austin and the remaining also had two employees so in this case we have ordered our result based on the count of employee ID in descending order so we have the highest number appearing at the top and then followed by the lowest okay now let’s explore another example suppose we want to find the number of employees that join the company each year we can use the year function on the date of joining column then we can count the employee IDs and group the result by each year so let me show you how to do it so I’ll write select I’m going to extract Year from the date of join column I’ll give an alas as year next I’ll count the employee ID from my table name that is employees and I’m going to group it by Year date of join we give a semicolon all right so let’s run this great you see here in the result we have the year that we have extracted from the date of join column and on the right you can see the total number of employees that joined the company each year so we have in 2005 there was one employee similarly we have in 2009 there were two employees if I scroll down you have information of other years as well now if you want you can order this as well based on year or count okay now you can also use the group bu to join two or more tables together so to show you this operation let me first create a sales table so I’ll write create table sales and the sales table will have column such as the product ID which is going to be of integer type then we have the selling price of the product now this will be a float value then we have the quantity sold for each of the products so I’ll write quantity quantity will of integer type next we have the state in which the item was sold and state I’ll put it as worker and give the size as 20 let’s run this so that we’ll create our sales table all right so we have successfully created our sales table next we need to insert a few values to our sales table so I’ve have already written the records in a notepad let me show you okay so here you can see I have my sales text file let me just copy these information I’ll just paste it on the query editor okay now let me go ahead and run this insert command all right so you can see here we have successfully inserted nine rows of information so let me just
run it through what we have inserted so the First Column is the product ID column then we have the selling price at which this product was sold then we have the quantity that was sold and in which state it was sold so we have California Texas Alaska then we have another product ID which is 123 and these are the states in which the products were sold so let me just confirm with the select statement I’ll write select star from sales I run this you can see we have successfully created our table okay now suppose you want to find the revenue for both the product IDs one to one and let’s say 1 to three since we have just two product IDs here so for that you can use the select query so I’ll write select product ID next I want to calculate the revenue so revenue is nothing but selling price multiplied by the quantity so I’ll use the sum function to find the total revenue and inside the sum function I’ll use my selling price column multiplied by my quantity column I’ll give this an alas name as revenue from my table name that is sales finally I’ll group it by product ID let’s run it there you go so here you can see we have the two product IDs one 121 and 1 12 3 and here you can see the revenue that was generated from these two products all right now let’s see we have to find the total profit that was made from both the products 1 to 1 and 1 to 3 so for that I’ll create another the table now this table will have the cost price of both the products so let me create the table first I’ll write create table let’s say the table name is C product which stands for the cost price of the products I’ll give my first column as product ID this will be an integer and I’ll have my second column as cost price cost price will have floating type values let’s run this so we have successfully created our product cost table now let me insert a few values into the C product table so I’ll write insert into ccore product I’ll give my values for one to one let’s say the cost price was $270 for each and next we have my product as 123 and let’s say the cost price for product 1 123 was $250 let’s insert these two values okay next we’ll join our sales table and the product cost table so this will give us the profit that was generated for each of the products so I’ll write select C do productor ID comma I’ll write sum s. cellor price now here C and S are alas names so if I subtract my cost price from the selling price that will return the profit that was generated I’ll multiply this with s do quantity close the bracket I’ll give an alas name as profit from sales as s so here s stands for the sales table I’m going to use inner join ccore product table as the Alias name should be C where s do productor ID is equal to C do productor ID we are using product underscore ID because this column is the common column to both the tables and finally I’m going to group it by C do productor ID all right so let me tell you what I have done here so I’m selecting the product ID next I’m calculating the profit by subtracting the cost price from the selling price and I multiplied the quantity column I’m using an join to connect my sales and the product cost table and I am joining on the column that is product ID and I have grouped it by c. product ID let’s run this there you go so here you can see for product id1 121 we made a profit of $1,100 and for product ID 1 123 you made a profit of $840 so now that we have learned Group by in detail let’s learn about the having clause in SQL the having clause in SQL operates on grouped records and returns rows where aggregate function results matched with given conditions only so now having and wear Clause are kind of similar but we Clause can’t be used with an aggregate function so here you can see the syntax of having Clause you have the select statement followed by the column names from the table name then we have the we conditions next we have the group bu finally we have having and at last we have order by column names so you can see here we have a question at hand we want to find the cities where there are more than two employees so you can see the employee table that we had used in our group by Clause as well so if you were to find the cities where there are more than two employees so this is how your SQL queries should look like so we have selected the employee ID and we are finding out the count using the count function next we have selected the city column from employees we have grouped it by City And then we have used our having Clause so we have given our condition having count of employee ID should be greater than two so if you see the output we have the different city names and these were the cities where the count of employees was greater than two all right so let’s go to our MySQL workbench and Implement how having works so suppose you want to find those departments where the average salary is greater than $75,000 you can use the having clause for this so let me first run my table which is employees if I run this you can see we had inserted 20 rows of information and the last column we had was salary so the question we have is we want to find those departments where the average salary is greater than $75,000 so let me show you how to do it so I’ll write select Department comma I’ll use the aggregate function that is average salary I’ll give an alas name as AVG underscore salary from employees next we’ll use the group by clause and I want to group it by each department and then I’m going to write my having Clause so in having Clause I’ll use my condition that is having average of salary greater than $75,000 let’s run it and see the output there you go so here you can see there were total three departments in the company that is sales finance and HR where the average salary is greater than $775,000 okay next let’s say you want to find the cities where the total salary is greater than $200,000 so this will again be a simple SQL query so I’ll write select City comma I want to find the total salary so I’ll use the sum function and I’ll pass my column as salary as I’ll give a alas name as total from employees Group by City And then I am going to use my having Clause I’ll pass in my condition as having sum of salary greater than $200,000 all right so let’s run this query there you go so so the different cities are Chicago Seattle and Houston where the total salary was greater than $200,000 now suppose you want to find the Departments that have more than two employees so let’s see how to do it I’ll write select Department comma this time since I want to find the number of employees I’m going to use the count function I’ll write count Star as employee uncore count or empore count which is my alas name from employees next I’ll group it by Department having I’ll give my condition count star greater than 2 let’s run this okay so you have departments such as sales product Tech and it where there are more than two employees okay now you can also use a wear Clause along with the having clause in an SQL statement so suppose I want to find the cities that have more than two employees apart from Houston so I can can write my query as select City comma count Star as EMP count from employees where I’ll give my condition City not equal to Houston I’ll put it in double code since I don’t want to see the information regarding Houston I’ll group it by City having count of employees greater than two so if I run this query you see we have information for cicago and cattl only and we have excluded the information for Houston now you may also use aggregate functions in the having Clause that does not appear in the select Clause so if I want to find the total number of employees for each department that have an average salary greater than $75,000 I can write it something like this so select Department comma count star as EMP count from employees Group by department and in the having Clause I’m going to provide the column name that is not present in the select expression so I’ll write having average salary greater than 75,000 this is another way to use the having Clause let’s run this all right you can see we have department sales finance and HR and you can see the employ count where the average salary was greater than 75,000 okay so let me run you from the beginning what we did in our demo so first we created a table called employee then we inserted 20 records to this table next we explored a few esql commands like distinct then we used average and finally we started with our group by Clause followed by looking at how Group by can be used along with another table and we joined two tables that was sales and product cost table to find out the profit then you learned how to use the having Clause so we explored several different questions and learned how to use having an SQL in this session we will learn about joints in SQL joints are really important when you have to deal with data that is present on multiple tables I’ll help you understand the basics of joints and make you learn the different types of joints with Hands-On demonstrations on MySQL workbench so let’s get started with what are joints in SQL SQL joint statement or command is often used to fetch data present in multiple tables SQL joints are used to combine rows of data from two or more tables based on a common field or column between them now consider this example where we have two tables an orders table and a customer table now the order table has information about the order ID which is unique here we have the order date that is when the order was placed then we have the shipped date this has information about the date on which the order was shipped then we have the product name which basically is the names of different products we have the status of delivery whether the product was delivered or not or whether it was cancelled then we have the quantity which means the number of products that were ordered and finally we have the price of each product similarly we have another table called customers and this customer table has information about the order ID which is the foreign key here then we have the customer ID which is the primary key for this table we also have the phone number customer name and address of the customers now suppose you want to find the phone numbers of customers who have ordered a laptop now to solve this problem we need to join both the tables the reason being the phone numbers are present in the customers table as you can see here and laptop which is the product name is present in the orders table which you can see it here so using a join statement you can find the phone numbers of customers who have ordered a laptop now let’s see another problem where you need to find the customer names who have ordered a product in the last 30 days in this case we want the customer name present in the customer’s table and the last 30 days order information which you can get from the order date column that is present in the orders table okay now let’s let’s discuss the different types of joints one by one so first we have an inner joint so the SQL inner joint statement returns all the rows from multiple tables as long as the conditions are met from the diagram ADB you can see that there are two tables A and B A is the left table and B is the right table the orange portion represents the output of an inner joint which means an inner joint Returns the common records from both the tables now you can see the syntax here so we have the select command and then we give the list of columns from table a which you can see here is the left table followed by the inner join keyword and then the name of the table that is B on a common key column from both the tables A and B now let me take you to the MySQL workbench and show you how inner join Works in reality so here I’ll type MySQL you can see I have got my SQL workbench 8.0 version installed I’ll click on it it will take some time to open okay I’ll click on this local instance and here I’ll give my password okay so this is how an SQL editor on my SQL workbench looks like so first of all let me go ahead and create a new database so I’ll write create database this is going to be my command followed by the name of the database that is going to be SQL joints I give a semicolon and hit control enter this will create a new database you can see here one row affected now you can check whether the database was created or not using show databases command if I run it here you can see I have SQL joints database created now I’ll use this database so I’ll write use SQL joints okay now to understand inner join consider that there is a college and in every College you have different teams for different sports such as Cricket football basketball and others so let’s create two tables cricket and football so I’ll write create table and my table name is going to be cricet next I’m going to create two columns in this table the First Column is going to be cricet ID then I’m going to give the data type as int and use the autoincrement operator I’m using Auto increment because my Cricket ID is going to be my primary key then I’m going to give the name of the students who are part of the cricket team and for this I’ll use war card data type and give the length as 30 I’ll give another comma and I’ll assign my Cricket ID as primary key within brackets I’ll give ccore ID cricket ID is nothing but a unique identifier for each of the players like you have role numbers in college okay let me just run it all right so we have successfully created our cricket table similarly let me just copy this and I’ll paste it here I’ll create another table called football this will have the information of all the students who are part of the football team and instead of cricket I am going to give this as football idid all right and the name column will have the names of the students I’ll change my primary key to football ID all right let me run this okay so now we have also created our football table the next step is to insert a few player names into both the tables so I’ll write my insert into command first let’s load some data to our cricket table so I’ll write cricet and I’ll give my name column followed by values and here I’ll give some names such as let’s say Stuart we give another comma the next player I’ll choose is let’s say Michael similar I’ll add a few more let’s say we have Johnson the fourth player I’ll take is let’s say hidden and finally we have let’s a Fleming okay now I’ll give a semicolon and run this okay so let me just check if all the values were inserted it properly for this I’ll use select star from table that is Cricket if I run it you can see I have created a table and have successfully inserted five rows of information now similarly let’s insert a few student names for our football table so I’ll change this to football and obviously there would be students who will be part of both cricket and football team so I’ll keep a few repeated names let’s say Stuart Johnson and let’s say Hayden are part of both cricket and football team then we have let’s say Langer and let’s say we have another player in the football team that is astral I’ll just run it okay you can see there are no errors so we have successfully inserted values to our football team as well let me just recheck it I’ll write select star from football all right so we have five players in the football team as well okay now the question is suppose you want to find the students that are part of both the cricket and football team in this case you can use an inner join so let me show you how to do it so I’ll write select star from cricket as I’m using an alias name as C which stands for Cricket then I’m going to write inner join my next table is going to be football as F which is an alas name for the football table then I’m going to use the on command or operator and then I’ll give the common key that is name here so C do name is equal to F do name So based on this name column from both the table my inner John operation will be performed so let’s just run it there you go so Stuart Johnson and Hayden are the only three students who are part of both the teams all right now you can also individually select each of the columns from both the tables so let’s say I write select c. ccore ID comma C do name comma F do football ID comma f. name from I’ll write Cricket as C inner join football as F on C do name is equal to F do name now if I run this you see we get the same output here as well all right now let’s explore another example to learn more about inner joints so we have a database called classic models let me first use classic models I’ll run this okay now let me just show the different tables that are part of classic tables all right so here you can see there are tables like customers there’s employees office there’s office details orders payments products and product lines as well all right so let me use my select statement to show what are the columns present in the products table okay so this product table has information about different product names you have the product code now this product code is unique here we also have the product vendor a little description about the product then we have the quantity in stock buying price and MSRP let’s see what we have in product lines if I run it you see here we have the product line which is the primary key for this table then we have the textual description for each of the products this is basically some sort of an advertisement all right now suppose you want to find the product code the product name and the text description for each of the products you can join the products and product lines table so let me show you how to do it I’ll write my select statement and choose my columns as product code then we have product name and let’s say I want the text description so I’ll write this column name okay then I’ll use from my first table that is products inner join product lines I can use using the common key column that is product line close the bracket I’ll give a semicolon and if I run it there you go so you can see the different product codes then we have the different product names and the textual description for each of the products so this we did by joining the products table and the product lines table all right now suppose you want to find the revenue generated from each product order and the status of the product to do do this task we need to join three tables that is orders order details and products so first let me show you what are the columns we have in these three tables you have obviously seen for the products table now let me show you for orders and Order details table so I’ll write select star from orders if I run it you can see it has information about the order number the date on which the order was placed we also have the shipment date we also have the status column which has information regarding whether the order was shipped or cancelled then we have some comments column we also have the customer number who ordered this particular product similarly let’s check what we have under order details so I’ll write select star from order details if I run it you can see it has the order number the product code quantity of each product we have the price of each product then we have the order line number okay so using the product orders and Order details let’s perform an inner join so I’ll write select o do order number comma o do status comma I need the product name which I’ll take from the products table so I’ll write P do product name now here o p are all alas name for the tables orders products and I’ll use OD for order details comma since we want to find the revenue we actually need to find the product of quantity ordered into price of each product so I’ll use a sum function and inside the SU function I’ll give quantity ordered multiplied by the price of each item I’ll use an alas as Revenue then I’ll use my from Clause from orders as o inner join order details as I’ll use an alas name as OD on I’ll write o do order number is equal to OD do order number I’ll use another inner join and this time we’ll join the products table so I’ll write inner join products as p on P do product code is equal to OD do product code and finally I’ll use the group by clause and group it by order number all right let me run this okay there’s some mistake here we need to debug this it says you have an error in your SQL syntax check the manual all right okay I think the name of the tables is actually orders or not order all right now let’s run it okay there’s still some error it says classic models. product doesn’t exist so so again the product name is I mean the table name is products and not product so let’s run it again all right there you go so we have the order number the status the product name and the revenue this we got it using inner join from three different tables now talking about left joins the SQL left join statement returns all the rows from the left table and the matching rows from the right table so if you see this diagram you can see we have all the rows from the left table that is a and only the matching rows from the right table that is B so you can see this overlapped region and the Syntax for SQL left join is something like this so you have the select statement and then you give the list of columns from table a which is your left table then you use the left join keyword followed by the next table that is table B on the common key column so you write a do key is equal to B do key okay now in our classic models database we have two tables customers and orders so if you want to find the customer name and their order ID you can use these two tables so first let me show you the columns that are present in customers and orders I think orders we have already seen let me first show you what’s there in the customer table okay so you can see we have the customer number the name of the customer then we have the contact last name the contact first name we have the phone number then there’s an address column there are two address columns actually we have the city name the state and we have other information as well and similarly we have our orders table so I’ll write select start from orders so I’ll write select star from orders if I run this you can see these are the information available in the orders table okay so let’s perform a left join where we want to find the customer name and their order IDs so I’ll write select C do customer name or let’s say first we’ll choose the customer number comma then I want the customer name so I’ll write C do customer name then we have the order number column which is present in the orders table and let’s say I also want to see the status then I’ll give my left table that is customers as C left join orders as o on C Dot customer number equal to O do customer number let’s run it okay again there is some problem all right so the table name is customers let’s run it so there’s another mistake here this is customer number so B is missing cool let me run it all right so here you can see we have the the information regarding the customer number then the respective customer names we have the order number and the status of the shipment so if I scroll down you’ll notice one thing there are a few rows you can see which have null values this means for customer number 125 and for this particular customer name there were no orders and similarly if I scroll down you will find a few more null values you can see here there are two null Val values here for customer number 168 and 169 there were no orders available all right now to check those customers who haven’t placed any orders you can use the null operator so what I’ll do is here I’ll just continue with this I’ll use a where clause and write where order number is null now let me run this okay so here you can see there are 24 customers from the table that don’t have any orders in their names okay now talking about right joins so SQL right join statement returns all the rows from the right table and only matching rows from the left table so here you can see we have our left table as a and the right table as B so the right join will return all the rows from the right table and only the matching rows from the left table now talking about the syntax so here you can see we have the select statement followed by the select statement you’ll have the list of columns that you want to choose from table a write join table B on the common key column from both the tables all right now to show how write join works I’ll be using two tables that is customers and employees so let’s see the rows of data that are present in the customer table first so I’ll write select star from customers let’s run it so here you have the customer number the customer name then we have the phone number the address of the customers you also have the country to which the customer belongs to the postal code and the credit limit as well similarly let’s see for the employees table here I’ll change customer customers to employees let’s run it okay so we have the employee number the last name the first name you have the extension the email ID the job title and also reports to here means the manager okay so based on these two tables we’ll find the customer name the phone number of the customer and the email address of the employee and join both the tables that is customers and employees so let me show you the command so I’ll write select C do customer name comma then we have C do phone I’ll give a space here next I want the employee number from the employee table so I’ll write e do employee number comma e do email from customers as C right join employees as e on E do my common key column is employee number here so I’ll write e do employee number is equal to C dot we have sales Representatives employee number and I’m also going to order it by the employee number column okay so you can see I have my customer name selected from the customers table the phone number of the customer then we have the employee number and the email address so let me run it okay there’s some problem all right so the table name is customers actually let’s run it once again there you go so you can see here we have all the values selected from our right table which is the employees table you can see right on employees which means your employees table is to the right and then we have the customer name and phone numbers of the customers from the customer table which is actually your left table so you have a few employee number such as one2 this 1056 which don’t have any customer name or phone numbers okay so there’s another popular join which is very widely used in SQL known as self joints so self joints are used to join a table to itself so in our database we have a table called employees let me show you the table first all right so here you can see we have the employee number the last name the first name of the employee you have the email ID and here if you see we have a column called reports 2 now this you can think of as the manager column so the way to read is for example for employee number 1056 the manager is one2 so if you check for one2 we have Dane Murphy then if I scroll down let’s say for employee number 1102 yeah for employee number 1102 the manager is 1056 so here you can see who is at 1056 you have Mary Patterson similarly if I scroll down let’s say for employee number 11 188 we have the manager as 11 43 now if I check the table at 1143 we have Anthony bow so so the employee Julie feli reports to Anthony bow all right now suppose you want to know who is the reporting manager for each employee so for that you can use a self jooin so let me show you how to join this employees table I’ll write select and then I’m going to use a function called concat within brackets I’ll start with my alas name that is m dot then I’ll write last name I’m going to concat last name followed by a comma then I’ll have my first name I’ll close this bracket and then I’m going to give my alas name let’s say manager here comma next I’m going to concat the same last name and first name and this time I’m going to use a separate alas let’s say e which stands for employee so I’ll write e do last name comma and within single codes I’ll give my comma and then I’ll write e do first name I close this bracket I’ll give an alas as let’s say employee from I’ll write employees as e inner join employees as M on M do I’ll use my common key column as employee number so I’ll write M do employee number is equal to e do here I’m going to use the reports two column and then I’ll order it by let’s say manager okay now let’s run this there you go so you have your two columns as manager and employee so for employee Louie bonder the manager is zarad bonder similarly if I scroll down you have there are multiple employees reporting to this particular manager similarly we have our manager as Anthony bow and we have different employees who are reporting to this particular manager and so on all right now moving ahead now let’s see what a full join is so SQL full outer join statement returns all the rows when there is a match in either left or right table now you must remember that MySQL workbench does not support full outer join by default but there’s a way to do it so by default this is how the syntax of full outer joint looks like now this statement will work on other SQL databases like micros moft SQL server but it won’t work on MySQL workbench I’ll show you the right way of using full auto join on MySQL workbench so to show full outer join I’m going to first use a left join and then we’ll also use a right join and finally we’ll use a union operator so the union operator is used to combine the result set of two or more select statements so first of all let me write C do customer name so for this example I’m using the customer table and the order table comma o do order number so I just want to know the customer name and the order number related to the customer from I have customers as C left join I’ll write orders as o on C do customer number is equal to O do customer number let me just copy this and after this I’m going to use my union operator so Union operator is used to merge results from two or more tables so basically this performs a vertical join and next I am going to use my right join operation so here instead of left join I’ll write right rest all looks fine let me just run it there you go so we have successfully run our full outer join operation you can see we have the different customer names and the order that each customer had placed all right so that brings us to the end of our demo session so let me just run through whatever we did in this session so first we created a database called SQL joints then we created two tables like cricket and football then we had inserted a few rows to each of these tables then we used this table to learn about inner join next we used a database called classic models it had multiple tables so we explored all of these tables like products there was product lines orders customers and employees and learned how to use inner join left join self join right join as well as full outer join in this video we will learn what is a subquery and look at the different types of subqueries then we learn subqueries with select statement followed by subqueries with insert statement moving further we will learn subqueries with the update statement and finally we look at subqueries with delete statement all these we will be doing on our MySQL workbench so before I begin make sure to subscribe to the simply learn Channel and hit the Bell icon to never miss an update so let’s start with what is a subquery so a subquery is a select query that is enclosed inside another query so if I show you this is how the basic structure of a subquery looks like so here whatever is present inside the brackets is called as the inner query and whatever is present outside is called the outer query so first the inner query gets executed and the result is returned to the outer query and then the outer query operation is performed all right now let’s see an example so we have a question at hand which is to write a SQL query to display Department with maximum salary from employees table so this is how our employees table looks like it has the employee ID the employee name age gender we have the date of join Department City and salary now to solve this query my subquery would look like this so I’ll first select the department from my table that is employees where I’ll use the Condition salary equal to and then I’ll pass in my inner query which is Select Max of salary from employees so what this does is it will first return the maximum salary of the employees in the table then our outer query will get executed based on the salary returned from the inner query so here the output is department sales has the maximum salary so one of the employees from the sales department earns the highest of the maximum salary if you see in our table the employee is Joseph who earns $115,000 all right and Joseph is from the sales department now let’s see how this query works so here we have another question which is to find the name of the employee with maximum salary in the employees table so this is our previous employees table that we saw and to find the employee who has the maximum salary my subquery would look something like this so I’m selecting the employee name from my table that is employees where I’m using the Condition salary equal to and then then I’m passing in my subquery or the inner query so first I’m selecting the maximum salary this will return a particular value that is the highest salary from the table and if you see our table the highest salary is $115,000 so our query becomes select employee name from employees where salary equal to $115,000 so the employee name is Joseph here and that’s the output now if you want to break it down here you can see first the inner query gets executed so our SQL query will first execute the inner query that is present inside brackets select maximum salary from employees the result is $115,000 and then based on the returned result our outer query gets executed so the query becomes select employee name from employees where salary equal to $115,000 and that employee is Joseph all right now we’ll learn the different types of subqueries so you can write subqueries using select statement update statement delete and insert statement we’ll explore each of this with the help of example on my my SQL workbench so let’s learn subqueries with the select statement so subqueries are majorly used with the select statement and this is how the syntax looks like you select the column name from the table name then you have the WHERE condition followed by The Columns that you want to pass the operator and inside that you have the subquery so here is an example that we will perform on our MySQL workbench so in this example we want to select all the employees who have a salary less than average salary for all the employees this is the output so let’s do this on my MySQL workbench all right so let me log into my local instance I’ll give my password okay so you can see I’m on my MySQL workbench so let’s start by writing our subquery using the select statement okay so for this demo session we’ll be using a database that is subqueries you can see it here I have a database called subqueries so I’ll use this subqueries database and we’ll create a few tables as well okay if I run it now we are inside the subqueries database so let me just show you the tables that are present inside this database I’ll write show tables if I run it okay there are two tables employees and employees undor B uh we’ll use this table throughout our demonstration all right now for our select subquery we want to fetch the the employee name the department and the salary whose salary is less than the average salary so we will be using the employees table so let me first show you the records and the columns we have in the employees table so I’ll write select star from employees and run it okay you can see here we have 20 rows of information we have the employee name the employee ID age gender date of join Department City and salary so this is the same table that we saw in our slide slides okay now for our subquery I’ll write select I want to choose the employee name the department and the salary there should be a comma here instead of a period next I’ll give my table name that is employees where my salary is less than and after this I’ll start my inner query or the subquery I’ll write select average salary so I’m using the AVG function to find the average salary of all the employees from my table that is employees if I give a semicolon and run this you’ll see the output so we have total 12 employees in the table whose salary is less than the average salary now if you want you and check the average salary so the average salary is $753 now the employees who have a salary less than the average salary so these are the people all right now moving back to our slides okay now let’s see how you can use subqueries with the insert statement now the insert statement uses the data return from the subquery to insert into another table so this is how the syntax looks like so you write insert into table name followed by select individual column so start from the table use the wear clause and then you give the operator followed by the inner query or the subquery so here we will explore a table called products table we are going to fetch few records from the products table based on a condition that is the selling price of of the product should be greater than $100 so only those records will fetch and put it in our orders table all right so we are going to write this query on my MySQL workbench so let’s do it I’ll give my comment as update subquery all right so first of all let’s create a table that is products so I’ll write create table products then we’ll give our column names the First Column would be the product ID of type integer then we have the column as item or the product which is of type Vare 30 next we have the selling price of the product the selling price will be of type float and finally we have another column which is called the product type and again product type is of the data type bar car I’ll give the size as 30 close the bracket and give a semicolon now let’s just run it okay so we have successfully created our products table now let’s insert a few records to our products table so I’ll write insert into products for followed by values I’ll give four records the first product ID is 101 the product is let’s say jewelry then the selling price is let’s say $800 and the product type is it’s a luxury product next let’s insert one more product detail the product ID is 102 the product is let’s say t-shirt the price is let’s say $100 and the product type is non-luxury next I’ll just copy this to reduce our task we’ll edit this the third product’s ID is 103 the product is laptop and let’s say the price is $1,300 and it’s a luxury product I’ll paste again and finally I’ll enter my fourth product which is let’s say table and the price is $400 and it’s a non-luxury product I’ll give a semicolon and we’ll insert these four records to our products table you can see see we have inserted four records let’s just print it now so I’ll write select star from products if I run it you can see we have our four products ready now we need to create another table where we are going to put some records from our products table so that new table is going to be the orders table so I’ll write create table orders now it will have three columns the order ID order ID will be of type integer then we have product underscore sold this will be of type varing character of size 30 and finally we have the selling price column this will be of type float let’s create our orders table the table name should be orders and there is some mistake here okay we should close the brackets okay let me run it so we have our orders table ready now let’s write our insert subquery so I’m going to insert into my table that is orders and I’ll select the product ID comma the item and the selling price or the sell price from my table that is products where I’ll write product ID in I’ll write my inner query select prodad ID or the product ID from products next I’ll give a wear Clause where the selling price is greater than $11,000 so let me tell you what I’m going to do here I’m going to insert into my orders table the product ID the item name and the s selling price from my products table where the product ID has this condition so let me first run this condition for you which is Select prod ID from products where the selling price is greater than 1,000 if I run this okay there is some issue here the column name is actually prodad ID now let’s run it again so that we can see the product IDs of the products which have a selling price greater than 1,000 so it is 101 and 103 now let’s run the entire query there is another mistake here let’s debug the mistake now this should be product ID instead of product _ in let’s insert again all right so we have successfully inserted two records to our table that is orders now let’s see the orders table I’ll write select star from orders if I run it there you go so there were two products from our product table that were jewelry and laptop which have a selling price greater than $11,000 so the selling price for jewelry was $1,800 and for laptop it was $1,300 so this is how you can use a subquery using the insert statement all right now going back to our slides again all right now let’s see how you can use subqueries with the update statement now the sub sub queries can be used in conjunction with the update statement so either single or multiple columns in a table can be updated when using a subquery with the update statement so this is how the basic syntax of an update subquery looks like so you write update table followed by the table name you set the column name you give the we operator and then you write your inner subquery so we are going to see an example where we’ll use this employees table and using this employees table we will update the records of the salaries of the employees by multiplying it with a factor of 35 only for those employees which have age greater than 27 so we are going to use a new table called employees Corb for this as well so let’s see how to do it so I’ll give my comment as update subquery before we see the subquery let’s see what we have in the table employees Corb this is basically a replica of the employees table there you go it has the same records that our employees table has we are going to use both the employees table and the employees _ B table to update our records so I’ll write update employees set salary equal to let me bring this to the next line I’ll write set salary equal to salary multiplied by 35 where age in then I’ll write select age from my other table that is employees uncore B where age is greater than equal to let’s say 27 all right so let me run through this query and tell you what we are going to do so I’m going to update the records of the employees table specifically for the salary column so I’m checking if the age is greater than 27 then we’ll multiply the salaries of the employees with a factor of. 35 in the employees table let me just run this then we’ll see our output okay so it says 18 rows affected which means there are total 18 employees in the table out of the 20 employees whose age is greater than 27 now if you see I’ll write select star from employees you can see the difference in the salaries if I scroll to the right you can see these are the up updated salaries okay now if you check for employees who have an age less than or equal to 27 for example Marcus whose age is 25 his salary is the same we haven’t updated his salary then if you see if you have okay there is one more employee Maya we haven’t updated the salary of Maya because the age is less than 27 all right now let’s go back to our slides again as you can see we got the same output on our MySQL workbench now let’s explore how you can write subqueries with the delete statement now sub queries can again be used in conjunction with the delete statement so this is how the basic syntax of a delete query using subquery would look like you write delete from the table name where Clause the operator value followed by the inner query in within brackets so here we are going to use the employees table and what we are going to do is we’ll delete the employees whose age is greater than equal to 27 so let’s see how you can do it all right so I’ll give my comment as delete subquery so we’ll follow the syntax tax that we saw I’ll write delete from my table name that is employees I’ll write where age in and then I’ll start my inner query or the subquery I’ll write select age from employees uncore B where AG is let’s say greater than equal to 32 or let’s say the AG is less than equal to 32 close the bracket and I’ll give my semicolon let me first run the inner query for you so that you get an idea of the employees who are less than 32 years of age so there are nine employees in the table who have an age less than equal to 32 so we are going to delete the records if I run this okay it says nine records deleted now let’s print or display what we have in the employees table if I run this there you go so if you see the age table we have total 11 employees now and all their ages are greater than 32 because we have deleted all those employees who had an age less than equal to 32 okay so let me show you from the beginning what we did so first we used our subqueries database then we used our employees table so we started by looking at how you can use the subquery with a select statement this should be insert instead of update so we learned how to write an insert subquery we use two tables products and our a table moving ahead we saw how to write subqueries using the update command so we updated the salaries of the employee by a factor of. 35 for those who had an age greater than equal to 27 and finally we saw how to use the subquery using the delete statement so we deleted all those records for the employees whose age was less than equal to 32 so let’s start with what is normalization normalization in dbms is a method used to organize data within database to reduce repetition by breaking down large data sets into smaller more manageable tables and ensuring these tables are properly related normalization helps prevent issues like data rency data rency means the unnecessary repetition or duplication of data within a database for example when a same piece of data is stored in multiple places it can lead to inconsistencies and take up more storage space than needed for example Data rency before normalization you can see the table mentioned above where we have order ID customer ID customer name customer address product and quantity you might see some of the data which is being repeated again and again in the above table the customer address for John do is repeated three times let’s suppose if John do moves to a new address every occurrence of his address in the table must be updated if any instances missed during the update it leads to inconsistencies and errors can occur in the database the solution is reducing the rency through normalization let’s check it out how so you can see this is the normalized table we have created first is the normalized customer table and then we have the order table so what are the benefits of normalization the address for JN do is stored only once in the customer table if JN do address changes it needs to be updated in one place ensuring consistency through the database this reduces the risk of errors and maintains data Integrity the process involves multiple steps that transform data into a tab below format removing duplicates and establishing clear connections between different tables making the database more efficient and reducing problems like errors during data insertion updates or deletion let’s now discuss the types of dbms normal forms normalization rules are categorized into different normal forms the first one is one and if for a table to be in first normal form it must satisfy the four rules single valued Atomic attributes each column should contain only one value per row this means that there should be no repeating groups or arrays within a single column same domain values all values stored in a specific column should be of the same data type or domain for example if a column is meant to store dates all values in that column should be dates then we have unique column names each column in the table should have a unique name this ensures Clarity and avoids confusion when referring to a specific column then we have order of data which doesn’t matter the order in which rows are stored in the table should not affect the data or its Integrity let’s check the example of the first normal form consider the following unnormalized table customer ID customer name and the phone numbers as you can see the phone numbers are repeated twice the problems with the original table is the nonatomic values the four numbers column contain multiple phone numbers separated by commas which violates the atomicity rule of 1 andf converting to First normal form to bring this table into one and F we must ensure that each column contains only Atomic value this involves splitting the rows where there are multiple phone numbers as you can see we have splitted the data each row now has a single phone number ensuring that the phone number column contains Atomic value same domain names all the values in the phone number column are consistent in format and type all are phone numbers then we can see that the unique column names the colums customer ID customer name phone number which has unique name satisfying the requirement order of data the order in which the rules appear does not matter as the data’s meaning and integrity are preserved by applying these rules the table now confirms the first normal form eliminating any rency related to the four numbers and ensuring data is stored in a more organized and efficient manner let’s go through each of these database normal forms step by step with simple examples to help you grasp the concepts more easily let’s talk about the second normal form for a table to be in second normal form it must satisfy the following condition number one it must be in one and F number two no partial dependency every non key attribute should be fully dependent on the entire primary key not just part of it this rule applies primarily to tables with composite primary Keys example of second normal form is consider the following table that is in one NF the order ID product ID product name quantity and the supplier name the problems with this table is that the partial dependency the product name and the supplier name depend only on product ID not the entire bio primary key which is order ID and product ID this violates 2nf converting to Second normal form to bring the table into 2nf we separate the data into two tables to remove partial dependencies order table and the product table no partial dependency in the order table quantity is fully dependent on both order ID and product ID in the product table product name and supplier name are dependent only on the product ID this ensures that each each non key attribute is fully dependent on the primary key bringing the tables into 2 andf let’s now talk about the third normal form 3 andf for a table to be in third normal form it must satisfy the following condition number one it must be in 2 andf number two there should be no transitive dependency where non-key attributes depend on other non-key attributes rather than the primary key let’s check out the example of a third normal form consider the following table that is in 2nf the problems with the tnf table is that the transitive dependency the instructor name is dependent on the course name which is not directly on student ID or course ID and this violates 3 andf so how do we convert this into 3 andf to achieve 3 andf we split the table to remove the transitive dependency student course table and course table no transitive dependency now the student course table there are no non-key attributes depending on other non-key attributes the course Table stores the course and instructor information separately this structure eliminates transitive dependency uring the tables conform to 3 andf Let’s now talk about the boys called normal form which is bcnf bcnf is an extension of the third normal form 3nf a table is in bcnf if it is in 3nf and for every functional dependency a implies to B A should be a Super Key let’s check out the example of a boy Squad normal for bcnf so you can see this table here consisting of employee ID department and the manager the problem with this table is that the bcn a violation in this table Department determines manager but department is not a Super Key since employee ID is the primary key this violates bcnf so how do we convert this to bcnf to achieve bcnf we split the table to ensure that every determinant is a Super Key as you can see the employee table and the department table the super key requirement in the employee table employee ID is the primary key and in the department table department is now the primary key the decomposition ensures that every functional dependency is Satisfied by a Super Key meeting the requirements of bcnf let’s now talk about the fourth normal form which is 4nf a table is set to be in 4nf if it is in bcnf and has no multivalue dependencies so let’s consider an example of a fourth normal form consider a table where an employee can have multiple skills and work on multiple projects as you can see the employee ID skill and the project the problem with this table is that it is multivalue dependency an employee skill is independent of the project but both are stored in the same table this leads to multivalue dependency violating 4nf so in order to achieve 4nf we separate the skills and the projects into different tables the employee skill table and the employee projects table and now you can see that no multivalue dependency by separating the skills and the projects we eliminate multivalue dependencies ensuring the table conform to for and let’s now talk about the fifth normal form the employee skill table and the employee projects table so as you can see that no multivalue dependencies is there by separating the skills and the projects we eliminate multivalue dependencies ensuring the tables conformed to 4 and F now let’s talk about the fifth normal form which is 5 and f a table is said to be in fifth normal form if it is in forf and cannot be decomposed into any smaller tables losing information also known as joint dependency let’s consider an example of a fifth normal form this is a table here that records the relationship between suppliers parts and the project the problem with this table is that the join dependency the table has a complex relationship between suppliers parts and projects that can be decomposed further so how do we convert this into fifth normal form form in order to achieve 5 andf we break the table into smaller related tables the suppliers part table and the suppliers project table also Parts project table eliminating joint dependency by decomposing the table into three smaller tables we remove the complex relationship and eliminate the joint dependency ensuring the tables confirmed to 5 andf So currently I am on my MySQL workbench let me connect to the local instance so I’ll give my pass word I’ll click on okay all right so this is my my SQL workbench query editor so first we are going to learn subqueries let me give a comment and write subqueries all right so first of all let’s understand what a subquery is so a subquery is a query within another SQL query that is embedded within the where Clause from clause or having Clause so we’ll explore a few scenarios where we can use subqueries so for that I’ll be using my database that is SQL uncore intro so I’ll write my command use SQL uncore intro now this database has a lot of tables I’ll be using the employees table that is present inside SQL intro Let me just expand this and you can see here we have an employees table so let me first show you the contents within this table I’ll write select star from employees let me execute it okay you can see here we have the employee ID employee name age gender there’s date of join Department City and salary and we have information for 20 employees if I scroll down you can see there are 20 employees present in our table so let’s say you want to find the employees whose salary is greater than than the average salary in such a scenario you can use a subquery so let me show you how to write a subquery I’ll write the select statement in the select statement I’ll pass my column names that I want to display so the column names I want are the employee name then I want the department of the employee and the salary of the employee from my table name that is employees next I’ll use use a we condition where my salary should be greater than the average salary of all the employees so I’ll write salary greater than after this I’m going to write my subquery so I’ll give select average of salary from my table name that is employees and I’ll close the bracket and give a semicolon so what it does is first it is going to find the average salary of all the employees that are present in our table once we get the average salary number we’ll use this wear condition where salary is greater than the average salary number so the inside subquery let me run it first if I run this this gives you the average salary of all the employees which is $275,300 now I want to display all the employees who have salary greater than $75,500 so let’s run our subquery there you go so there are eight employees in our table who have a salary greater than the average salary of all the employees all right next let’s see another example suppose this time you want to find the employees whose salary is greater than John’s salary so we have one employee whose name is John let me run the table once again okay if I scroll down you see we have an employee as John you see this our employee ID 116 is John and his salary is $67,000 I want to display all the employees whose salary is greater than John’s salary so B basically all the employees who are earning more than $65,000 I want to print them so let’s see how to do it I’ll write select I want the employee name comma the gender of the employee I also want the department and salary from my table name that is employees I’ll write where salary is greater than I’ll start my opening bracket inside the bracket I’m going to give my inner query that is Select salary from employees where the employee name is John So within single quotations I’ll give John as my employee I’ll end with a semicolon so let me first run my inner query so this will give us the salary that John has which is $67,000 now I want the employees who are earning more than $667,000 so let’s run our subquery okay so you can see 12 rows returned which means there are 12 employees in our table who are earning more than $67,000 you see here all these employees have a salary greater than6 $7,000 okay now you can also use subqueries with two different tables so suppose you want to display some information that are present in two different tables you can use subqueries to do that so for this example we’ll use a database that is called classic models you can see the first database so let me use this database called classic Model models I’ll write use classic models now this database was actually downloaded from the internet there’s a very nice website I’ll just show you the website name so this is the website that is MySQL tutorial.org you can see here they have very nice articles blogs from where you can learn my SQL in detail so we have downloaded the database that is classic models from this website you see here they have a MySQL sample database if you click on this it will take you to the link where you can download the database so they have this download link which says download my SQL sample database and the name of the database is classic Models All right so we are going to use this classic models database throughout our demo session if I expand the tables section you can see see there are a lot of tables that are present inside this classic models database we have Cricket customers there’s employees office there’s orders order lines and many more so for our subquery we’ll be using two tables that is order details and products table first let me show you the content that is present inside the products table first if I run this you see here it says 110 rows returned which means there are 110 different products that are present in our table which has the product code the product name product line we have the product vendor description quantity and stock Buy price MSRP the other table we are going to use is order details which has the details of all the orders let me show you the records order details tables has okay so there are thousand records present in this table you have the order number the product code quantity ordered price of each item you have the order line number as well okay now we want to know the product code the product name and the MSRP of the products whose price of each product is less than $100 for this scenario we are going to use two different tables and we are going to write a subquery okay so if you see here in the order details table we have a column called price each I want to display the product code the product name and the MSRP of the products which have a price of each product less than $100 so the way I’m going to do is I’ll write select product code comma product name now one thing to remember that this product name is actually present inside our products table and product code is present in both the tables that is products and Order details here you can see this is the product code column comma MSRP which is present inside the products table again from my table that is products where I’ll write product code I’m going to use the in operator next I’ll write my inner query that is Select product code from my table order details where my price of each product is less than $100 let me run this okay so you can see there are total 83 products in our table which have a price less than $100 you can see the price here okay now we learn another Advanced Concept in SQL which is known as stored procedures I’ll just give a comment saying stored procedure okay so first let’s understand what is a stored procedure a stored procedure is an SQL code that you can save so that the code can be reused over and over again so if
you want to write a query over and over again save it as a stored procedure and then call it to execute it so in this example I want to create a stored procedure that will return the list of players who have scored more than six goals in a tournament so I have a database is called SQL IQ these are a few databases that I’ve have already created so this database has a table called players if I expand the tables option you see we have a table called players and you can see the columns player ID the name of the player the country to which the player belongs to and the number of goals each player has scored in a particular tournament so I’ll write a store procedure that will return the list of top players who have scored more than six goals in a tournament so first of all let me Begin by using my SQL IQ database we’ll run it so now we are inside the SQL IQ database let me select star from players to show the values that we have in the players table you can see there are six players in our table we have the player ID the names of the players the country to which these players belong to and the goals they have scored so I’ll write a stored procedure so the stor procedure syntax is something like this it should start with a D limiter okay in the D limiter I’ll write Amberson erson next I’ll write create procedure followed by the procedure name let’s say I want to name my procedure as topor players next statement is begin after begin I’ll write my select statement I want to select the name of the player the country and the goals each player has scored from my table that is players where I’ll write goals is greater than six we give a semicolon then I’ll end my procedure with a d limiter that was done double Amberson next I’ll write D limiter and give a semicolon now the semicolon suggests this is a default DM there should be a space okay now let’s run our stored procedure there you go so you have successfully created our store procedure now the way to run a store procedure is you need to use the call method and give the procedure name that is topor players in our case with brackets and a semicolon let’s execute it okay there is some problem here so we made a mistake while creating a procedure the name of the column is goals and not go goal let me create that procedure again okay it says the procedure topor player already exists let’s just edit the procedure name instead of top player we’ll write it as top players and similarly we’ll edit here as well now let’s create it again okay now to call my procedure I’ll write call space followed by the procedure name which is topor players if I run this you can see we have two players in our table who have scored more than six goals so we consider them as the top players in a particular tournament all right now there are other methods that you can use while creating a stored procedure one of the methods is by using an in parameter so when you define an in parameter inside a stored procedure the calling program has to pass an argument to the stored procedure so I’ll give a comment stored procedure using in parameter all right so for this example I’ll create a procedure that will fetch or display the top records of employees based on their salaries so if we have a table in our SQL IQ database which is called employee details I’m going to use this table you can see we have the name of the employee the age sex then we have the date of join City and salary using this table I’ll create a procedure that will fetch or display the top records of employees based on their salaries and we’ll use the in parameter so let me show you how to do it I’ll write delimiter this time I’m going to use forward slash I’ll write create procedure followed by the procedure name let’s say SP for stor procedure sort by salary is the name of my procedure and inside this procedure I’ll give my parameter in I’ll create a variable V and assign a data type integer then I’ll write begin followed by my select statement where I’ll select the name age salary from my table name that is EMP details or employee details I’m going to order this by salary descending and I want to display limited number of Records so I’m using this limit keyword and my variable V which I created here here I end my select statement I end my stored procedure with forward slash and I’ll go back to my default delimiter that is semicolon all right so let me run this there should be a space here all right so let’s run this okay you can see we have successfully created our second stored procedure which is Spore sort by salary now you can also check whether the stored procedure was created or not here you have an option to see the stored procedures let me just refresh this and you can see we have three stored procedures that we have created so far one is Spore sort by salary the other two were topor play and topor players okay now let’s call our stor procedure I’ll write call space followed by the stored procedure name which is Spore sort by salary and inside this I’ll give my parameter which was actually V and this V we have used in limit let’s say I want to display only the top three records of the employees who have the top three highest salaries okay so let me run it there you go so ammy Sara and Jimmy were the top three employees who have the highest salary so you saw how you could use the in parameter in a stored procedure we created a variable and that variable we used in our select statement and we called our stored procedure and passed in that variable okay now instead of a select statement inside a stored procedure you can also use other statements let’s say update so I’ll create a stored procedure to update the salary of a particular employee so in this procedure instead of Select statement we’ll use the update command in this example we’ll use the in operator twice let me show you how to do it I’ll write my D limiter first which is going to be for slash then I’ll write create procedure my name of the procedure is going to be update salary and inside the update salary name I’ll write in and then temp underscore name which will be a temporary name variable and the type I’ll assign is varar 20 I’ll again use my in parameter I’ll write in next my other variable would be newcore salary and the data type would be float I’ll write begin and write my update command or update statement I write update table name that is employee details set salary equal to newcore salary where name is equal to my temporary variable that is tempore name so this is my update command and I’ll and the delimiter all right so let’s run this okay we have successfully created our stored procedure if I refresh this you can see I have my store procedure update _ salary okay now let’s say first of all I’ll display my record that are present inside employee _ details table okay so we have six rows of information let’s say you want to update the salary of employee Jimmy or let’s say Mary from 70,000 to let’s say 72,000 or let’s say 80,000 so I’ll call my store procedure that is update uncore for salary and this time I’m going to pass in two parameters the first parameter will be the employee name and next with a comma I’ll give my new salary that I want to so my employee name let’s say is Mary and the salary I want to be updated is let’s say $880,000 I’ll give a semicolon and I’ll run it you can see it says one row affected now let’s check our table once again there you go if you see this record for Mary we have successfully updated the salary to $80,000 now moving ahead we learn to create a stored procedure using the out parameter so I’ll give a comment stor procedure using out parameter Okay so so suppose we want to get the count of total female employees we will create total employees as an output parameter and the data type would be an integer the count of the female employees is assigned to the output variable which is total uncore emps using the into keyboard let me show you how to write a stored procedure using the out parameter so first I’ll declare my delimer to forward slash I’ll write create procedure followed by the procedure name it is going to be Spore count employees and inside this I’m going to give my out parameter and the variable name that is total uncore emps which is total employees and the data type will be integer next I’m going to write begin followed by my select statement that is Select I want the count of total employees and the output I’m going to put into my new variable that is total _ emps from my table that is empore details where sex is equal to F which means female I’ll give a semicolon next I’ll end it with the D limiter and I’m going to change the D limiter to a default D limiter that is colon so let me tell you what I’m doing here I’m creating a new stor procedure that is Spore count employees using this stored procedure I’m going to count the total number of female employees that are present in our table empore details so I’ve used my out parameter and I’m creating a new variable called total uncore emps the data type is integer here in the select statement I’m counting the names of the employees and the result I’m storing it in total _ emps I have used my wear condition where the gender of the sex is female so let’s run this okay so we have created our stored procedure let’s refresh this okay you can see we have our new stored procedure Spore count employees now to call it I’ll write call the name of the procedure that is countor Spore count employees within brackets I’ll pass in the param meter as at the rate fcor EMP I’ll give a semicolon then I’ll write select at the rate fcor EMP as female employees okay so as is an alias name let’s run this one by one first I’ll call my procedure and then we’ll display the total number of female employees you can see in our table we have three female employees all right now with this understanding let’s move on to our next Topic in this tutorial on Advanced SQL now we are going to learn about triggers in SQL so I’ll give a comment here triggers in SQL so first let’s understand what is a trigger so a trigger is a special type of stored procedure that runs automatically when an event occurs in the database server there are mainly three types of triggers in SQL we have the data manipulation trigger we have the data definition trigger and log triggers in this example we’ll learn how to use a before insert trigger so we will create a simple students table that will have the students role number the age the name and the students marks so before inserting the records to our table we’ll check if the marks are less than zero so in case the marks are less than Z our trigger will automatically set the marks to a random value let’s say 50 so let’s go ahead and create our table that is students all right so I’ll write create table student now this table will have the student role number the data type is integer we will have the age of the students again the data type is integer we have the names of the students so the third column would be name the data type would be variable or varying character size I’m giving it as 30 finally we have the marks as floating type so let’s create this table which is student so we have created our table now I’ll write my trigger command so trigger command will start with D limiter like how our usual stored procedures have next this time I’ll write create trigger then you you need to give the name of the trigger that is Mark underscore let’s say verify I’m going to use a before insert trigger so I’ll write before insert on my table name that is student next I’ll write for each row if new do marks is less than zero then we set new do marks equal to 50 so this is my condition first we’ll check before inserting if any student has marks less than zero will assign a value 50 to that student because usually the marks are not less than zero in any exam I’ll write end if semicolon and I’ll close the delimiter so this is my trigger command I’ll run it it says trigger already exists in this case we need to update the trigger name let’s say I’ll write marks _ verify uncore student for STD let’s run it again okay there is an error here because in our table the column name is Mark and not marks so here we need to change it as Mark instead of marks all right let’s run it okay so we have created our trigger now let me insert a few records to the student table so I’ll write insert into student I’ll write values it give the values as 501 which is the student role number the age is let’s say 10 the name is let say Ruth and the marks is let’s say 75.0 give a comma we’ll insert our second student record student role number is 502 age is 12 the name is let’s say mic and this time I’m purposely giving a value of minus 20.5 give another comma we’ll insert the third record for student role number 503 age is 13 the name is Dave and let’s say the marks obtained by Dave is 90 now we’ll insert our final record for student number 504 the age is 10 name I’ll enter as Jacobs and this time again I’m purposely giving the marks in negative 12 point let’s say 5 close the bracket and give a semicolon and I’ll run my insert statement okay so we have inserted four rows of information to our student table now let me run the select query I’ll write select star from student if I run this you see the difference there you go so originally we had inserted for 502 the marks was minus 20.5 and for 504 for Jacobs the marks was – 12.5 our trigger automatically converted the negative marks to 50 because when we created our trigger we had set our marks to 50 in case the marks were less than zero so this is how a trigger works now you can also drop a trigger or delete a trigger you can just write drop trigger followed by the trigger name in this case our trigger name is marks _ verore St I’ll just paste this here and if you run this it will automatically delete your trigger I give this as a comment okay now moving on now we are going to learn about another crucial concept in SQL which is very widely used this is known as views so views are actually virtual tables that do not store any data of their own but display data stood in other tables views are created by joining one or more tables I’ll give a comment as views in SQL okay now to learn views I’m going to use my table which is present inside classic models data datase now this database as I mentioned we had downloaded we had downloaded it from the internet so first of all let me write use classic models so I’ll switch my database first all right now we are inside classic models so here let me show you one of the tables which is called customers so I’ll write select star from customers okay I missed s here let’s run it again so this is my customer table which is present inside classic models database it has the contact last name the contact first name the customer name customer number we have the address State country another information now I’ll write a basic view command using this customer table the way to write is I’ll write create view followed by The View VI name which is cust _ details then you write as select I’m going to select a few column names from my original customer table which is this one so I need the customer name let’s say I need the phone number and the city so you have this information here you have the phone number and the city all right I’ll write from my table that is customers if I run this my view that is cust details will be created let’s run it there’s some error here because the name of the table is customers and not customer I’ll give an S and I’ll run it again all right so you can see we have created our view and to display the contents that are present inside our view I can write select star from followed by The View name that is custor details let’s run it there you go so we have the customer name the phone number and the City of the different customers that we have in our table all right now let’s learn how you can create views using joins so we’ll join two different tables and create a view so for that I’m going to use my products table and the products lines table I’m talking about the products table and the product lines table present inside classic models database so before I start let me display the records that are present inside the products table let’s run it so these are the different products you can see here now let’s see what we have in product lines table so we have the product line the text description and there’s some HTML description and image so I’ll create a view by joining these two tables and we’ll fetch specific records that are present in both the tables so let me first start by writing create view followed by The View name that is product underscore description as I’ll write select product name comma then I’ll write quantity in stock I also want the MSRP now these three columns are present inside the products table and next from the product l table I want the text description of the products so I’ll write from products table I’ll give an alas as P followed by Inner join my other table that is product lines as let’s say PL on the common column that is product line so P dot product line is equal to I’ll give a space PL do product line okay so here we have used an inner joint to fetch specific columns from both the tables and our view name is productor description let us run it all right so we have our view ready now let me view or display what is present inside our productor description view I like select star from productor description let’s run it there you go so we have the product name the quantity in stock MSRP and textual descriptions of the different products in the table okay now there are are a few other operations that you can perform let’s say you want to rename a view instead of productor description you want to give some other name so I’ll just give a comment rename description so to rename a description you can use the rename statement I’ll write rename table product underscore description Which is my old name I want to change this name to let’s say I’ll give vehicle description since all our products are related to some of the other vehicle so I’ll write vehicle description okay let us run it all right so here you can see I have renamed my view so here if I just refresh it and I’ll expand this you can see we have the Cur details view and we have the vehicle _ description view okay now either you can view all the views from this panel or you can use a command let’s say I’ll write display views is the comment now to show all the views you can use show full tables where table underscore type is equal to within single code I’ll write view so this is the command that will display all the views that are present inside a database there is some error here let’s debug the error this should be okay so instead of table types it should be table type equal to view let’s run it you can see the two different views that we have one is customer details another is vehicle _ description okay now you can also go ahead and delete a view for that you can use the drop command so I’ll write drop view followed by The View name let’s say I want to delete customer _ details or custor details view I’ll write drop View ccore details let’s run it you can see here we don’t have the custor details view anymore all right now moving to our final section in this demo here we will learn about Windows functions Windows functions were Incorporated in my SQL in the 8 .0 version so Windows function in my SQL are useful applications in solving analytical problems so using the employees table present inside my SQL intro database so we’ll find the total combined salary of the employees for each department so first let me switch my database to SQL undor intro database I’ll run it okay and display my table that is employee so here we have 20 employees in our table using this table we are going to find the combined salary of the employees for each department so we will partition our table by department and print the total salary and this we are going to do using some windows functions in MySQL so I’ll write select I want the employee name the age of the employee and the department of the employee comma next I’ll write the sum of salary over I want to partition it by department so I’ll write Partition by Department which is D and I’ll give an alas as total salary so that it will create a new column with the name total salary from my table that is employees the output will be a little different this time let’s execute it and see the result there you go so here we have created another column in our result that is total salary and for each of the employees and the respective departments we have the highest salary so in finance the highest salary of one of the employees was $155,000 similarly if I come down we have the highest salary from HR if I scroll further we have the highest salary from it marketing product sales and the tech Team all right now we’ll explore a function which is called row number now the row number function gives a sequential integer to every row within its partition so let me show you how to use the ru number function I’ll write select rore number function over my column would be salary so I’ll write order by salary I’ll give the alas as ronom give a comma and I want to display the employee name and the salary of the employee from my table that is employees and I’ll order by salary so let’s see how our row number function will create sequencial integers okay you can see here we have a row number column and we have successfully given row numbers to each of the records you can see it starts from one and goes up till 20 okay now this row number function can be used to find duplicate values in a table to show that first I’ll create a table I’ll write create table let’s say I’ll give a random name that is demo and let’s say we have in this table the student ID which is of type integer and we have the student name which is of type varar the size is 20 I’ll create the small table with a few records let’s create this table first now we are going to insert a few records to our demo table so I’ll write insert into demo values I’ll give one1 the name is Shane give a comma I’ll insert the second student name one2 the name is Bradley we give a comma this time for 103 we have two records let’s say the name of the student is her give a comma I’ll copy this and we’ll paste it again so we have duplicated 103 next we have 104 for the name of the student let’s say is Nathan then again let’s say for the fifth student which is Kevin we have two records I’ll copy this and I’ll paste it here let me give a semicolon and we’ll insert these records to our table demo all right now let me just run this table for you I’ll write select star from demo if you see this we have a few information that are duplicated in our table that is for student ID 103 and student ID 105 now I’m going to use my row number function to find the duplicate records present in my table I’ll write select student uncore ID comma student uncore name I’ll give another comma and write rore number over within brackets I’ll write Partition by store ID comma store name okay then I’ll write order by store ID close the bracket I’ll give an alas as rum from my table that is demo let’s just run it you can see here okay let me just delete n from here and do it again all right if you see here there is just one student in the name Shane we have one student in the name Bradley but here if you see for her the second record it says two which means there are two records for H and if I scroll down there is one record for Nathan and there are two records for Kevin which means Kevin is also repeated okay now we are going to see another Windows function that is called rank function in my SQL so the rank function assigns a rank to a particular column now there are gaps in the sequence of ranked values when two or more rows have the same rank so first of all let me create a table and the name of the table would be a random name we’ll give it as let’s say demo one and it will have only one column let’s say variable a of type integer we’ll create this table first okay now let’s go ahead and insert a few records to our table which is demo one so I’ll write value 101 102 let’s say 103 is repeated I’m doing this purposely so that in the output you can clearly distinguish what the rank function does next we have 104 105 we have 106 and let’s say 106 is also repeated finally we have 107 okay let me insert these values to my table that is demo one okay this is done now if I write select Vore a and use my rank function I’ll write rank over then I’ll order by my variable that is Vore a as an alas name let’s a test rank from my table that is demo one let me execute this and show you how the rank function works if I run this there you go so here if you mark So for variable a101 the test rank is 1 for 102 the test rank is two but for this value which is 103 the test rank is repeated because there was a repetition for 103 so we have skipped the rank four here for 104 the rank is 5 now for 105 the rank is 6 now for 106 again since the record was repeated twice we have skipped the eighth Rank and our rank function assigned the same value which is 7 for 106 and for the last value 107 the rank is 9 all right now moving ahead we’ll see our final Windows function which is called first value so first value is another important function in my SQL so this function Returns the value of the specified expression with respect to the first row in the window frame all right so what I’m going to do is I’m going to select the employee name the age and salary and I’ll write first underscore value which is my function and pass in my employe name and then I’ll write over order by my column that is salary descending I’ll give an alas as highest uncore salary from my table that is employees so let me run this and see how the first underscore value function works all right so in our table Joseph was the employee who had the highest salary which was $115,000 so the first value function populated the same employee name throughout the table you can see it here now you can also use the first uncore value function over the partition so let’s say you want to display the employee name who has the highest salary in each department so for that you can use the partition I’ll write select _ name comma I want the department and the salary comma I’ll use my function that is first underscore value follow by the name of the employee inside my first value parameter I’ll write over here I’m going to use partition I’m going to partition it by department since I want to know the employee name who has the highest salary in each department and I’m going to order by salary descending and I’ll give my alas again as highest salary from my table that is employees so let’s run this and see the difference in the output okay so as you can see here we have the employee who had the highest salary from each department so for finance Jack had the highest salary from HR it was Marcus similarly in it it was William if I scroll down for marketing it was John for product it was Alice who had the highest salary similarly in sales we had Joseph and in Tech we had Angela so this is how you can use the first uncore value function using partition all right so that brings us to the end of this demo session on our tutorial so let me just scroll through and show you what we did from the beginning first we learned about subqueries in SQL so we initially wrote a simple subquery and then we used our classic models database which was downloaded from the internet I’d also shown you the link from where you can download this database here we used two different tables and we performed a subquery operation we learned how to create stored procedures so we learned how you can use the in operator or the in parameter as well as the out parameter in store procedure after stored procedure we learned another crucial Concept in SQL which is called triggers now triggers are also special kind of store procedures so we saw how to write a before insert trigger you can see it here next we learned how to delete a trigger we also saw how to work with views in SQL so views are basically virtual tables that you can create from existing tables we also saw how you can use views using two different tables and an inner join and we learned how to display views how to rename view names how to delete a view and finally we explored a few Windows function in this tutorial we will learn how to work with databases and tables using SQL with python to do this demo we will be using our jupyter notebook and the MySQL workbench you can see it here so we will write our SQL queries in the jupyter notebook with python like syntax if you don’t have MySQL or jupyter notebook install so please go ahead and install them first while installing the MySQL workbench you’ll be asked to give the username and password let me show you so I am on my MySQL workbench so once you connect it will ask for the username and the password so I’ve given my username as root and password you can give while installing it we will be using the same user ID or the username and the password to make our connection so let’s get started with our Hands-On demonstration part first and foremost let me go ahead and import the necessary libraries I’ll give a comment as import libraries all right so first I’ll import MySQL do connector next from MySQL doc connector I’m going to import my error method or the error module next I want to import pandas as PD so let’s run this okay there is some error here this should be capital E and not small all right you can see I have imported my important libraries now I’m going to create a function that will help us create a server connection so I’ll write my userdefined function by using the DF keyword I’ll write create underscore Server uncore Connection this is going to be my function name and it will take in three parameters first is the host name next is the username and then we have the user password all right I’ll give a colon and then in the next line I’m going to Define a variable which is going to be connection and I’ll assign it to a value called none now we’ll be using exception handling techniques to connect to our MySQL server the tri block lets you test a block of code for errors and the accept block will handle the errors so I’ll write try and give a colon and then I’m going to reassign the connection variable to a method which is MySQL do connector do connect now this MySQL connector. connect method sets up a connection so it establishes a session with the MySQL server if no arguments are passed it uses the already configured or default values so here we are going to pass in three parameters the first is the host name I’ll write host equal to host name which is hostor name name I’ll give a comma then I’ll write user equal to user uncore name next will be my password and I’ll assign the value user _ password all right now I’m going to use a print statement and write mySQL database connection successful after this I’ll give my accept blog so I’ll use the keyword accept here I’ll write error as err give a colon and then I’m going to use the print statement here I’m going to use some print formatting techniques using the F letter I’ll write error colon and I’ll use curly braces give VR and then I’ll close the double codes after this I’m going to return my connection all right let me give a comment here we are going to assign our password so we need to put our MySQL terminal password so this password you assign it while installing MySQL workbench I’ll write PW and I’ll give my password which is simply at the rate 1 2 3 4 5 and then I’m going to give my database name so I’ll give database name here I’m going to write DB equal to this is the database I want to create which is going to be MySQL python let me just scroll this down okay now I’ll say connection equal to I’ll pass in my user defined function name which is create server connection and the parameters which are going to be Local Host that is my host name my username which is root and then I’ll give PW which is my password that is exact L simply at the rate 1 2 3 4 5 let’s just run it now okay there is an error here we need to remove this double quotation all right made another mistake here this this should be root okay you can see here my SQL database connection successful all right next we are now going to create a database that is MySQL _ python so I’ll give a comment create MySQL uncore python database again to create this database I’m going to create another user defined function using the DF keyword I’ll write the function name as create database passing the parameters as connection comma query give a semicolon and in the next line I’ll write cursor equal to I’m going to make the connection so I’ll write connection dot cursor and I’ll give the parenthesis so this mysql’s cursor of MySQL connector python is used to execute statements to communicate with the mySQL database the MySQL cursor class initiates objects that can execute operations such as the MySQL statements okay next I’m going to again use my try and accept block so I’ll write try give a coolon and here I’m going to use cursor do execute within that I’m going to pass in my query next I’ll use a print statement and the message I’m going to display is database created successfully after this I’m going to write my except block I’ll write accept error as err give a colon and then I’ll use a print statement I’ll write print I’ll use the formatting again error colon and I’ll write within single codes I’ll give curly braces err and then I’ll close the double codes next let’s use the variable create underscore database underscore query and here I’m going to write my SQL query to create the database so I’ll write create database and followed by that I’ll give my database name which is going to be MySQL python okay after this I’ll call my function which is create database and I’ll pass in the parameters the first one is connection and next the query qu is create _ database _ query let me just copy it and I’m going to paste it here all right so what I’m doing here is I am creating a new function that is to create a new database with the name MySQL undor python which you can see it here now this function takes in two parameters connection and query I’m using the connection. cursor function which is often used to execute SQL statements using Python language and then I have created my try and exer blocks so this Tri block statements will try to create my new database which is MySQL python in case it fails to create the new database the exer block will work so here I’m writing my SQL query to create a new database which is create database followed by the database name and I’m assigning it to a variable which is create data datase query and then I’m calling my function create database and passing in the two parameters connection and the query all right so let’s just run it all right you can see here it has created my database successfully now you can verify this by checking the MySQL workbench or the MySQL shell you can see on the MySQL workbench here on the left panel under schemas there is a database called MySQL python let me just expand it now we haven’t created any table so it’s not showing it now the next step we are going to connect to this database so let’s go ahead and connect to our database that we have just created I’ll write the comment as connect to database now to connect to a database I’m again going to create a userdefined function using the DF keyword I’ll write create underscore DB which is for database _ connection and the parameters it will take is the host name followed by the username then we have the user password and finally we have the database name I’ll give a colon in the next line I’m going to create my variable which is connect connection and then I’ll assign it to a value none after this I’m going to use my exception handling techniques so I’ll write my tri block first I’m going to reassign my connection variable using the MySQL connector method so I’ll write MySQL do connector do connect so this this method we’ll take in the parameters so first it will take the host name I’ll write host equal to hostor name I’ll give a comma next it will take the usern name so user equal to user name another comma next it will take the user password I’ll use pass WD equal to user uncore password we give another comma and this time is going to be the database name so I’ll write database equal to dbor name now let’s use the print statement and and the message we are going to print is mySQL database connection successful all right finally we’ll write my accept block I’ll write accept error as err give a colon and then I’ll use the print statement f F within double Cotes I’ll write error colon within single Cotes curly braces I’ll write err and we’ll close the double quotes finally this function will return the connection value all right let’s run it and there you go it has run successfully so we have connected to our database now it’s time for us to execute SQL queries I’ll give another comment saying execute SQL queries all right now to execute our SQL queries I’ll use another user defined function which is execute underscore query and I’ll pass in the parameters as connection and query give a colon I’m going to write cursor equal to connection do cursor now this is used to establish a connection and run SQL statements next we’ll use the try and accept block so I’ll write try cursor dot execute this will take in one parameter which is going to be my query and then I’ll write connection do commit which is another method now let’s use the print statement so I’ll write print let’s say the message would be query was successful and then we’ll write our accept block which is accept if the tri block doesn’t work through an error using the print statement within double codes inside the inside the curly braces I’ll write err and close the double codes all right so let’s run it okay so we have successfully created our various functions that we needed to create a database establish a connection and to execute our queries all right now it’s time for us to create our first table inside the MySQL _ python database so to do that I’m going to write my create command in SQL so first we are going to assign our SQL command to a python variable using triple codes to create a multi-line string so let me show you how to do that I’ll write my variable name which is going to be create orders table it is always recommended to use relevant variable names to make it more readable and now I’m going to use triple codes so the triple quote will ensure I can create my multi-line string inside the triple quote I’m going to write my create command which is create table here I’m going to create an orders table first and inside the orders table I’m going to create my column names the First Column would be the order ID it is going to be of type integer and I’ll assign this order ID as my primary key column we’ll give a comma next the second column would be customer underscore name the customer name column would be of type varing character so I’ll write varar and I’ll give a size of 30 and this is also going to be not null moving ahead my fourth column would be the product name column so I’ll write productor name product name will be of type varing character the size is let’s say 20 and it is also not null next I’m going to create my fourth column which is the date on which the item was ordered or the product was ordered so I’ll write date ordered the data type will be date next I’ll create a quantity column to keep track of the number of quantities that were ordered this is of type integer my next column would be unit price which will basically have information about the price of each unit of product unit price can be of type float and finally I’ll have the phone number of the customer I’ll write phone number phone number can be kept as of type varing character I’ve have assigned a size of 20 now let’s give a semicolon and we’ll close the the triple codes all right so this is how the syntax would look like next to run this we are first going to call our create DB function so let me give a comment as connect to the database I’ll write connection equal to create _ dbor connection my parameters would be my host name which is Local Host my username which is root comma my password and then my database name which is MySQL python so I’ll write just DB all right finally let’s execute this query using the execute underscore query function that we had created earlier this takes in two parameter the first one is connection followed by the variable name which is create orders uncore table let us run it okay there is some error here let’s see what’s the error okay so here we have put four double code this should be triple codes now let’s run it okay there is another here let’s debug it it says name cursor not defined let me just roll it to the above cell if you see here in our execute underscore query function instead of cursor I have written cursor so R is missing let’s redun this and now let’s run this again there you go you can see here my SQL database connection successful even our query was also successful now if you want to recheck if the table that is orders was created or not you can check it on the MySQL workbench so let me show you how to do it so I am on my MySQL workbench and under MySQL python database you have something called as tables let me just right click and I’ll select refresh all there you go you can see this Arrow just click on this arrow and here you can see we have a table called orders so we have created our table called orders now you can check the columns as well you have the order ID you have the order ID the customer name product name ordered date quantity unit price and phone number now it’s time for us to insert a few records to this table which is orders now to insert records I’ll give a comment as insert data I’ll start with the variable name let’s say the variable name is data underscore orders I’ll give triple Cotes next I’ll write my insert into command so I’ll write insert into my table name that is orders for followed by values and now I’ll start entering my records for each of the rows so first I’ll give one1 which is the order ID then I’ll give the customers’s name let’s say Steve and the product he had ordered is let’s say laptop then I’ll give my date in which the item was ordered let’s say it is 2018 I’ll choose 06 as the month and the date is let’s say 12 we give another comma this time we’ll pass in the quantity which is two let’s say the price of each laptop was $800 and we’ll give a phone number this is random let’s say 62 9 3 7 3 0 Let’s see 802 all right similarly I’m going to insert five more records of different customers and their items that they have purchased to this table orders so here on my notepad I have my rest of the five records let me just copy it and we’ll paste it in the cell here this will save us some time okay let me recheck if everything is fine I’ll give a comma here all right so we have six customers in our table which have their customer IDs from 101 to 106 you have Steve jaw Stacy Nancy Maria and Danny you have the different items they have purchased laptop books trousers t-shirts headphones and smart TV is the date on which they had ordered this item the number of quantities they had ordered and then we have the unit price and some random phone numbers so let’s create the connection now I’ll write connection equal to I’ll write create undor dbor connection then I’ll going to give my same parameters let me just copy it from the top is Local Host the host name root is my username then we have password and the database name and then I’ll use the same query as above which is execute query I’ll copy this paste it here and instead of of create orders table variable I’ll put as data _ orders so this will store my insert into command you can see the variable I’ve used here is dataor orders now it’s time let’s just run it all right there was some mistake here let’s debug it again this should be triple quotes and not four now let me rerun it again there you go you can see here my SQL database connection successful and my query was also successful now we’ll create another user defined function which will help us read query and display the results so I’ll write my function name as DF read uncore query this will take in two parameters connection and query then I’ll write cursor equal to connection do cursor I’ll put my result as none and then I’ll use my try and except block I’ll write try cursor dot execute this will take in one parameter which is query and then I’ll give another variable which is result equal to cursor dot fetch all now this fetchall method will return all the results in the table I’ll write return result next we’ll use the accept block so I’ll write accept error as ER give a colon and I’ll use my print statement just scroll this down I’ll use my formatting F error give a colon followed by a space within single Cotes inside curly pess I’ll give ER and close my double Cotes let’s run it all right so now we are all set now we are going to use our select Clause having whereby then we’ll see how to use Auto by Clause some inbuilt functions we’ll update some records delete some records and do a lot of other stuff so let’s start with our first query so our first query is going to be using the select statement all right so suppose I want to display all the records that we have inserted into our ords table so the way to do is I’ll assign my query to a variable let’s say q1 I’ll give triple quotes within triple quotes I’ll write select star from orders we give a semicolon followed by the triple codes now we’ll establish the connection so let me just go to the top and I’ll copy this line which is to connect to our database I’ll paste it here now we’ll create a variable called results that will store the result of this query and we are going to assign this variable to our function that is read query and this read query will have two parameters the connection and the variable name which is q1 for the query next to display I’m going to use a for Loop I’ll write for results for result in results print I’ll say result now we are done let’s just run this query there you go you can see here we have successfully printed all the rows in our table which is orders you can see we have six records in total now we are going to explore a few more queries so let me just copy this and we are going to edit in the same query I’ll paste it here next let’s say you want to display individual columns from the table and not all the columns so let me let me create the variable Q2 now instead of star I’m going to display only the customer name and let’s see the phone numbers of the customer so I’ll write phone uncore number all right the rest all Remains the Same let me just recheck it and here instead of q1 we’ll put Q2 and let’s run this cell all right you can see here now we have displayed only two columns the First Column is the customer name and then we have the respective phone numbers okay now let me just paste that query again now we are going to see how you can use an inbuilt function that is in our table we have the order date and from the order date we are only going to display the different ear that are present in the order date so to do that I’m going to use the year function I’ll edit this query instead of q1 I’ll make it Q3 and here I’m going to write select here which is my function name from my column which is date ordered from orders and here I’ll change this to Q3 q1 Q2 Q3 are basically query 1 query 2 and query 3 let’s run it there you go so we have successfully extracted the different years present in the order date column now if you want to display the distinct or the unique dates present in the column you can use the dextin keyword in the select statement so the way to do it is I’ll write select distinct give a space the rest of the query Remains the Same and here Q3 I’ll write Q4 I’ll make this as Q4 let’s run it you can see 2018 and 2019 are the unique year values that are present in the order date column okay now moving ahead let’s write our fifth query and this time we are going to explore how you can use the wear Clause so I’ll change this to Q5 before I write my query so let’s say you want to display all the orders that were ordered before 31st of December 2018 so to filter this we are going to use the wear Clause so I’ll write write select star from orders next I’ll write where my date underscore ordered is less than within course I’ll give my date value which is 2018 December 31st so all the items or the products that were ordered before 31st of December 20 18 will be displayed so let’s run it all right you can see here there are three orders in our table which have been ordered before 31st of December now moving ahead we want to display all the orders that were made after 31st of December so here what you can do is I’ll just copy the above query again I’ll copy this line so instead of less than 31st of December 2018 I’ll make it as greater than so every order that was placed after 31st of December will be displayed if you run it so you can see here there are three orders in our table which were ordered after 31st of December 2018 now moving ahead let’s write a seventh query now let’s see how the autoby Clause Works in SQL so you can filter your results based on a particular column or sort it based on a particular column so this is going to be my query 7 I’ll write it from scratch again let’s say you want to display all the columns from the table so I’ll write select star from orders then I’m going to use order by unit price I’ll give a semicolon let’s run this query and see the output now if you see the result here and you mark the unit price column the result has been ordered in ascending order of unit price you see here it starts with the lowest price and then goes on with the highest price towards the end if you want to order it in descending order you can use the keyword Dees C so this will ensure your top or the most expensive products appear at the top and the least expensive products appear at the bottom all right next now let’s see how you can create a data frame from the given table so as you know using jupyter notebook and pandas you can create data frames and work on it very easily so with this table also we can create our own data frame so for that let me create an empty list first I’ll write from DB equal to I’ll assign this as an empty list so we are going to return a list of lists and then create a pandas data frame next I’ll write my for Loop I’ll write for result in results I’ll assign result to list of results so I’m converting the result into a list and then I’m going to append it to the empty variable or the empty list which is from DB do append I’ll append the result to my empty list next we need to pass in the column now that will be part of our data frame so I’ll write columns equal to this column I’ll pass it within a list so I’ll give my first column as order ID then we have the customer name next I have my product name then I have the date on which it was ordered give a comma then we’ll have the quantity column let me write it in the next line next we have the unit price column and finally we have the phone number column so I’ll write within double quotes phone number and this we are going to assign it to a data frame so I’ll be using PD do data frame which is my function to convert a list into a data frame my variable I’m going to pass this from _ DB and I’ll write my next argument is columns equal to my variable name that is columns finally let’s display the data frame which is DF all right so here I’m creating a empty list first and then I am creating a for Loop and I’m appending the results to my empty list here you can see I have created my column list and using pd. data frame I’m converting the list into a data frame if I run this this is append and not append all right you can see we have our data frame ready this is the index column it starts from zero onwards and then we have the different column names okay now let’s see how to use the update command now suppose you want to change the unit price of one of the orders you can use the update command so the way to do it I’ll first create my variable let’s say update and I’ll give three codes or triple codes then I’ll use my update command which is update followed by the table name that is orders next I’ll write set let’s say unitor price if you see this let’s say I want to set the unit price of trousers from $50 to let’s say $45 I want to update this particular record so I’m going to write set unit price column equal to $45 where the order ID equal to 103 so this query will update the third row in our table which is order ID 103 so it will update from $50 to $45 I’ll close the triple quotes and now I’ll use the connection queries again let me just paste it here all right I’ll delete these three lines of code and instead of that I’ll put execute underscore query and this will take into parameters as always which is going to be connection followed by the variable name that is update let’s run it you see here it says mySQL database connection successful query was successful now you can recheck that to do it let me just go to the top and we’ll just copy our first query which is q1 I’ll copy this and I’ll paste it here let me just rename this now this will be Q8 and I’ll change this as well I’ll write select star from orders where my order ID equal to 103 let’s see the unit price of 103 now you can see here instead of 50 now we have updated it to $45 all right now the last command we are going to say is how you can delete a record from the table I’ll write delete command as my comment now to delete a query I’ll first give my variable name which is delete uncore order and I’ll pass in within triple quotes next I’ll write my delete query which is delete from my table name that is orders then I’ll give my we Clause where let’s say I want to delete my order ID 105 let me just go to the top and explain you again so if you see this we want to delete the order ID 105 which was for customer name Maria and she had ordered headphones we want to completely remove this particular record so I have my delete query ready now let me just create my connection and display the results so I’ll go to the top and I’ll copy this connection command which also has the execute query command and I’ll paste it here and I’m going to make a change here instead of update we’ll write delete underscore order everything looks good let’s just run it you can see our query was successful and now if you want to print it let me just show you I’ll just copy this we’ll paste it here I’ll make this as q9 I want to verify if my order ID 105 was deleted or not instead of this statement I’ll write select star from orders and here I’ll change this to q9 if I run this you can see it here you can Mark order ID 105 was deleted and it no more appears in this table all right so this brings us to the end of the demo session on SQL with python let me just scroll you through what we did so first we imported the important libraries MySQL connector then we imported the error function then we imported pandas using PD we learned how to create a server connection to mySQL database we created a new database that is MySQL Python and now we connected to that database we created a function to execute our queries we saw how you can write a create table command then we inserted a few records to our orders table we created a read uncore query command to read the queries and display the results then we started exploring our different SQL commands one by one we saw how to use select query then we selected a few individual columns from our table followed by using a inbuilt function which was ear then we saw how to use the distinct keyword after that we used our wear Clause to filter our table based on specific conditions we saw how to order your results based on a particular column then we saw how you could convert the table into a data frame using pd. dataframe function finally we learned how to use the update command and the delete command postl is a very popular and widely used database in the industries in this tutorial we will learn post SQL or post chis SQL in detail with an extensive demo session so in today’s video we will learn what post chis SQL is and look at the history of postris SQL we will learn the features of postris SQL and jump into performing postris SQL commands on the SQL cell and PG admin so let’s begin by understanding what is post SQL postc SQL is an open-source object relational database management system it stores data in rows with columns has different data attributes according to the DB engines ranking postris SQL is currently ranked fourth in popularity amongst hundreds of databases worldwide it allows you to store process and retrieve data safely it was developed by a worldwide team of volunteers now let’s look at the history of postr sequel so in 1977 onwards the Ingress project was developed at the University of California Berkeley in 1986 the post Chris project was led by Professor Michael Stonebreaker in 1987 the first demo version was released and in 1994 a SQL interpreter was added to postris the first postris SQL release was known as version 6.0 or 6.0 on January 29 1997 and since then postr SQL has continued to be developed by the post SQL Global Development Group a diverse group of companies and many thousands of individual contributors now let’s look at some of the important features of postest SQL so postest SQL is the world’s most advanced open source database and is free to download it is compatible as it supports multiple operating systems such as Windows Linux and Macos it is highly secure robust and reliable postp SQL supports multiple programming interfaces such as C C++ Java and python postp SQL is compatible with various data types it can work with Primitives like integers numeric string and Boolean it supports structured data types such as dat and time array and range it can also work with documents such as Json and XML and finally postris SQL supports multiversion concurrency control or mvcc now with this Theory knowledge let’s look at the post SQL commands that we will be covering in the demo so we will start with the basic commands such as select update and delete we will learn how to filter data using where clause and having clause in SQL we will also look at how to group data using the group by clause and order the result using the order by Clause you will learn how to deal with null values get an idea about the like operator logical operator such as and and or we will also explore some of the popular inbuilt mathematical and string functions finally we’ll see some of the advanced concepts in postris SQL that is to write case statements subqueries and user defined functions so let’s head over to the demo now okay so let’s now start with our demo so first we’ll connect to post SQL using psql cell so here under type here to search I’ll search for psql you can see this is the SQL cell I’ll click on open let me maximize this okay so for Server I’ll just click enter database I’ll click enter port number is already taken which is 5432 I hit enter username is already given and now it is going to ask for password so here I’ll give my password so that I can connect to my post SQL database so it has given us a warning but we have successfully connected to post SQL all right so now to check if everything is fine you can just run a simple command to check the version of post SQL that we have loaded so the command is Select version with two brackets and a semicolon I’ll hit enter okay you can see the version post SQL 13.2 okay now let me show you the command that will help you display all the databases that are already there so if I hit slash L and hit enter it will give me the list of databases that are already there so we have post SQL there’s something called template 0o template 1 and we have a test database as well okay now for our demo I’ll create a new database so first I’ll write create space database and I’ll give my database name as SQL uncore demo I’ll give a semicolon and hit enter you see we have a message here that says create database so we have successfully created our SQL demo database now if you want to connect to that database you can use back/ c space SQL uncore demo there you go it says you are now connected to database SQL demo so here we can now create tables we can perform insert operation select operation update delete alter and much more now I’ll show you how to connect to post SQL using PG admin so when you install the post SQL database you will get the SQL cell and along with that you also have the PG admin so I’ll just search for PG you can see here it has prompted PG admin I’ll click on open this will open on a web browser you can see it has opened on Chrome and this is how the interface of PG admin looks like it is a very basic interface so on the top you can see the files we have object this tools and we have the help section as well and here you have dashboard properties SQL statistics dependencies dependence and here on the left panel you have servers let me just expand this so it will connect to one of the databases all right so if I go back you see when I had run back/ L to display the databases it had shown me post SQL and test now you can see here we have the post SQL database and the test database all right now we also created one more database which was SQL demo so let me show you how to work on this PG admin and the query tool all right so I’ll right click on SQL demo and I’ll select query tool I’ll just show you how to run a few commands on the query tool so let’s say you want to see the version of post SQL that you are using so you can use the same command that we did on psql Cell which is Select version closed with brackets and a semicolon I’ll select this and here you can see we have the execute button so if I hit execute or press F5 it will run that query you can see we have the output at the bottom and it says post SQL 13.2 compiled by visual C++ it has the 64-bit system okay now let me tell you how to perform a few basic operations using postr SQL commands so here let’s say I’ll write select 5 into 3 I’ll give a semicolon select this and hit F5 so this will run the query and it returns me the result that is the product of 5 and three which is 15 similarly let’s edit this let’s say I’ll write 5 + 3 + let’s say 6 I’ll select this and hit F5 to run it it gives me the sum of 5 + 3 + 6 which is 14 now the same task you can do it on this cell as well let me show you how to do it here so let’s say I’ll write select let’s say I want to multiply 7 into let’s say 10 you know the result it should be 70 if I hit enter it gives me 70 now this question mark column question World we’ll deal with this later all right let me go back to my PG admin again let me do one more operation let’s say this time I’ll write select 5 multiplied by and within brackets I’ll write 3 + 4 I’ll give a semicolon so what SQL will do is first it will evaluate the expression that is there inside the bracket that is 3 + 4 which is 7 and then it will multiply 7 with 5 now let me select this and I’ll hit execute so you can see 7 * 5 is 35 all right now we’ll go back to our shell and here I’ll show you how to create a table so we are going to create a table called movies on the cell that is psql cell so here we will learn how you can create a table and then you can enter a few data into that table all right let me just scroll down a bit okay so my create command goes something like this so I’ll write create table followed by the table name that is movies next my movies table will have a few columns let’s say I want the movie ID after the column name we need to give the data type so movie ID I’ll keep it as integer so integer is one of the data types that is provided by postr SQL next my second column the table would be the name of the movie so I’ll write moviecore name so all the variables or the column names should be as per SQL standards so there shouldn’t be any space between the column names so I have used underscore to make it more readable so my movie name will be of type varar or variable character or varing character and I’ll give the size as 40 so that it can hold 40 characters maximum next my third column will have the genre of the movie so I’ll write moviecore joner again joner is of type barar I’ll give the size as let’s say 30 and my final and the last column will have the IMDB ratings so I’ll write IMDb underscore ratings now the ratings will be of type real since it can have floating or decimal point values if I close the bracket I’ll give a semicolon and I’ll hit enter there you go so we have successfully created a table called movies now let me go back to my PG admin all right so here I have my database that is SQL demo I’ll just right click on this and click on refresh now let me go to schemas I’ll just scroll down a bit here under schemas we have something called as tables let me expand this okay so you can see we have a table called movies in the SQL demo database now and here you can check the columns that we have just added so our movies table has movie ID movie name j and readings all right now there is another way to create a table the previous time we created using the SQL cell now I’ll tell you how to create a table using the PG admin so here under tables I’ll right click and I have the option to create a table so I’ll select table okay so it’s asking me to give the name of the table so this time we are going to create a table called students so I’ll write my table name as students all right these will be default as it is now I’ll go to the columns tab so here you can create the number of columns that you want so you can see on the right I have a plus sign I’ll just select this so that I can add a new row so my first column would be let’s say the student role number I’ll write student underscore RO number again the column name should be as per SQL standards the data type I’m going to select is integer all right now if you want you can give these constraints such as not null so that student R number column will not have any null values and I’ll also check primary key which means all the values will be unique for role numbers all right now if you want to add another column you can just click on that plus sign and let’s say this time I want to give the student name as my second column so I’ll write student underscore name student name will be of type let’s say character wearing if you want to give the length you can specify the length as well let’s say 40 I’ll click on the plus sign again to add my final column the final column would be gender so gender I’ll keep this time as type character okay now you can click on save so that will successfully create your students table there you go so here on the left panel you can see earlier we had only one table that was movies and now we have two tables so one would be added that was students so if I expand this under columns you can see we have the three columns here student rule number student name and gender you can also check the constraints it will tell you if you have any constants so you can see it says students rule number there’s one primary key all right all right now let me run a select statement to show the columns that we have in the movies table so I’ll write select star from movies give a semicolon and let me execute this okay so here on the at the bottom you can see we have the movie ID the movie name movie Jor and IMDb readings now the next command we are going to learn is how to delete a table so there is one way by using the SQL command that is drop table followed by the table name let’s say you want to delete students you can write drop table students and that will delete the table from the database this is one of the methods so you just select and run it now the other way is to you just right click on the table name and here you have delete slash drop if I select this you get a prompt are you sure you want to drop table students I’ll select yes so you can see we have successfully deleted our students table all right now let’s perform a few operations and learn a few more commands in post SQL so to do that I’m going to insert a few records to my movies table so for that I’ll use my insert command so I have my insert query written on a notepad I’ll just copy this and I’ll paste it on my query editor okay so let me just scroll down all right so here you can see I have used my insert command so I have written insert into the name of the table that is movies and we have the movie ID the movie name movie Jer and IMDb readings and these are the records or the rows so we have the first record as movie ID 101 the name of the movie is a very popular movie which is vertigo then we have the movie genre that is Mystery it is also a romance movie and then we have the IMDb readings the current IMDb readings that is 8.3 similarly we have sank Redemption we have 12 Angry Men there’s the Matrix seven inter staler and The Lion King so there are total eight records that we are going to insert into our movies table so let me just select this and hit execute okay you can see it has returned successfully eight records now if I run select star from movies you can see the records that are present in the table so I’ll write select star from movies I’ll select this and I’ll execute it there you go at the bottom you
can see eight rows affected if I scroll this down you have the eight records of information in the movies table all right now if you want to describe the table you can go to the SQL cell and here if you write back SL D and the name of the table that is movies this will describe the table so here you have the column names this has the data type and here you can specify if there are any null values or any con constraints like default constraint or primary key or foreign key and others let me go back to my PG admin okay now first and foremost let me tell you how to update records in a table so suppose you have an existing table and by mistake you have uh entered some wrong values and you want to update those records later you can use the update query for that so I’m going to update my movies table and I’ll set the genre of movie ID 103 which is 12 Angry Men from drama to drama and crime so in our current Table we only have jonre as drama for 12 angry man I’m going to update this column which is the movie genre to drama and crime okay so let me show you how to do it I’ll write update followed by the name of the table that is movies go to the next line I’ll write set then I’ll give the column name which is moviecore Jer equal to I’m going to set it as drama comma crime earlier it was only drama and I’ll give my condition using the where Clause we’ll learn where clause in a bit so I’ll write where moviecore ID is equal to 103 so here our movie ID is the unique identifier so it will first look for movie ID 103 it will locate that movie and it change the genre to drama and crime so now you can see the difference earlier we had 12 Angry Men as drama as the movie genre now if I run this update statement okay you can see we have successfully updated one record now let me run the select statement again okay so here you can see if I scroll down there you go so movie ID 103 movie name 12 Angry Men we have successfully updated the genre as drama comma crime okay now let me tell you how you can delete records from a table so for that you can use the delete command so you’ll write delete from the table name that is movies where let’s say I want to delete the movie ID 108 which is The Lion King so I’ll write where moviecore ID is equal to 108 this is one of the ways to delete this particular movie or you can give let’s say where movie name is is equal to The Lion King let me select this and I’ll hit execute now if I run my select query again you see this time it has returned seven rows and you cannot find movie with movie ID 108 that was The Lion King so we have deleted it all right next we are going to learn about wear clause in post SQL so to learn we Clause I’ll be using the same movie table again let’s say we want to filter only those records for which the IMDB ratings of the movies is greater than 8.7 so this is my updated table now I want to display only those records or those movies whose IMDB ratings is greater than 8.7 so we’ll display 12 angry man which is 9 then we are going to display the Dark Knight which is again 9 and we are also going to display the sank Redemption which has 9.3 the rest of the movies have and am Tob rating less than 8.7 so we are not going to display those all right so let me show you how to write a we Clause so I’ll write select star from movies where I’ll give my column name that is IMDB ratings is greater than I’ll use the greater than symbol then I’ll pass my value that is 8.7 I’ll give a semicolon and let’s run it I’ll hit F5 there you go so we have returned the sank Redemption The Dark Knight and 12 Angry Men because only these movies had IMDB ratings greater than 8.7 okay now let’s see say you want to return only those movies which have IMDB ratings between 8.5 and 9 so for that I’m going to use another operator called between along with the wear Clause so let me show you how to use between with wear Clause I’ll write select star from movies where my IMDB uncore ratings is between I’ll write 8.5 I’ll give an and operator and 9.0 so all the movies that are between 8.5 and 9.0 ratings will be displayed so let’s select this and I’ll run it there you go so we have returned the darkno The Matrix the seven interal and we have the 12 Angry Men so a few of the course that we missed out where I think vertigo which has 8.3 and there’s one more all right now moving ahead let’s say you want to display the movies whose movie genre is action you can see in a table we have a few movies whose genre is action movie so you can do that as well I’ll write select star from movies where the movie J I’m writing this time in one line you can break it into two lines as well I’ll write moviecore Jer which is my column name equal to I’ll give within single codes action now why single code because action is a string hence we need to put it in single codes if I run this there you go so we had one movie in our table whose movie genre action that is The Dark Knight okay now you can also select particular columns from the table by specifying the column names now here in all the examples that we saw just now we are using star now star represents it will select all the columns in the table if you want to select specific columns in the table you can use the column names so you can specify the column names in the select statement let me show you let’s say you want to display the movie name and the movie genre from the table so you can write select moviecore name comma I’ll give the next column as moviecore Jer from my table name that is movies where let’s say the IMDB uncore ratings is less than 9.0 so this time in our result it will only show two columns that is movie name and movie JRE let me run it there you go so these are the movie names and the movie Jers you can see that have an IMDB ratings less than 9.0 all right like how you sh the between operator there is one more operator that you can use with the we Clause that is the in operator so the in operator works like a r clause or an R operator so let’s say I want to select all the columns from my movies table where the IMDB ratings is in 8 .7 or 9.0 if I run this it will display only those records whose IMDB ratings is 8.7 or 9.0 all right so up to now we have looked at how you can work on basic operations in SQL like your mathematical operations you saw how a select statement works we created a few tables then we inserted a few records to our tables we saw how you can delete a table from your database and we have performed a few operations like update delete and we saw how a wear Clause works now it’s time to load a employee CSV file or a CSV data set to post SQL so I’ll tell you how you can do that but first of all before loading or inserting the records we need to create an employee table so let me first go ahead and create a new table called employees in our SQL _ demo database so I’ll write create table my name of the table would be employees next I’m going to give my column names so my first column would be employee ID so the employee ID will be of type integer it is not going to contain any null values so I’ll write not null and I’ll give my constraint as primary key so the employee ID as you know is unique for all the employees in a company so once I write primary key it will ensure that there are no repetition in the employee IDs okay next I’ll have my employee name so my employee name is going to be of type varar and I’ll give my size as 40 okay next we’ll have the email address of the employee again email address would be of type varar and the size is 40 again I’ll give another comma this time we’ll have the gender of the employee gender is again worker of size let’s say 10 okay now let’s include a few more columns we’ll have the Department column so I’ll write department worker let’s say the size is 40 then let’s say we’ll have another column that is called address so the address column will have the country names of the employees address is also our car and finally we have the the salary of the employee salary I’m going to keep it as type real so real will ensure it will have decimal or floating Point values okay so now let me select this create table statement and execute it all right so we have successfully created our table if you want you can check by using select star from employees let me select this and I’ll hit execute all right you can see we have our employee ID as primary key there’s employee name email gender this department address and salary but we don’t have any records for each of these columns now it’s time for us to insert a few records to our employees table now to do that I’m going to use a CSV file so let me show you how the CSV file looks like okay so now I am on my Microsoft Excel sheet and on the top you can see this is my employe data. CSV file here we have the employee ID the employee name email gender this department address and salary now this data was generated using a simulator so this is not validated and you can see it has a few missing values so under email column you have a few employees who don’t have an email ID then you can see on Department also there are some missing values here as well all right so we’ll be importing this this table or the records present in this CSV file onto postr SQL all right so here in the left panel under tables let me right click and first refresh this there you go so initially we had only movies table and now we also have the employees table now what we need to do is I’ll right click again and here you see we have the option to import or export let me click on this and I don’t want to export I need to import so I’ll switch on import all right now it is asking me to give the file location so let me show you how to get the file location so this is my file location actually so my Excel file which was this is present in my e Drive under the data analytics folder I have another folder called postc SQL and within the post SQL folder I have my CSV file that is employe data. CSV so I’ll just select this you can either do it like this or you can browse and do okay now my format is CSP next I’m going to select my headers as yes and then let me go to columns and check if everything is fine all right so I have all my columns here let’s click on okay you can see I have a message here which says import undor export all right so here you can see successfully completed we can verify this by using select star from employees again if I run this all right let me close this there you go it says 150 rows affected which means we have inserted 150 rows of information to our employees table you can see we have the employee ID this are all unique we have the employee name the email we have the address and the salary let me scroll down so that okay you can see we have 150 rows of information that means we have 150 employes in our table okay now we are going to use this employees table and explore some Advanced SQL commands now there is an operator called distinct so see if I write select address from employees this is going to give me 150 address of all the employees there’s some problem here I did a spelling mistake there should be another D if I run this again I’ll query will return 150 rows you can see we have the different country names under address that is Russia we have France there United States we have Germany okay and I think we have Israel as well yeah now suppose you want to display only the unique address or the country names you can use the distinct keyword before the column name so if I write select distinct address from employee it will only display the unique country names present in the address column if I run this see it has return returned us six rows of information so we have Israel Russia Australia United States France and Germany all right now as I said there are a few null values which don’t have any information so you can use the isal operator in SQL to display all the null values that are there suppose I want to display all the employee names where the email ID has a null value so I’ll write select star from employees where email is null this is another way to use your wear Clause if I select and run this there you go so you see here for all these employee names there was no email ID present in the table so it has written us 16 rows of information so around 10% of employees do not have an email ID and if you see a few of them do not have an email ID and also they don’t have a department so if you want to know for those employees which do not have a department you can just replace where department is null instead of where email is null now if I select this okay it has returned us nine rows of information which means around 5% of employees do not have a Department moving ahead now let me show you how the order by Clause Works in SQL now the order buy is used to order your result in a particular format let’s say in ascending or descending order so the way to use is let’s say I want to select all the employ from my table so I’ll write select star from employees order by I want to order the employees based on their salary so I’ll write order by salary let me select and run it okay there is some problem I made a spelling mistake this should be employees let me run it again okay now if you mark the output a result has been ordered in ascending order so all the employees which have salary greater than $445,000 appear at the top and the employees with the highest salaries appear at the bottom so this has been ordered in ascending order which means your SQL or post SQL orders it in ascending order by default now let’s say you want to display the salaries in descending order so that all the top ranking employees in terms of salary appear at the top so you can use the dec keyword which means descending if I run this you can see the difference now so all the employees with the highest salary appear at the top while those with the lowest salaries appear at the bottom so this is how you can use an order by Clause okay so now I want to make a change in my existing table so here if you see under the address column we only have the country names so it would be better if we change the name of the address column to Country so I want to rename a column you can do this using the alter command in postc SQL so let me show you how to rename this column that is address so I’ll write alter table followed by the table name which is employees then I’m going to use rename column address I’ll write two I want to change it to Country if I give a semicolon and hit execute it will change my column name to Country now you can verify this if I run the select statement again there you go earlier it was address column and now we have successfully changed it to Country column okay let me come down now it’s time for us to explore a few more commands so this time I’m going to tell you how an and and an or operator Works in SQL so you can use the and and or operator along with the wear Clause so let’s say I want to s SE the employees who are from France and their salary is less than $80,000 so let me show you how to do it I’ll write select star from employees where I’m going to give two conditions so I’ll use the and clause or the and operator here I’ll write where country is equal to France now Mark here I’m not using address because because we just updated our table and changed the column name from address to Country so I’ll write country equal to France and my next condition would be my salary needs to be less than $80,000 I’ll go a semicolon let me run this all right so it has returned 19 rows of information you can see all my country names of France and the salary is less than $80,000 so this is how you can use or give multiple conditions in a we Clause using the and operator now let’s say you want to use the or operator and let’s say you want to know the employees who are from country Germany or the department should be sales so I’ll write select star from employees where country is equal to Germany and instead of and I’m going to use or their Department should be sales okay now let’s see the output I’ll hit F5 this time to run it all right so we have 23 rows of information now let me scroll to the right you can see either the country is Germany or the department is sales you see one of them in the table so here for the first record the country was Germany the second record the department was sales again sales again for the fourth record the country is Germany so this is how the or condition works so if one of the conditions are true it will return the result it need not be that both the conditions should satisfy now in post SQL there is another feature that is called limit so post SQL limit is an optional clause on the select statement now this is used as a constraint which will restrict the number of rows written by the query suppose you want to display the top five rows in a table you can use the limit operator suppose you want to skip the first five rows of information and then you want to display the next five you can do that using limit and offset so let’s explore how limit and offset works I’ll write select star from employees let’s say I’ll use my order by Clause I’ll write order by salary let’s say in descending and limit it to five this is going to display the top five employees which have the highest salary if I run this there you go you see it has given us five rows of information and these are the top five employes that have the highest salary okay so this is one method of or one way of using the limit Clause now in case you want to skip a number of rows before returning the result you can use offset Clause placed before the limit Clause so I’ll write select star from employees let’s say order by salary descending this time I’m going to use limit 5 and offset three so what this query will do is it will skip the first three rows and then it will print the next five rows if I run this there you go so this is how the result looks like okay now there is another clause which is called Fetch let me show you how that works I’ll copy my previous SQL query I’ll paste it here and here after descending I’m going to write fetch first three row only so my fetch is going to give me the first three rows from the top there you go it has given us the first three rows and you can see the top three employees that have the highest salary since we ordered it in descending order of salary all right you can also use the offset along with the fetch Clause I’ll copy this again and let me paste it here now after descending I’m going to write offset let’s say three rows and fetch first five rows only so what this SQL query is going to do is it will skip the first three rows of information and then it is going to display the next five rows it is going to work exactly the same as we saw for this query let me run it there you go so these are the first five rows of information after excluding the top three rows all right we have another operator that is called as like in post SQL so like is used to do pattern matching so suppose you have a table that has the employee names you forgot the full name of an employee but you remember the few initials so you can use the like operator to get an idea as to which employee name it is now let’s explore some examples to learn how the like operator Works in postris SQL so suppose you want to know the employees whose name starts with a so for that you can use the like operator let me show you how to do it so I want to display the employee name and let’s say I want to know their email IDs from the table name that is employee where since I want to know the employees whose name starts with a so I’ll write employee name like now to use the pattern is within single course I’ll write a and Then followed by percentage now this means the employee name should have an e in the beginning and percentage suggest it can have any other letter following a but in the beginning or the starting should be a if I run this so there is an error here the name of the table is employees and not employee let’s run this again there you go you can see there are 16 employees in our table whose name starts with a you can see this column employee name all of them have a letter A in the beginning okay now let me just copy this command or the query I’ll paste it here let’s say this time you want to know the employees whose name starts with s so instead of a I’ll write s so this means the starting letter should be S and followed by it can have any other letter if I run this so there are 10 employees in the table whose name starts with s okay let’s copy the query again and this time I want to know the employees whose name ends with d now the way to do it is instead of a percentage I’ll write this time percentage D which means at the beginning it can have any letter but the last letter in the string or in the name should be ending with D now let me copy and run this so there are 13 employees in the table whose name ends with a d you can see it here all right now let’s say you want to find the employees whose name contains ish or have ish in their names so the way to do is something like this so I’ll copy this now here instead of a percentage I’ll replace this with percentage ish percentage now this means that in the beginning it can have any letter and towards the end also it can have any letter but this ish should appear within the name let me run and show it to you okay so there is one employee who name contains ish you can see here there’s an ish in the last name of the employee all right now suppose you want to find the employee name which has U as the second letter it can have any letter in the beginning but the second letter of the employee name should have U now the way to do is I’ll copy this and instead of a% I’ll write underscore U followed by percent now this underscore you can think of a blank that can take any one letter so the beginning can start with a B C D or any of the 26 alphabets we have then then it should contain u as the second letter followed by any other letter or letters let me run this okay so there are 10 employees in the table whose name has a u as the second letter you can see these okay now moving ahead let me show you how you can use basic SQL functions or inbuild functions so we’ll explore a few mathematical functions now so let’s say you want to find the total sum of salary for all the employees so for that you can use the sum function that is available in SQL so I’ll write sum and inside the sum function I’ll give my column name that is salary from my table name that is employ let’s see the result this will return one unique value there you go now this is the total salary since the value is very large it has given in terms of e now one thing to note here is if you see the output the column says sum real so this output column is not really readable so SQL has a method which can fix is that is called an alas so since we are doing an operation of summing the salary column we can give an alas to this operation by using the as keyword so if I write sum of salary as let’s say total salary then this becomes my output column you can see the difference if I run this okay you can see now in the output we have the total salary now this is much more readable than the previous one so this is a feature in Excel where you can use or give alas names to your columns or your results now similarly let’s say you want to find the average of salary for all the employees now SQL has a function called AVG which calculates the mean or the average salary if I write AVG and I I can edit my alas name as well let’s see I’ll write mean salary let’s run it you can see the average salary for all the employees it’s around $81,000 okay now there are two more important functions that SQL provides us which is Max and minimum so if I write select maximum or Max which is the function name of salary as let’s say instead of total I’ll write maximum so this will return me the maximum salary of the employee let’s run it and see what is the maximum salary that is present in the salary column all right so we have 1ak 9,616 as highest salary of one of the employees similarly you can use the minan function as well I’ll just write minimum and this will return me the minimum salary of one of the employees in the table I’ll replace the alas name as minimum okay now run it this will give me the minimum salary that is present in our table so it is $4,680 okay now let’s say you you want to find the count of Department in the employees table you can use the count function so if I write select count let’s say I want to know the distinct Department names I can write inside the count function distinct Department as total departments from employees let’s run this this will return me the total number of departments that are there so it gives me there are 12 departments okay now let me show you one more thing here if I write select Department from employees let let’s run this okay so it has returned me 150 rows of information but what I’m going to do is I’ll place my distinct keyword here just before the column name so that I can verify how many departments are there in total there you go so there are 13 departments and one of them is null so moving ahead we’ll replace this null with a department Name by updating a table okay so now let’s update our department column so what we are going to do is wherever the department has a null value we are going to assign a new Department called analytics so earlier we have also learned how to use the update command so I’m going to show it again so we’ll write update followed by the table name that is employees I’m going to set my column that is Department equal to within single codes my name of the department would be analytics where department is I’ll say null so wherever the department has a null value we replace those information with Department that is analytics let’s run this you can see quy returned successfully now let’s say I’ll run this command again and this time you can see the difference there you go so we have 13 rows of information and there is no null department now we have added a new department that is analytics okay now we are going to explore two more crucial commands or Clauses in SQL that is Group by and having so let’s learn how Group by Clause Works in post SQL so the group by statement groups rows that have the same values into summary rows for example you can find the average salary of employees in each country or city or department so the group by Clause is used in collaboration with the select statement to arrange identical data into groups so suppose you want to find the average salary of the employees based on countries you can use the group by Clause so let me show you how to do it I’ll write select I want the countries and the average salary for each country so I’ll use the average function that is AVG and inside the function I’ll pass my column that is salary I’ll give an alas name as let’s say average uncore salary from my table name that is employees next I’m going to use my group by Clause so I’ll write Group by since I want to find the average salary for each country so I’ll write Group by country name let’s give a semicolon and let me run it I’ll use F5 there you go so here on the left you can see the country names we have Israel Russia Australia United States France and Germany and on the right the second column you can see the average salary for each of these countries now you can also order the result in whichever way you want suppose you want to arrange the results based on the average salary so you can use the order by Clause after the group by Clause so I’ll write order by here you can use the alas name that is average salary this is actually average uncore salary and let’s say I want to arrange it in descending order so I’ll write DSC now let’s run this you can mark the difference in the average salary column there you go so as per our result in United States the average salary is the highest and if I scroll down the average salary is the lowest in Germany now let’s see one more example using group buy suppose this time you want to find the maximum salary of male and female employees you can do that too so let me show you how to do it so I’ll write select this time we want to find the maximum salary based on gender so I’ll select my gender column comma and this time I’ll use my Max function since I want to find the maximum salary for male and female employees I’ll give an alas name as Max maximum underscore salary from my table that is employees Group by I’ll write gender okay so let’s run this there you go you can see so one of the female employees had a highest salary of $1 lak1 19,618 while of that of a me was $ 17,6 54 all right now suppose you want to find the count of employees based on each country you can use the count function along with the group by Clause so I’ll write the select statement select since I want to count the employees based on each country so I’ll first select my country column and then I’m going to use the count function I’ll write count e _ ID from my table name that is employees I’m going to group it by country so this query will give me the total number of employees from each country you can see here Israel there are four employees in Australia there are four employees in Russia we have 80 employees in France there were 31 in United States we have 2 7 so on and so forth now let me scroll down okay now it’s time to explore one more Clause a very important Clause that is used in post SQL that is having so the having Clause works like the wear Clause the difference is that wear Clause cannot be used with aggregate functions the having Clause is used with the group by Clause to return those rows that meet a condition so suppose you want to find the countries in which the average salary is greater than $80,000 so you can use the group by clause and the having Clause to get the result so I’ll write my select statement as select country comma I want the average salary so I’ll write AVG of salary I can give an alas name as average salary from employees now I’m going to group it by each country so Group by country colum since I want to find the countries in which the average salary is greater than 80,000 so I’ll use having Clause after the group by Clause I’ll write having average of salary is greater than 880,000 now this condition cannot be specified in the wear Clause so we need a having Clause you cannot use aggregate functions along with wear Clause let me just run it now there you go so we have Russia and United States where the average salary is greater than $80,000 all right now let’s say you want to find the count of employees in each country where there are less than 30 employees so for this I’m going to use the account function first let me select the country column then I’m going to use the count function and in the count function I’m going to pass my employee ID so that we can count the number of employees from my table that is employees now if you want you can use an alias name for this as well but I’m just skipping it for the time being I’ll write Group by country next I’ll write having count of employee ID less than 30 so this will return me the countries in which there are less than 30 employees let’s run it you can see here Israel Australia United States and Germany are the countries in which there are less than 30 employees okay now if you want you can use the order by Clause as well so suppose I’ll write here order by count of employee ID so what this will do is it will arrange my result in ascending order of employe ID count there you can see we have successfully arranged our result in s order of employee IDs okay next we are going to explore one more feature of post SQL that is of using a case statement now in post SQL the case expression is same as IFL statement in any other programming language it allows you to add if else logic to the query to form a powerful query now let me just scroll down and I’ll show you how to use a case statement this is very similar to your eel statement that you use on Excel in C++ in Python and or any other programming language so what I’m going to do is I’m going to write a SQL query that will create a new column and the name of the column would be let’s say salary range so I’m going to divide my salary suppose if the salary is greater than $45,000 and if it’s less than $555,000 in the new column that is salary range we are going to assign a value low salary now if the salary is greater than $55,000 and if it is less than $80,000 we are going to assign a value that is medium salary if the salary is greater than $80,000 we’ll assign a value High salary so all this we are going to do using our case expression in post SQL so I’ll start with my select statement but before that let me show you how to write a comment in post SQL so you can write a comment by giving a Double Dash comments are very helpful because they make your codes or the scripts readable I’ll write case expression in postc SQL similarly if you want you can go to the top and let’s say here you can write with Double Dash having clause okay let’s come down so I’ll write my select statement as select I want the department the country and the salary column I’ll give a comma and I’ll start with my case statement I’ll write case when my salary is greater than 45,000 and my salary is less than 55,000 then the result would be within single codes I’ll write low salary so this is exactly like an if else condition next I’ll write another case when salary is greater than 55,000 and salary is less than let’s say 80,000 then the result would be medium salary and finally I’ll give my last condition that is when salary is greater than 80,000 then the result will be high salary let me write this in a single line then High salary now one thing to remember in postris SQL the codes are insensitive so you can write your select statement in capital in lower case or in sentence case similarly I can write case as small C or you can write as Capital C all right now moving ahead after this I’m going to write end I’ll give an alas name as salary range now this is going to be my new column in the output let me just come down after this we need to give our table name from employees I’ll order it by salary descending okay so what I’m going to do here is I’ll first select Department country and salary column from my employes table and then I’m creating a new column that is salary range and I’m specifying the range so I have three conditions here for low salary for medium salary and high salary so so let’s run this and see the output there you go here you can see we have added a new column known as salary range and we have order our salary in descending order so all the highest salaries appear at the Top If I just scroll down you can see we have medium salaries here and if I scroll down further you can see this low salaries so case statements are really useful when you want to create a new column based on some conditions in the existing table all right now moving ahead we are now going to see how to write subqueries in post SQL so subqueries we write a query inside another query which is also known as nested query so suppose we want to find the employee name Department country and salary of those employees whose salary is greater than the average salary so in such cases you can use subqueries but let me show you how to write a query inside another query first I’ll write the select statement I’m going to select the employee name comma I want the department comma also want to display the country name and the salary from the employees table where my salary should be greater than the average salary so after this bear salary greater than I’m going to use brackets and write my subquery that is Select average salary from employees now let me break it down for you so first we are going to select the average salary from the employees so this particular SQL statement we’ll find the average salary from the table we’ll compare this average salary with salaries of all the employees so whichever employee has the salary greater than the average salary will display their names the department country and their original salary so if you want you can run this statement as well let me select this statement and run it for you you can see we have return the average salary of all the employees which is nearly $81,400 $6 so we want the salaries of the employees to be greater than this average value so let me run this and see how many employees have a salary greater than the average salary there you go so we have around 75 employees whose average salary or whose salary is greater than the average salary all right now moving ahead this time I’m going to tell you how to use some inbuilt functions we learn some inbuilt mathematical functions and string functions that are available in postris SQL so I’ll just give a comment there’s another way to write a comment instead of a Double Dash you can use the forward slash an asteris and inside the asteris you can write let’s say SQL functions and you need to close this so I’ll give another asteris and a forward slash so this is also a comment in postris SQL all right so first of all we’ll explore a few math functions so there is a function called ABS which is used to find the absolute of a value so if I write select abs of let’s say Min – 100 it is going to return me positive 100 or just 100 because as you know the absolute of any value will remove the negative sign involved in that value there you go so our original input was – 100 the absolute of- 100 is + 100 next let’s see another function that is called greatest so the greatest function in post SQL will return the greatest number in a range of numbers so suppose I write select greatest inside the greatest function I’ll pass in a few few numbers let’s say two I’m just randomly passing a few numbers let’s say 4 90 let’s say 56.5 and let’s say 70 I’ll give a semicolon let me run this you will see the greatest function will return the greatest integer value or greatest number that is present in the range of numbers that we have provided so in this case 90 was the largest number or the greatest numbers so we got the result as 90 again you can use an alas for each of these statements now like greatest we also have a function called least which is going to return the least number present in a range of numbers if I run this so the result is two because two is the least number that is present in this selection all right now there’s a function called mod which is going to return the remainder of a division so suppose I write select mod and this takes two parameters let’s say 54 ided 10 as you can guess the remainder is 4 and so is our result you can see it has return the remainder 54 divided by 10 the remainder is 4 all right if I scroll down now let’s see how to use the power function so I’ll write select power let’s say I want to know power 2 comma 3 which is 2 Cube that is 8 let me just run this there you go so the result is 8 you can also check let’s say power of 5 comma 3 it should be 125 all right next you can use the sqrt function that is available in post SQL to find the square root of a number I’ll write sqrt and let’s say I want to find the square root of 100 you can guess the result the output should be 10 if I run this you can see the output here 10 let’s say I want to find the square root of let’s say 144 you can again guess the result it should be 12 let’s verify it okay there is some error let me verify it again there you go it is 12 now there are a few trigonometric functions as well you can use the S function the COS function and the tan function let’s say I want to know the sign of 0 if you have studied High School mathematics you would know the sign of 0 is 0 you can see the result it is0 let’s say you want to know s 90 if I run it you can see the output here 89 all right now there are other functions like ceiling and floor that you can use so let me show you what the ceiling and floor function does I’ll write ceiling let’s say I’ll pass my floating value as 6.45 and let me run it you can see the ceiling function Returns the next highest integer that is 7 in this case since the next highest integer after 6.45 is 7 let’s see what the floor function does and let me run it as you can see the floor function Returns the next lowest integer that is six in this case or the nearest lowest integer to any provided decimal value okay now that we saw how to use mathematical functions there are a few string functions available in postris SQL so let’s explore them as well I’ll write string functions okay scroll down cool there’s a function called character length that gives you the length of a text string suppose I write select give the function as character length and inside this function I’m going to pass in a text let’s say India is a democracy this is my text let me run this okay you can see the result here which is 20 since there are 20 characters in my string that I have provided all right now there’s another function called concat in post SQL so concat is basically used to merge or combine multiple strings so I’ll write select concat within brackets I’ll give the text string now let’s say I want to combine post Crest SQL I’ll give a speed comma I want to merge post SQL is I’ll give another comma and write my final word that is interesting now what we have done is inside the concat function we have passed in separate strings and now using the concard function we want to merge the three strings let’s see what what the result is I’ll run it all right let me just expand this you can see here we have Conca inated the three strings successfully so the output is post SQL is interesting okay now there are functions like left right and mid in post SQL so what the left function does is it will extract the number of characters that you specify from the left of a string let’s say I’ll write select left and I’ll pass in my text string as India a democracy I’ll copy this and I’ll paste it here let’s say I want to extract the first five characters from my string so I’ll give five so what it will do is it will count five characters from left so 1 2 3 4 and 5 if I run this it should ideally print in for me there you go it has printed India for us all right similarly you can use the right function to extract few characters from the right of a string let’s say you want to extract let’s say I’ll give 12 characters from right so from here onwards it will count 12 characters I’ll change left to right now let me select this and run it so you can see here this is the output from the right it has counted 12 characters and returned a democracy okay now there is a function called repeat so the repeat function is going to repeat a particular string the number of times you specify let’s say I want to select and use my repeat function and inside the repeat function I’m going to pass in let’s say India and I want India to be displayed five times I’ll give a semicolon and run it in the output you can see India has been printed five times okay let’s scroll down there is another function a string function in post SQL called as reverse so what reverse function is going to do is it is going to print any string passed as an input in reverse order so if I write select reverse and inside the reverse function I’ll pass in my string that is India is a democracy I’m going to use the same string I’ll copy this and I’ll paste it here I close the codes and the brackets let’s print this you can see it here India is a democracy has been printed in reverse order there you go all right now this time we explored a few inbuilt functions that are already present in post SQL now post SQL also has the feature where you can write your own user defined functions so now we will learn how to write a function of Our Own in postris SQL so let’s create a function to count the total number of email IDs that are present in our employees table so for this we’ll write a function a user defined function so let me give my comment as user defined function okay so let me start by first writing create so this is the syntax to write a function in post SQL so I’ll write create or replace function then I’ll give my function name as count emails and as you know functions have brackets then I’ll write Returns the return type as integer then an alas with dollar symbol I’ll write total emails since I’m going to display the total number of email IDs that are present in my table I’ll close the dollar symbol then I’m going to declare a variable the variable name is going to be total underscore emails this is of type integer I’ll write big and inside begin I’ll write my select statement so I’ll write select I want to count the email IDs that are present so I’ll pass my column name that is email into total emails from my table name that is employees I’ll give a semicolon and then we’ll write return total emails as you know user defined functions often return a value so hence we have mentioned the return statement as well and now I’m going to end my function then the next syntax would be let me just scroll down Okay so here I’ll give my dollar symbol again followed by total underscore emails next I’ll write my language post SQL so the way to mention is PL p g SQL let’s give a semicolon and end it so this is my user defined function function that I have written so I created a function with the function name countor emails and this would return integer as an alas which is total _ emails we declared that variable as an integer then we started with our begin statement that has my select statement where I’m selecting the count of email IDs that are present in the employees table and I’m am putting the value into total _ email so I’ve have used the into keyword and this Returns the result as total _ emails and I have ended let’s run this okay there is some problem there is an typo so this should be integer okay let me run it once again there you go so you’ve successfully created a userdefined function now the final step is to call that function now to call this function I’m going to use my select statement and the function name that is countor emails I’ll give a semicolon let’s execute this there you go so here you can see there are 134 email IDs present in our employees table now one thing to Mark is there are total 150 employees in the table but out of them 134 employees have email IDs the rest of them don’t have so they would ID have null values all right so that brings us to the end of this demo session on postris SQL tutorial let me go to the top we have explored a lot so we started with checking the version of post SQL then we saw how to perform basic mathematical operation that is to add subtract multiply then we saw how to create a table that was movies we inserted a few records to our movies table then we used our select Clause we updated a few values then we deleted one row of information then we learned how to use the wear Clause we learned how to use the between operator we also learned how to use the in Operator Let Me scroll down we created a table called employees and then we learned how the distinct keyword works we also learned how to use isnull with wear Clause we learned about the order by Clause we saw how to alter or rename a column then we explored a few more examples on WE Clause where we learned about and and or operator then we learned how to use limit and offset as well as the fetch operator or the fetch keyword in postr SQL moving further we learned about the like operator in SQL which was used to perform pattern recognition or pattern matching you can say here we saw how to use basic inbuilt post SQL functions like sum average minimum count maximum next we saw how to update a value in a column using post SQL update command we Lo learned how to use Group by then we learned how to use having Clause then we learned how to use case expressions in postc SQL so we saw how case expression is similar to our ifls in any other programming language we explored a few mathematical and string functions and finally we wrote Our Own userdefined function so that brings us to the end of this tutorial on postris SQL in this session we will learn about how to join three or more tables in SQL that’s right so so far we have a fundamental understanding of how to join two tables but in a few situations you might have to extract the data by joining three or more tables right so that’s exactly what we are going to discuss today now without further delay let’s get started now we will jump into the MySQL workbench where we have our query ready so here we will be using three tables employe details employ employe register and employee joining register so we want employee name contact number and joining date joining date is available in joining register contact number is available in employee register and employee name is available in in employee details right so here we are utilizing all three tables and joining them to extract these three columns so here I’m providing the table name and the column name to make sure that the SQL workbench will not get confused which employee name I mean which employee name column should I access which table should I use so to clear that confusion I’m providing the table name so my SQL will use employee details table and from there it will extract the employee name column and contact number to be sure it is present in only one table so it will go to employee register and joining date it is also present in only one table so no need to specify the table name name but to be on safer side if you want to add you can add that’s well and good and it will create an impact to your interviewer considering that you know about the syntaxes so I’ll just follow the normal syntax the way I’m going now and now I’m trying to join it’s the same operation what you use to join two different tables so you’ll just join use the join clause and give the second table name and on what basis so I’m joining these two tables on the primary key employee ID so both tables have the same common employee ID So based on that I’m joining these two tables and then you will use the join Clause once again and give the third table name here and based on which primary key or which common key so this is the one which is common in both the tables and is unique which is the employee ID so I’m using the same one to join the two tables with the third one you can follow the same syntax and join another table to it as well so with this let’s execute this particular query to find our answer so there you go you got the query executed and you have the table over here with employee name contact and joining date let’s quickly get back to my SQL workbench so here let’s say you wanted to create a table and load the data so if the data is minimalistic maybe the data about 10 rows or 15 rows you can manually create a table and insert the elements into your table using such insert commands but this set like mine which is in the Excel spreadsheet and and has about 10,000 rows would you like to you know write 10,000 insert commands no right it would be really timec consuming so for situations like this MySQL workbench has enabled developers to load the data from spreadsheets within a few steps but before we get started let’s check our column headers so here you can see uh it is not compatible with the MySQL workbench or SQL commands right so it has a space and it has a word row and it is a keyword in my SQL right so we don’t want that confusion so for that reason we will try to modify this maybe using an underscore right similarly for the row ID you can eliminate space and use an underscore and when it comes to order ID the same so just let us quickly change all the column headers so that there are SQL compartible there you go so we have replaced all the headers with underscores and made them SQL compatible so let us save it and when you’re saving it just make sure that your Excel file data is also having the uh you know SQL compatible uh name so here we have load CSV to my SQL so here we have the name with space right so let’s try to change that to lowercase Excel data and like right now it is is SQL compatible Now quickly let’s go back to my SQL workbench here we have it now you can just create a new table just right click here or you can also do it from here create a new database and the new schema will be the name of your data set so let’s type it as Excel data or just Excel and apply now this is the schema apply now you have Excel right here just drop down on here you can see the tables right click the tables and here you have the option of uh import data Vis it right just click on that now browse your folders and have it so yeah another notification for you guys so you need to save your Excel spreadsheet in the form of comma separated file right let’s quickly go back and do that open your spreadsheet go to file see as comma separated file save there you go now let’s get back to workbench and now I think you will be able to find it just open next drop table of access make sure you do that to be on the safest side and check all the names here so we have a problem with row ID but that is something which you can fix down the line and before you go to the next step check all the other names as well every other name on the column header is fine just the first one we can just alter the table not a big deal and uh next it should start importing there you go the data file got imported of course it took a little while because it’s 10,000 that’s normal now let’s quickly go to the next step and here you can see 9,987 records imported successfully just click on finish and I think it should be shortly done let’s close the schema go to the query table and and yeah so you can quickly refresh so that you will have the Excel dat over here now let’s use the database that is Excel on it now we are in Excel database now the table we’re looking for is Select star from the data name the data table name is Excel data without a space semicolon just quickly run it and I think we should be shortly able to see all the data sets right over here yeah about the First Column ID we can simply use the alter table um function or query to change the name let’s quickly do that with the table name alter table rename okay what was this can you copy that copy field name rename row ID to so um a small see syntax ER there so I think they should be sorted yeah and now let’s quickly run this and I guess it should be done now let’s quickly run the select command again there you go so we have the row ID order ID uh aut dates ship dates ship in mode customer ID customer name Etc and everything is as per the expectations and that’s how you can load Excel data to mySQL workbench we will learn about the top five interview questions in SQL that you must know to crack your business analytics interviews now without further Ado let’s get started so speaking about the tough five interview questions let’s quickly jump to the workbench of SQL so I’m using my SQL workbench and here we have a database called use simply learn so SLP is the database name so we will be using the use command to get access to that particular database so we are in access to it and now let’s quickly check out tables show tables there you go we have a few tables here book collection book order employee details joining register and employee register so let’s go with the employee details so I’ll just simply shoot a command select star from EMP details so now we have our employee table so we will be using this particular data set to run few queries from our interview questions so getting back to the interview questions so most commonly you will be asked the following interview questions so the first question is you will be asked to find out the names of the employees that start with the vbls so AEI w u so they will ask a question give me the list of names that start with these five letters it can be either a or e or I O U right so what’s the question so here you will be using like operators and not like operators let’s say they want the names with vels so you can just use the like operator and use this particular command select employee name that’s the name of the column from employee register or employee details and then where employee name is like a modulus which means it should start with a and it can have any number of alphabets after that right so let’s quickly also check what do we have in employee register so I think it’s a similar table to employ details that we used before we have the same details here so no not our problem now let’s try to extract the names of the employees W names start with WS right so we will be using the we clause and like operators run the command and there you go so we have three names so if if you able to answer this question they will ask they might ask a similar question with a little modification so this time they might ask you give me the list of names that will not start with vels so you’ll just replace the like operator with not like so either they’ll ask the questions which might ask start with vels or they might ask a question which does not start with vels this is one of the common questions now going to the second question so here also they will give it a Simple Start they will ask to give the details of the employe who has the highest salary or they will ask you to give the highest salary you can simply use the max aggregation and you can get the maximum salary so we have $887,000 and sometimes if you are able to answer this question they will make it a little tricky to you and they will ask give the second highest salary here you can use offset or there are multiple possibilities but let me give you the simplest one where you can have the same query only difference is where salary is less than Max of salary first the subquery will be executed which will extract the maximum salary and the next one is less than so it’ll give you only one R which has a little salary which is Les less than the maximum one right so simply let’s execute the query so we will have the answer so the next highest salary is $78,000 now moving on to the third question so sometimes they will ask you to use the update commands as well so here we have some salary details of our employees in the employee register employee going to do here is let’s say this is the appraisal period and they’re giving you 15% hike to all the employees so you need to update the salary column so what you do is simply uh update table name salary plus salary into the percentage of hike which is 15% so here we adding that particular percentage in the form of decimal numbers which is 0.15 and simply run the command and you have it now you can just simply uh query the same detail which is Select Staff from employee details so you will have the updated salary list here there you go now let’s proceed with the next question that we have in our list which is about select the employee name and salary from a given range right if they ask you give me only the range of employees who ow salary lies between 50,000 to 70,000 so you can use the between operator here and range of numbers that is 50,000 and 70,000 just run this particular code and there you go you have the Dil so there are two employees whose salary lies between 50,000 and 70,000 now the last question is uh they might ask you to extract the details from a certain department so basically this might also turn up to find a difference between having and group by Clause sorry having and wear Clause yeah so this is one of the common interview questions where they will ask the difference between having and wear Clause so when you are implementing Group by in your quer query and you’re also implementing some aggregate functions like count sum Etc minimum maximum in those situations when a group by Claus is involved then you can use having when there is no uh Group by function then you can simply go with the wear Clause so here I’m trying to extract the number of people present in finance department so I’m not grouping by department so I can just use where clause and run this and now in situations where I have to group by I mean you know when I have to implement Group by in those scenarios you can include having clause in place of well so that is the fundamental difference between having and group by and also you got the understanding of group by command here imagine walking into a giant Library this isn’t just any Library it’s huge there are rows and rows of shelf each packed with thousands of books but wait you don’t need to read every book here you’re just looking for specific ones like books about space or stories about superheroes but finding what you need is such a huge uge Library that’s going to be tricky this massive library is like a database a database is a huge collection of information stored neatly ready to be used it holds everything name address grades prices whatever data you can think of but sometimes all that information can be overwhelming you don’t want to shift through everything every time you need something specific right that’s where views comes in in this video we will explore views in Sequel explaining what what they are and how they simplify working with databases we’ll also cover how to create views manage them by updating deleting and listing them and also introduce different types of views like simple complex read only and those with check option we’ll also dive into materialized views which store data for faster queries and by the end you will understand how views can manage data easier and more efficient we will also look into a quiz question to clarify your understanding so what exactly is a view let’s go back to our Library example imagine if you had a Magic Window a special one that only shows you the books about space or superheroes that you are interested in you don’t have to wander through the entire Library anymore you just look through your magic window and it gives you exactly what you need that Magic Window is what a view is in the world of databases a view is a special virtual window into a data that shows you only what you need to see and the best part is it’s not actually stor any new data it’s giving you a filtered look into a huge database think of view as a shortcut making your life a whole lot easier so let us get into the demo part about how to creating a view and the types of views in SQL so let’s start with the demo part that is how do we create a table in my SQL so here as you can see uh I’ve just logged into an online compiler and now we will just learn how we create a table and then we’ll move on to creating views and the types of views so first to create a table just enter this command just WR over here create create table sorry and this just enter the table name it could be something like student details and here you can give the U student ID name we want a student ID name in the first row so we’ll just keep s ID and and the type of the variable is integers we’ll just mention in here and since it’s a primary key you just mention it over your primary key
next variable can be something like name and for this the type is bar care you can just enter any number here suppose I’ve enter 255 I’m sorry comma next mention the address again it’s Vare address so as you can see we have created this table with student ID name so we have to give you underscore student ID name with primary key inte teer type and the name and the address over here so after we have created this table we want to insert data into the table this is our next step step so to insert data what could be the basic uh command which you can write can be something like insert into student the table name student details over here and just mention what all uh columns which we have attributes we have created which is uh S uncore ID next is name and then we have address over here and then we mention the values so now that we have created table and then we can enter our details over here so these are the values which I have inserted which is hsh Ashish prati tanra sham okay so like this you can enter the values over here and now if I want my records to be displayed here the command which I’m using is Select star from student details so all these the table will be shown here so we’ll just click on this run button over here okay so now you can see this is the Sid name number and the names which we have mentioned over here so as you can see this is the output generated this is the Sid the name and here is the address so as you can see the table is created now and the output is also shown now we will move on to the main step which is creating a view so what exactly is a view a view is like a window that lets you see specific data as I’ve already told you in the intro part so now let’s say we only care about students with S ID less than five okay and instead of running the same query every time we want to create a view so here’s how you can do it you can just simply enter the command so here’s how you can create a view so just mention this U command which is create view detail view as select name comma address from student details so student details is the table here which we have already created before and I want the student ID less than five okay so I want this to be shown here so we’ll just simply click on run over here so as you can see this is the error it’s showing why is it showing because line number 203 view must be the first statement in a query batch so to resolve this we have to ensure that the SQL batch is properly separated by go command and the view creation is syntactically correct all right so we haven’t used the go command here to do that we just simply after we have inserted our records in the table here you just type goo okay and so this is the end of the first batch and now since we have have created a view in a new batch we’ll just mention this uh whatever command we have already given and at the end of the second batch we’ll again write Cod okay and now next I want my query to be shown here so I’ll just write this command for my for generating my output which is Select select star from and the table name okay not that uh student details table name name I want this the view table name to be show which is detail view right this is the table name so just copy it from here just paste it give this semicolon so now you can see a view is created so why have we used go because go ensures that to create view command is executed in a new batch and this will help the SQL Server properly separate commands and avoid conflict all right right and we have also used the select star from details view which will fetch the data from The View and includes only student with student ID less than five which is danj pratik Ashish and hsh okay name and the address is displayed over here so this is our output generated now let’s talk about managing views and updating the view let’s say later on you want to update the view to also include the students age instead of deleting or recreating the view you can use create or replace view to update it so let’s add the age column to the table now so we have to just insert the data for the students here so to add a new column age to the students detail table we need to use this command which is Alter table and then provide the name of the table which is student details add age and the type is integer and give the semicolon over here all right and now we have to insert the age data for the student so to do this we will use the update command and here we will just write this update okay name of the table which is student and here we use set age is equal to 19 where S ID is equal to two no sorry with the S ID is equal to one so in the similar way you have to just update all the table over here so after updating it you can just simply search run here so like this you will just update the student details and set the age accordingly and now the next step is after updating it we have as you can see we have just entered all the age number which we want to be displayed here and we have used the insert to command to insert records into the table with the age values and now in order to select it we will uh give the command which is Select star from and the name of the table which is student details and now we want to end the P we have to use this go command enter so now as you can see we have updated and inserted all the age data for the students and we have selected all the data from student details to display the final result by giving this command which is Select Staff from student details and this is the name shown over here and here is the address and this is the age so we have inserted all the age data and we have also corrected the update statement set age is equal to 19 where Sid is equal to 1 and do not forget to add this go okay now the next thing which we will be talking about is deleting a view in order to delete a view you just simply have to uh give this command which is drop view if exists and then give the name I mean the table name which is details view right and just simply you can uh go to this just run and you can see that our table has been dropped okay so now we have deleted our table just by giving this command now so and do not forget that this command will delete the view but don’t worry the data in the original student details table will not be affected only the view table which we have created is deleted and now next we’ll be talking about listing all the views okay so now in order to list all the views just you have to Simply write this command which is show full tables where table type is equals to v i view so by doing this thing uh this output will give you all the views which we have created in this table the name student ID okay and the uh addresses and also the age so it will give you all the table view table which we have created now let’s move on to the main part which is uh the types of views in SQL now let us first understand what is a simple view so simple View view is Created from a single table it’s straightforward and it doesn’t involve complex Logics like joints or subqueries for example to create a simple table you just simply have to write this command which is create view student names as and then select name from student details okay so if you query this View and then write select star from student names okay so after doing this thing you just simply click on run so after we have written this view simple view which is create view student name as select name from student details and do not forget again to mention this go and then select query the simple view to display student names and Select Staff and student names all right and at last again add this go and here this is the output generated the names all right so by using simple query you can do this thing now let’s move on to the second card which is creating a complex view a complex view involves multiple tables or complex logic let’s say we have another table who has student marks that that stores student marks so let’s say so let’s say we have created this table student marks and uh we have given the details here and again we have inserted the data values student ID marks 1 93 these are the values which we have inserted this is the student ID and these are the marks which we have given all right so now let’s create a view that pulls data from both student details and student marks so now as you can see we have created a complex view by providing all these details and this is the student ID and the marks shown over here all right so now let’s move on to the third part which is readon view so a readon view ensures that no one can modify the data through the view this is useful when you want users to able to see the data but not change it to make the view read only you can use permissions in your SQL databases and this feature depends on on your database engine to create a readon view and SQL Server we cannot directly enforce read only Behavior with the create view statement however you can control access to the View using permissions so here’s you can how you can do it uh so first you can create the view normally you can use revoke insert update and also delete permissions from users for that particular view uring that they can only read the data so now uh this was all for the readon view let’s move on to the fourth type of the view which we are discussing today which is the check option so with the check option is seel which is with the check option I’ll just type here with check option okay this is the fourth type of view which we are talking about with check option and cq4 it ensures that any insert or update operation performed through a view complies with the conditions specified in the where laws of the view this means that you cannot insert or update records through the view that violate the condition of the view itself so let’s go through the creation of a view with the WID check option and provide an example with an explanation and expected output so now as you can see we have the expected output for the valid insertion uh using this command which is with check option and with view creation check option we created a view named a sample view as you can see here that selects student ID and name from the student details table but only where the name is not null all right so as you can see we have clearly mentioned here not null and the width check option ensures that any insert or update through the view must comply with a condition where name is not n and the first insert into sample view inserts so student where stent id6 name which also has a valid name and here is the output generated here all right this is the student ID the name over here and that’s it so now we have learned about this width check option as well now I’ll be talking about a materialized view so what exactly is a materialized view well a materialized view is different from a regular view because it stores the actual data in a database meaning the data is precomputed and doesn’t need to be fetched from tables every time you query it this makes accessing data from a materialized view much faster especially for complex query all right so as you can see we have created the table and we create three tables the order details table and the product details and also the customer details table over here and then we have provide the necessary data also the Second Step was the sample data is inserted into all the three tables the materialized view fast order summary is created to summarize orders joining data from the three tables and Computing the total cost and the next step is the materialized view is queried and because the data is precomputed it returns results very quickly with new data when added to the audit DS table the materialized view is refreshed using refreshed materialized view to include the new data all right I hope you get it why are we using the refreshed option and the next step is the materialized view is deleted using the job materialized table over here we have used this job materialized view fast order summary and in this way you can you know uh create a materialized view so now you might be wondering that what is the difference between the materialized view and the complex View and the simple view I’ll be seeing you that later so first let us now discuss why are views so useful okay so uh why are views so useful by now you might be wondering what’s the big deal with the views and here’s why it’s so useful they make our life easy you don’t have to keep writing complex queries over and over you create a view once and it saves you tons of time we also help you in simplifying data instead of pulling everything from your database use can help you narrow down exactly what you need you also help in improving security want to show only certain parts of the data to certain people use views to control what others can see without letting them touch the raw data you can also rename columns for clarity you can rename confusing columns in the view without changing the original table making it easier for users to understand the data so so let us not discuss the differences between the simple complex and the materialized view so here’s a quick summary of the differences so simple view PS data from a single table no complex logic or joints involved and it doesn’t store data it also the performance is it executes every query every time whereas the complex view it combines data from multiple tables using joints Aggregates or other complex logic and it doesn’t store data executes query every time and talking about a materialized view it stores the result of a query making it faster to retrieve data without running the query again it also stores data and it is much faster as it uses pre computed data so now it’s time for the quiz here’s a quiz question for you what is the key difference between a regular View and a materialized view in SQL the first option is regular view store data but materialized views don’t second option is materialized view stores data but regular views don’t C both regular and materialized view stores data and number D is neither of them store data so if you want to answer them you can just write them in the comment section below and that’s it views are an incredible tool in SQL that can simplify your queries improve security and make your life easier so SQL Server is a powerful relational database management system developed by the Microsoft which is widely used for managing and storing the data its benefits include High scalability robust security features and seamless integration with other Microsoft tools tools and Technologies SQL Server provides efficient data management through advanced features like indexing full text search and inmemory processing it also offers excellent support for large D sets making it ideal for Enterprise applications the built-in business intelligence tools help organization gain valuable insights from their data SQL service High availability and Disaster Recovery features ensure continuous operations with minimal downtime with strong data integrity and transactional support it ensures reliable and consistent data management across all applications that said if these are the type of videos you’d like to watch then hit that like And subscribe buttons and the bell icon to get notified so in this session for today which is SQL over tutorial we will cover the SQL Basics that is how to create a table how to insert data how to retrieve the data from the tables Etc and apart from that we will also go through some of the other fundamentals of SQL basics which include sorting in SQL server and followed by that we will also go through the group bu and OD by sequences in SQL Server next ahead we will also learn another important part which is conditional statements which includes case statements in SQL proceeding ahead we will get into another segment of today’s session which is about joints and SQL where we will be combining two or more tables in SQL Server followed by that we have the next part of today’s session which is all about the having clause in SQL Server next we will proceed with learning the next part which is about the between operator in SQL server and followed by that we will get ahead with pattern matching in SQL Server next we will cover the time and date functions available in SQL server and after that we will proceed with temp which is temporary tables and SQL server and proceeding ahead we have the most important part which is about the Common Table expressions in SQL server and followed by that we have the last part in SQL Server tutorial which is about creating views and executing a query to extract the data present in a view in SQL so far so good so these are the foundational skills in SQL Server that you need to get before becoming a pro in SQL Server so this particular tutorial will discuss the major Foundation skills the fundamental skills the basics of SE server and its operations now without further delay let’s get started with one of the compilers which can help us execute the SQL Server queries so we are on one of the SQL Server compilers available online in case if you are facing any difficulty setting up the SQL Server management studio in your PC then you can come up with this one and we’ve also set a particular tutorial where you can learn how to download and install SQL Server management studio and how to configure your SQL Server management studio and the link to that particular tutorial will be dropped in the description box below make sure to refer that in case if you wanted to execute these same codes in SQL Server management studio right so first we will be dealing with two different data table so we will be dealing with customer data and dealership data so the first table will be about the customer data where we will be having about the order ID audit date delivery date dealership in code product category and car fuel type Etc followed by that we will insert some rows into that particular customer table about 15 to 20 tables and after that we have dealership database where we will be having AIT date state region customer ID customer name primary foreign Etc and we will be inserting about 20 entries into that particular table don’t worry if you have more than 20 entries in case if you have more than 20 entries let’s say about 2,000 entries or 20,000 entries it’s not at all a big deal if you’re working on SQL Server studio right there you can use the wizard to just ingest the data from your Source into the SQL Server right you can use ssis tool to import all that data and you’re good to go you don’t have to manually create the data and you don’t have to manually insert the data just for the sake of learning the basic process of how to create a data table and how to insert the data table you’re going through this particular procedure so far so good so we have also inserted the data in the next data table which is our dealership data and now let’s query the data from our tables and now let’s select the execute data there you go we have the data table right over here and let’s copy this query and paste it to query the data from the customer table as well so instead of dealership we will be writing down customer so if You observe closely I’m using uppercase for us like select and from and sentence case or lower case for the variables the table names Etc so that there’s a difference between the keyword as well as the regular variables there you go we have executed the customer data and here we have it the order ID order date delivery date dat to deliver category and Etc now let’s mention the use cases corre so um let’s use double codes or maybe we can also use hasht along with the pipe symbol here or the slash symbol here and write the use cases and then proceed with executing the codes or queries so the first use case is let’s try to filter customers from specific regions and now let’s close this particular command proceed with writing the query so we will be using select keyword and we want customers from a specific region right so let’s write down the customer name so I think the customer name is not mentioned in the customer data but instead of customer name we have a order ID so let’s extract the order ID not a problem select order ID and dealership name for state and the important part which is about the region and what product did they and what’s the revenue that uh the dealership has extracted out of that particular customer from the table customer next line is about join dealership so we will be using join table dealership the keyword so we have one common keyword in between both the tables which is about the order ID which is equals to order ID so this is not done here since we are clubbing both tables we need to specify the tables here so dealership do order ID and customer. Order ID so that the SQL Server will identify via are trying to map two different tables and uh we are trying to combine and extract the data now we are trying to filter out uh customers from a specific region correct now we will be using we Clause to specify that particular region so let’s go with west region correct since we are using the text format here so it’s better we choose double codes correct now let’s run this query let’s give it a next try ambiguous order ID so um let’s do one thing we will pull customer table name here so that it’s no more ambiguous there you go so the thing is we have order ID in both the tables customer table and dealership table so SQL Server got confused here which particular table you want me to extract order ID from so if you mention customer table or dealership table it will choose a specific table and extract that particular column now we have the order ID dealership and all the members that we selected are from the vest region if you check here now let’s proceed with the Second Use case of today’s session or okay let’s continue with the same here so that it is clearly visible for us now let’s sort you’re using the sort command here products B B on the revenue so it’s like maybe uh highest revenue should be in the top or lowest Revenue should be in the top let’s go with the highest revenue okay sort products based on uh or based by Revenue we will write the command here itself we will go with uh some columns I would like to have product here so I’ll eliminate everything else and the product will be here and I want the revenue as well now I don’t want the revenue I want the total revenue so if you’re looking for total then you will be going with the function or aggregate function which is sum right I want the sum of all the revenues that particular product has earned throughout the years or that particular Financial Year from which table so I have both product and revenue in the customer table itself so I’ll go with customer table itself I don’t want to join anything here I’ll eliminate the join command and uh instead of region or instead of we command I would use the group by command here bu product and it is not done so far we want to order it so we want to keep it in descending order so that the highest grossing product is on the top and the lowest Crossing product is on the bottom right so that we can also make make sure that our inventory is filled with those products which are giving us High Revenue so we will be using or bu total revenue right so uh we can give it an Laos as total revenue all right now we can use this particular term here order by total revenue descending DEC is good enough now this is how you will sld the products now let’s execute this particular query there you go so the car Model T okay yeah so the car model j is giving us the highest revenue next is followed by TM and sng so we are not mentioning specific if you go back to the uh table here we are not mentioning the actual car brands and actual car Nam so that we don’t want any copyrights to be faced so we are just mentioning some random names not to be too specific there now let’s proceed with our next query for the session where we want to group by state and calculate total revenue let’s edit the same comment here don’t worry if you want this uh demo document we will also link that demo document with all edit and view rights so that all the viewers can have a quick glance and try to execute these queries in their own local systems okay now let me type Down group by state and calculate total revenue there you go now let’s try to edit the same query now we want statewise revenue and we want from customer table right we want to join dealership for this particular one because dealership is the one which has some details for it so the state data right here you can see we have inserted State data California Texas so we want we want the state data so it is present in dealership table so we also want to perform a join there no worries let’s edit the same query here so we want instead of product we want state and instead of sum of Revenue uh yeah we want Revenue so we will keep it as it is total revenue as total revenue some of Revenue as total revenue from customer table and we want to perform a join operation so let’s create some space join dealership okay uh let’s copy the name so that we don’t make any confusions here dealership sorry here don’t worry we’ll make some edits down the line dealership on order ID so let’s go with the order ID which is available here Order ID equals to order ID remember the first step we did eliminate the confusions by mentioning the table names dot column name and customer name sorry the customer table name do column name on yeah we did it on dealership do order IDE equals to customer. order ID now we will be performing the group buy operation we don’t want uh the order buy Here Group by state of course in case if you wanted to you know order by the highest crossing state you could have used order by there but so far according to the use case we don’t want that so let’s continue with the same exec tion here click execute and you will be having the answer here so based on the states you have their respective revenues there you go now let’s proceed with the next use case for today’s discussion which is about using the conditional statement like case using case query or clause for custom calculations we’ll perform some customized calculations now let’s say we wanted to find out a product which is uh giving Revenue greater than 10,000 as high Revenue let’s say we have revenues in terms of thousands of dollars and let’s have a benchmark like $10,000 and $10,000 is the minimum Revenue you wanted to extract out of that product and if it is not yielding at least 10,000 for your dealership then that product is not selling much so that you can at least make some space in your dealership so that you can import some products which are giving you highest uh Revenue right so we want to find out those uh products which are giving us revenue between 5,000 to 10,000 as medium revenue and less than 5,000 as low revenue and greater than 10,000 as high Revenue you understood the game right so we have three segments High Revenue medium okay okay type of Revenue Vue and least Revenue product so that you can eliminate the least Revenue products out of your inventory now we want order ID so copy the order ID from here and paste it here so we are looking for order ID and we are also looking for product so uh we don’t want some much revenue here let’s eliminate this one and instead of that let’s add product from we’ll extract this from okay before from uh this this form from statement will be at the last here we will begin with a use case right let’s type case now when a specific product or Revenue okay let’s revenue is greater than $10,000 then let’s not use sentence case let’s use keywords and caps then mention it as high or high Revenue let’s copy paste the same code here when revenue is between between 5,000 and we will be using an and operator here then term it as okay we don’t want alter average revenue or medium revenue and copy paste the same here we remove the alter and revenue is less than okay I think we don’t want to use this instead of this we can just place else right so we will place else it should be termed as low revenue or least let’s go with low Revenue there you go and now from which table you want to extract that I want to extract all this data from customer table so everything will go off apart from that now let’s execute this particular code let’s see if we get any errors incorrect Syntax for case I think we made some mistake here okay we forgot the comma here should have mentioned a comma and yeah so the thing is we by mistake chose the alter from suggestions alter keyword from suggestions so far we missed a comma and Al from suggestions I think it’s everything good to go let’s try to execute and if it faces some issues no problem we’ll try to resolve it in a different way so incorrect we missed to write the end okay we did not end the case okay okay fine fine not a problem end as okay uh let’s term it as uh the entire uh table as Revenue category since we are uh splitting into three categories Revenue categories there you go so this is the way to learn make some mistakes that uh you can learn in a better way for the next time you’ll never make a mistake so far so good so we have all the car models categorized into the uh revenue revenue categories High Revenue low Revenue so far we have all the cars in high Revenue not a bad deal I think all the cards are performing really well maybe if you change the numbers a little bit maybe if we take up one lakh in place of 10,000 then maybe we can get a couple of costs but so far so good this is how the query works now let’s uh switch to our next query next use case where we will be combining data from multiple tables using joh we already did that but still for the sake of uh learning experience we will also perform that particular operation so we will be naming this particular use case as combine data from multiple tables using a join so far you have already have a good experience on how joins work but still we will try to do that now we will use customer table here customer table. order ID and uh we want customer table do product and customer. Revenue and uh let’s also say take some data from dealership so we already know that some data of states is in dealership so we’ll also take the dealership data so uh dealership dot State also take the region dealership. region from customer table let’s eliminate the case statement from customer and we want to join let’s push this to the first line so that we don’t have confusion how and where the query is going on so here I want to join so the second line is all about join dealership so let’s copy this we we are combining dealership with customer on order ID in the same way we will take order ID equals to order ID now which order ID is equals to which order ID the first table customer. order ID is equals to the second table dealership order ID so that SQL Server understands which columns from which tables are being joined here for what reason right so far so good we have uh given the columns that we want to have in our output which are these columns and we are joining two tables based on certain criteria but now maybe we can specifically me mention some more data let’s say we already mentioned some uh query where we wanted data for a specific region let’s try to continue that where region is equals to West there you go let’s close the single code or double code now what happens is it is trying to give us the details of customer order ID product Revenue state region from customer table and we’re going to also execute or extract the details of state and region from the dealership table and we’re trying to join to extract those data with dealership data and we are specifically extracting the data where the region is West let’s execute the data don’t worry if we find any errors in this particular code there you go we have the result so we have all the details from the west region there you go let me expand this so that we have a better view anyways it’s okay now let’s go with the sixth quarium for today’s session where we will be executing a query based on having close in SQL server and we will try to filter out some states only show the states where total revenue is greater than 50,000 just like we discussed before we initially used a case statement with $110,000 at least Revenue but now let’s increase the number to 50,000 and we want those states which are giving us minimum 50,000 Revenue so let’s uh rename the use is here we will try to name it as filter data or groups with having with having Clause okay so we want uh State we have state here and let’s also count as total orders so order ID so customer. order ID will be now count of total orders so the count will be the aggregation function here count total order IDs and we can name it as total orders and uh do we have Revenue yes we have revenue and let’s also remove the product I don’t think we might need a product here and the aggregation will be some aggregation has sum of Revenue and I don’t think we need to specifically mention it here but anyways we’ll keep State first copy State and drop it here we want State count of orders as orders and sum Revenue as total revenue what this does is it’ll give a Clarity right so instead of uh if I don’t alos it what it shows is sum of Revenue and for a generic person it might not be as helpful as a data engineer can right for a data engineer data analyst he can totally understand by just reading the agregation function so we counting the orders here we are getting the sum of Revenue but for a mere person who just wants to see the report the business guy who just wants to see the report for him total orders or uh total revenue is a simplest language that he can understand correct now we are extracting this data from customer and uh we will join dealership again okay because we also want to extract the state right so we did not mention the state here but we can mention the state anyway okay we did mention the state so we since we have the state column for extracting State details will anyway go for the dealership so we are already joined dealership data with customer data and let’s do a group by function here Group by region Group by state actually and now the condition having some of Revenue at least or greater than 50,000 so we will go with the having Clause here and sum of Revenue or you can also use the aliah’s name total revenue greater than $50,000 so let’s execute this query and see if the alas works or not okay I think alas will not work here in case of alas let’s go with the ACT ual term and place it over here and now let’s try to execute this if it works or not okay we mentioned two things here region and the state so we just wanted State there not region I think this should solve the issue 20 rows affected ambiguous column order ID now we will let’s say take customer name and place it here or I think the dealership would be the best because we have the details of orders here no no no customer table has the order details so let’s keep it that way there you go so we have uh so many number of states which have Revenue greater than 50,000 so these are the outputs there you go now let’s proceed with the next query where we will be using the range function which is also known as the between function in SQL Server so let’s name the comment as using the range function let’s not uh capitalize it using the range function named between so between is the keyword right now let’s build a use case let’s identify couple of uh States we will use the same query will not make some major differences here so we we want to identify a couple of States whose revenue is greater than 50,000 but less than one L right this makes a good use case for that for that implementation of bit function we will keep all the uh columns as they are and maybe we can also include a couple of columns maybe product as well and uh we will join two tables now I think we don’t need a group by here but in place of group by and in place of having we will specify where some so to use where Clause I mean to use between Clause having is not the right keyword where is the right keyword so Su of Revenue should be in place of the symbol between you take the suggestions and one lakh yeah this is 1 2 3 4 5 zeros so this is is the right way now let’s try to execute if it works or not if there is some error yeah there is some error an aggregate may not appear where Clause unless it is subsidary okay contain having claes select I think this is the place where we can go with the alas name let’s try that or if areas does not work then we will go with a revenue okay let’s simplify this let’s not go with the join statement here let’s eliminate the join we shall just simplify we don’t want State uh we won’t okay let’s not count this there was no need for counting I think that was one error we will go with order ID I to L we don’t want this and anyways we want to take a look at the the product and dealership name as well and we also want revenue from customer table where revenue is between these numbers let’s try to simplify and run this query think it should work yeah it worked so these are the uh dealerships and products which yield in revenue between 50,000 to 1 lakh right so this is the best way to use it so we had some extra aggregate functions which complicated the query no no problem now let’s go with some pattern matching sometimes uh let’s say we are looking for sales from California something like that or we are looking for some car model correct and we don’t know the full name or we might have a spelling mistake right uh we have California here but let’s say we don’t know the spelling of California but we know the first three or four letters of California right so in those instance what you can do is try to match the pattern that we have in our hand with the pattern which is available in the data table and wherever it finds a match it extracts those rows so this is how the pattern matching works now let’s execute a query for a better understanding let’s keep the same query use okay let’s change uh the use case here using the pattern matching in SQL Server so we will have order ID as it is dealership name as it is and product as it is from customer table where product so let’s copy this and paste it here like or I like I like is uh the opposite so let’s go with like car model let’s check with the car models first so all car models are the same so me maybe if uh we go with the fuel type I think fuel type will help because all the card models have the keyword card model and only thing is an alphabet M Etc so it doesn’t make sense for us to execute bit uh the like operator here so instead of product let’s keep fuel type like hybrid correct let’s go with the hybrid one so we will take only the first four letters let’s imagine we don’t know the full spelling of hybrid so if the M pattern is like and since it’s a text we will use uh single quotes or double quotes if the pattern H hybr matches with the elements or the column present in the customer data it will pull all those uh columns or rules now let’s execute this so there you go okay we one important thing we missed to include the percentage this percentage symbol will make SQL Server understand that the text should have hybr and after that anything is accepted so anything which has a beginning with hybr should be pulled out right now let’s execute once again and see the data there you go you have it correct so remember the symbol percentage right and in case if you did didn’t knew uh the hybrid let’s say it has some ybr in its format right it’s it has some vbr in the format anything before vbr is okay anything after vbr is okay again it will yield the same result hybrid there you go and in case if you wanted to change let’s write the name of petrol I don’t know the spelling of petrol so let’s say p e d so let’s imagine I don’t know the name of petrol so instead of petrol I’m writing eliminating p and I’m writing p e t r and anything after that now let’s run this query and see the output there you go so we have all the vehicles which are of fuel type petrol so this is how you can use pattern matching in SEL server now let’s perform some calculations with dates right so we’ll perform some date and time calculations let’s rename the comment as state and time functions and time and some mathematical math Cals now let’s say you are the owner of dealership and uh let’s say for a specific car you are losing customers initially it was using uh initially it used to perform very good like many customers used to come for that specific car and right now that specific car is receiving less orders and you order to find out what is the reason behind it and after a General survey you come to know that the number of days you took to deliver that car is growing let’s say earlier you used to deliver that car in 2 days but right now you’re taking like two months to deliver that car right so that might be the reason but you wanted to make sure that you have a solid proof that you have the number of days that you’re looking at to show your sales team why is so many number of dayses being taken to deliver a card now for that let’s go with select order ID order date you want order date for it now you can simply copy the order date here and paste it there and you also want the delivery date and copy that and paste it that remember these date and Order date and delivery date are of date data type and now you want to calculate the difference so for that you use a function called Date diff or date diff so the the you know there’s there’s two ways of calling it so if you prefer calling it as date right diff or a you call it as dated if okay so there’s two ways of calling that function so I prefer to call date diff because date difference so date diff comma sorry uh Open Bracket so we want to provide some details here so I want to provide a day I want to count the days right so I want to count of days I’m mentioning day and Order date difference between the order date and the delivery date you can specify that using a comma so I want the difference between these two in case if you want to Alas it you can also do that days to deliver from customer and we don’t want this simply place a semicolon there and now just copy this and execute there you go now you have the uh number of days that you or your sales team is taking to deliver the vehicles so and on an average you’re taking about 10 days to deliver now you can prove this to your sales team and uh let them know this is not good you want to have at least minimum 4 to 5 days or 2 to 3 days to deliver a vehicle if this goes on the say might drop and it might be a little problematic right now let’s proceed with the next use case of today’s session about the temporary tables now why temporary tables so there comes a situation where you have to just run some numbers run some something very uh not too critical but you just wanted to do that so in such scenarios what you can do is you don’t want to harm the original table so what you can do is you can create a temporary table or a copy of that table which is somewhere in the intermediate memory storage and as as soon as you close the studio it fades away and nothing happens to your original data table so that is where the temporary tables come to come into picture now let’s create a simple use case for that particular temporary tables right so we will be selecting order ID and let’s also take product and let’s also take Revenue into temp or yeah it’s enough temp order tables I don’t want that temp order and I don’t want to it and from which table are you taking that I’m taking that from customers you can either choose to keep it in in a new line or you can keep it in the same line but I want to keep it in a new line from customers and where revenue is I said you right you wanted to just explore a few things which is not too mandatory uh but you just want to take a look at it that’s why you take the option of creating U temporary tables and I want to find out which are those uh products which are giving us Revenue greater than 1 to 3 4 five1 lakh dollar right now let’s run this it’s run it’s done but we don’t know where it is so what you can do is you just write up simple select query select stock from your temporary table close the query and run it there you go so far there are no such uh products which are giving us greater than one lakh sales of that single product in valid object name temp order okay there might be some error about this particular query let’s try to reduce the number did we miss anything where revenue is greater than okay this is a number we don’t want semicolon there okay we missed a semicolon here let’s run this execute let’s keep it as 10,000 okay okay so there was no certain product which was above one lakh that was a problem okay so these are the products which are giving us U 10,000 sales at least not a problem now let’s proceed with the next uh important part of today’s session which is about the Common Table Expressions so Remember Common Table expressions are also known as CTE play a very major role in realtime data analytics right so uh let’s have a sample of that let’s create a Common Table expression which is rather simple and uh just learn how technically it works right so the only difference is the CTE start with a keyword word named as withd and after that you can term your uh comment table as some data so or some name I’ll give it give it as sales data as and open a bracket and inside this bracket is where you write your actual query now let’s organize a few things I don’t want the temp order table here and I don’t want temp order here from okay I I want to extract a few columns I want uh maybe State and I maybe want uh I don’t want order ID I want Revenue maybe revenue is good so let’s sum the revenue and uh term it as total revenue from customer and now let’s proceed with a join command where we will be joining dealership data let’s copy the dealership data table name we will be joining based on the order ID that is common so uh maybe order ID copy the order ID is equals to order ID and which order ID are you talking about I’m talking about uh customers order ID and dealership data order ID so we need to mention that on dealership. order ID and customer. Order ID Group by state good since we took State as well we can use a group by function here and this is not the end of uh everything so semicolon may have to wait so this is the first part now using this particular CTE this entire term is CTE so this particular the output of this particular query will be stored in sales data now we will make use of this CT or sales data turn to extract a few more queries so we will be writing another select statement select state from from okay let’s also take the total revenue which we created here let’s take the same term here so that we don’t make a mistake from the CT which we created very recently which happens to be the sales data where total revenue is crossing something about $50,000 and now is the semicolon let’s try to execute this there you go so a few regions or a few States and total revenue Vue which are exceeding $50,000 are there you go what is post SQL postris SQL is an open-source object relational database management system it stores data in rows with columns as different data attributes according to the DB engines ranking post SQL is currently ranked fourth in popularity amongst hundreds of databases worldwide it allows you to store process and retrieve data safely it was developed by a worldwide team of volunteers now let’s look at the history of post Christ sequel so in 1977 onwards the Ingress project was developed at the University of California Berkeley in 1986 the post Chris project was led by Professor Michael Stonebreaker in 1987 the first demo version was released and in 1994 a SQL interpreter was added to postris the first postris sequel release was known as as version 6.0 or 6.0 on January 29 1997 and since then post SQL has continued to be developed by the post SQL Global Development Group a diverse group of companies and many thousands of individual contributors now let’s look at some of the important features of postest SQL so postest SQL is the world’s most advanced open source database and is free to download it is compatible as it supports multiple operating systems such as Windows Linux and Mac OS it is highly secure robust and reliable postp SQL supports multiple programming interfaces such as C C++ Java and python postp SQL is compatible with various data types it can work with Primitives like integers numeric string and Boolean it supports structured data types such as dat and time array and range it can also work with documents such as Json and XML and finally postris SQL supports multiversion concurrency control or mvcc now with this Theory knowledge let’s look at the post SQL commands that we will be covering in the demo so we will start with the basic commands such as select update and delete we will learn how to filter data using wear clause and having clause in SQL we will also look at how to group data using the group by clause and order the result using the order by Clause you will learn how to deal with null values get an idea about the like operator logical operator such as and and or we will also explore some of the popular inbuilt mathematical and string functions finally we’ll see some of the advanced concepts in postris SQL that is to write case statements subqueries and user defined functions so let’s head over to the demo now okay so let’s now start with our demo so first we’ll connect to post SQL using psql cell so here under type here to search I’ll search for psql you you can see this is the SQL cell I’ll click on open let me maximize this okay so for Server I’ll just click enter database I’ll click enter port number is already taken which is 5432 I’ll hit enter username is already given and now it is going to ask for password so here I’ll give my password so that I can connect to my post SQL database so it has given us a warning but we have successfully connected to postr SQL all right so now to check if everything is fine you can just run a simple command to check the version of post SQL that we have loaded so the command is Select version with two brackets and a semicolon I’ll hit enter okay you can see the version post SQL 13.2 okay now let me show you the command that will help you to display all the databases that are already there so if I hit /l and hit enter it will give me the list of databases that are already there so we have post SQL there’s something called template zero template 1 and we have a test database as well okay now for our demo I’ll create a new database so first I’ll write create space database and I’ll give my database name as as SQL demo I’ll give a semicolon and hit enter you see we have a message here that says create database so we have successfully created our SQL demo database now if you want to connect to that database you can use back SL c space SQL demo there you go it says you are now connected to database SQL demo so here here we can now create tables we can perform insert operation select operation update delete alter and much more now I’ll show you how to connect to post SQL using PG admin so when you install the post SQL database you will get the SQL cell and along with that you also have the PG admin so I’ll just search for PG you can see here it has prompted PG admin I’ll click on open this will open on a web browser you can see it has opened on Chrome and this is how the interface of PG admin looks like it is a very basic interface so on the top you can see the files we have object there’s tools and we have the help section as well and here you have dashboard properties SQL statistics dependencies dependence and here on the left panel you have servers let me just expand this so it will connect to one of the databases all right so if I go back you see when I had run back/ L to display the databases it had shown me post SQL and test now you can see here we have the post SQL database and the test database all right now we also created one more database which was SQL demo so let me show you how to work on this PG admin and the query tool all right so I’ll right click on SQL demo and I’ll select query tool I’ll just show you how to run a few commands on the query tool so let’s say you want to see the version of post SQL that you are using so you can use the same command that we did on psql Cell which is Select version closed with brackets and a semicolon I’ll select this and here you can see we have the execute button so if I hit execute or press F5 it will run that query you can see we have the output at the bottom and it says post SQL 13.2 compiled by visual C++ it has the 64-bit system okay now let me tell you how to perform a few basic operations using post SQL commands so here let’s say I’ll write select five into 3 I’ll give a semicolon select this and hit F5 so this will run the query and it returns me the result that is the product of 5 and three which is 15 similarly let’s edit this let’s say I’ll write 5 + 3 + let’s say six I’ll select this and hit F5 to run it it gives me the sum of 5 + 3 + 6 which is 14 now the same task you can do it on this cell as well let me show you how to do it here so let’s say I’ll write select let’s say I want to multiply 7 into let’s say 10 you know the result it should be 70 if I hit enter it gives me 70 now this question mark column question World we’ll deal with this later all right let me go back to my PG admin again let me do one more operation let’s say this time I’ll write select 5 multiplied by and within brackets I’ll write 3 + 4 I’ll give a semicolon so what SQL will do is first it will evaluate the expression that is there inside the bracket that is 3 + 4 which is 7 and then it will multiply 7 with 5 now let me select this and I’ll hit execute so you can see 7 * 5 is 35 all right now we’ll go back to our shell and here I’ll show you how to create a table so we are going to create a table called movies on the cell that is psql cell so here we will learn how you you can create a table and then you can enter a few data into that table all right let me just scroll down a bit okay so my create command goes something like this so I’ll write create table followed by the table name that is movies next my movies table will have a few columns let’s say I want the movie ID after the column name we need to give the data type so movie ID I’ll keep it as integer so integer is one of the data types that is provided by post SQL next my second column the table would be the name of the movie so I’ll write moviecore name so all the variables or the column name should be as per SQL standards so there shouldn’t be any space between the column name so I have used underscore to make it more readable so my movie name will be of type varar or variable character or varing character and I’ll give the size as 40 so that it can hold 40 characters maximum next my third column will have the genre of the movie so I’ll write moviecore Jer again joner is of type barar I’ll give the size as let’s say 30 and my final and the last column we’ll have the IMDB ratings so I’ll write IMDb underscore ratings now the ratings will be of type real since it can have floating or decimal point values if I close the bracket I’ll give a semicolon and I’ll hit enter there you go so we have successfully created a table called movies now let me go back to my PG admin all right so here I have my database that is SQL demo I’ll just right click on this and click on refresh now let me go to schemas I’ll just scroll down a bit here under schemas we have something called as tables let me expand this okay so you can see we have a table called movies in the SQL demo database now and here you can check the columns that we have just added so our movies table has movie ID movie name Jor and ratings all right now there is another way to create a table the previous time we created using the SQL cell now I’ll tell you how to create a table using the PG admin so here under tables I’ll right click and I have the option to create a table so I’ll select table okay so it’s asking me to give the name of the table so this time we are going to create a table called students so I’ll write my table name as students all right these will be default as it is now I’ll go to the columns tab so here you can create the number of columns that you want so you can see on the right I have a plus sign I’ll just select this so that I can add a new row so my first column would be let’s say the student role number I’ll write student uncore RO number again the column name should be as per SQL standards the data type I’m going to select is integer all right now if you want you can give these constraints such as not null so that student role number column will not have any null values and I’ll also check primary key which means all the values will be unique for role numbers all right if you want to add another column you can just click on that plus sign and let’s say this time I want to give the student name as my second column so I’ll write student underscore name student name will be of type let’s say character wearing if you want to give the length you can specify the length as well let’s say 40 I’ll click on the plus sign again to add my final column the final colum would be gender so gender I’ll keep this time as type character okay now you can click on save so that will successfully create your students table there you go so here on the left panel you can see earlier we had only one table that was movies and now we have two tables so one would be added that was students so if I expand this under columns you can see we have the three columns here student rule number student name and gender you can also check the constraints it will tell you if you have any constraints so you can see it says students rule number there’s one primary key all right all right now let me run a select statement to show The Columns that we have in the movies table so I’ll write select star from movies give a semicolon and let me execute this okay so here on the at the bottom you can see we have the movie ID the movie name movie JRE and IMDb readings now the next command we are going to learn is how to delete a table so there is one way by using the SQL command that is drop table followed by the table name let’s say you want to delete students you can write drop table students and that will delete the table from the database this is one of the methods so you just select and run it now the other way is to you just right click on the table name and here you have delete slash drop if I select this you get a prompt are you sure you want to drop table students I’ll select yes so you can see we have successfully deleted our students table all right now let’s perform a few operations and learn a few more commands in post SQL so to do that I’m going to insert a few records to my movies table so for that I’ll use my insert command so I have my insert query written on a notepad I’ll just copy this and I’ll paste it on my query editor okay so let me just scroll down all right so here you can see I have used my insert command so I have written insert into the name of the table that is movies and we have the movie ID the movie name movie Jer and IMDb readings and these are the records or the rows so we have the first record as movie ID 101 the name of the movie is a very popular movie which is vertigo then we have the movie genre that is Mystery it is also a romance movie and then we have the IMDb readings the current IMDb readings that is 8. three similarly we have sank Redemption we have 12 Angry Men there’s the Matrix 7 inter staler and The Lion King so there are total eight records that we are going to insert into our movies table so let me just select this and hit execute okay you can see it has returned successfully eight records now if I run select star from movies you can see the records that are present in the table so I’ll write select star from movies I’ll select this and I’ll execute it there you go at the bottom you can see eight rows affected if I scroll this down you have the eight records of information in the movies table all right now if you want to describe the table you can go to the SQL cell and here if you write back SL D and the name of the table that is movies this will describe the table so here you have the column names this has the data type and here you can specify if there are any null values or any constraints like default constant or primary key or foreign key and others let me go back to my PG admin okay now first and foremost let me tell you how to update records in a table so suppose you have an existing table and by mistake you have entered some wrong values and you want to update those records later you can use the update query for that so I’m going to update my movies table and I’ll set the genre of movie ID 103 which is 12 Angry Men from drama to drama and crime so in our current Table we only have Jon as drama for 12 Angry Men I’m going to update this column which is the movie genre to drama and crime okay so let me show you how to do it I’ll write update followed by the name of the table that is movies go to the next line I’ll write set then I’ll give the column name which is moviecore Jer equal to I’m going to set it as drama comma crime earlier it was only drama and I’ll give my condition using the wear Clause we’ll learn where clause in a bit so I’ll write where moviecore ID is equal to 103 so here our movie ID is the unique identifier so it will first look for movie ID 103 it will locate that movie and it change the genre to drama and crime so now you can see the difference earlier we had 12 Angry Men as drama as the movie genre now if I run this update statement okay you can see we have successfully updated one record now let me run the select statement again okay so here you can see if I scroll down there you go so movie ID 103 movie name 12 Angry Men we have successfully updated the genre as drama comma crime okay now let me tell you how you can delete records from a table so for that you can use the delete command so you’ll write delete from the table name that is movies where let’s say I want to delete the movie ID 108 which is The Lion King so I’ll write where moviecore ID is equal to 108 this is one of the ways to delete this particular movie or you can give let’s say where movie name is equal to The Lion King let me select this and I’ll hit execute now if I run my select query again you see this time it has returned seven rows and and you cannot find movie with movie ID 108 that was The Lion King so we have deleted it all right next we are going to learn about we clause in post SQL so to learn we Clause I’ll be using the same movie table again let’s say we want to filter only
those records for which the IMDB ratings of the movies is greater than 8.7 so this is my updated table now I want to display only those records or those movies whose IMDB ratings is greater than 8.7 so we’ll display 12 angry man which is 9 then we are going to display The Dark Knight which is again 9 and we are also going to display the sank Redemption which has 9.3 the rest of the movies have and IM to be rating less than 8.7 so we are not going to display those all right right so let me show you how to write a wear Clause so I’ll write select star from movies where I’ll give my column name that is IMDB ratings is greater than I’ll use the greater than symbol then I’ll pass my value that is 8.7 I’ll give a semicolon and let’s run it I’ll hit F5 there you go so we have returned the sashank Redemption The Dark Knight and 12 Angry Men because only these movies had IMDB ratings greater than 8.7 okay now let’s say you want to return only those movies which have IMDB ratings between 8.5 and 9 so for that I’m going to use another operator called between along with the wear Clause so let me show you how to use between with wear clause I’ll write select star from movies where my IMDb underscore ratings is between I’ll write 8.5 I’ll give an and operator and 9.0 so all the movies that are between 8.5 and 9.0 ratings will be displayed so let’s select this and I’ll run it there you go so we have returned the Dark Knight The Matrix the seven interal and we have the 12 Angry Men so a few of the records that we missed out where I think vertigo which has 8.3 and there’s one more all right now moving ahead let’s say you want to display the movies whose movie genner is action you can see in a table we have a few movies whose genre is action movie so you can do that as well I’ll write select star from movies where the movie genre I’m writing this time in one line you can break it into two lines as well I’ll write moviecore Jer which is my column name equal to I’ll give within single quotes action now why single code because action is a string hence we need to put it in single codes if I run this there you go so we had one movie in our table whose movie genre was action that is The Dark Knight okay now you can also select particular columns from the table by specifying the column names now here in all the examples that we saw just now we are using star now star represents it will select all the columns in the table if you want to select specific columns in the table you can use the column names so you can specify the column names in the select statement let me show you let’s say you want to display the movie name and the movie genre from the table so you can write select moviecore name Comm I’ll give the next column as moviecore Jer from my table name that is movies where let’s say the IMDB uncore ratings is less than 9.0 so this time in our result it will only show two columns that is movie name and movie JRE let me run it there you go so these are the movie names and the movie genners you can see that have an IMDB ratings less than 9.0 all right like how you sh the between operator there is one more operator that you can use with the we Clause that is the in operator so the in operator works like a r clause or an or operator so let’s say I want to select all the columns from my movies table where the IMDB ratings is in 8.7 or 9.0 if I run this it will display only those records whose IMDB ratings is 8.7 or 9.0 all right so up to now we have looked at how you can work on basic operations in SQL like your mathematical operations you saw how a select statement works we created a few tables then we inserted a few records to our tables we saw how you can delete a table from your database and we have performed a few operations like update delete and we saw how a wear Clause works now it’s time to load a employee CSV file or a CSV data set to post SQL so I’ll tell you how you can do that but first of all before loading or inserting the records we need to create an employee table so let me first go ahead and create a new table called employees in our SQL demo database so I’ll write create table my name of the table would be employees next I’m going to give my column names so my first column would be employee ID so the employee ID will be of type integer it is not going to contain any null values so I’ll write not null and I’ll give my constraint as primary key so the employee ID as you know is unique for all the employees in a company so once I write primary key will ensure that there are no repetition in the employee IDs okay next I’ll have my employee name so my employee name is going to be of type varar and I’ll give my size as 40 okay next we’ll have the email address of the employee again email address would be of type varar and the size is 40 again I’ll give another comma this time we’ll have the gender of the employee gender is again worker of size let’s say 10 okay now let’s include a few more columns we’ll have the department column so I’ll write Department varar let’s say the size is 40 then let’s say we’ll have an another column that is called address so the address column will have the country names of the employees address is also VAR car and finally we have the salary of the employee salary I’m going to keep it as type real so real will ensure it will have decimal or floating Point values okay so now let me select this create table statement and execute it all right so we have successfully created our table if you want you can check by using select star from employees let me select this and I’ll hit execute all right you can see we have our employee ID as primary key there’s employee name email gender this department address and salary but we don’t have any records for each of these columns now it’s time for us to insert a few records to our employees table now to do that I’m going to use a CSV file so let me show you how the CSV file looks like okay so now I am on my Microsoft Excel sheet and on the top you can see this is my employe data. CSV file here we have the employee ID the employee name email gender this department address and salary now this data was generated using a simulator so this is not validated and you can see it has a few missing values so under email column we have a few employees who don’t have an email ID then you can see under Department also there are some missing values here as well all right so we’ll be importing this table or the records present in this CSV file onto postr SQL all right so here in the left panel under tables let me right click and first refresh this there you go so initially we had only movies table and now we also have the employees table now what we need to do is I’ll right click again and here you see we have the option to import or export let me click on this and I don’t want to export I need to import so I’ll switch on import all right now it is asking me to give the file location so let me show you how to get the file location so this is my file location actually so my Excel file which was this is present in my e Drive under the data analytics folder I have another folder called post SQL and within the postc SQL folder I have my CSV file that is employee data. CSV so I’ll just select this you can either do it like this or you can browse and do okay now my format is CSP next I’m going to select my headers as yes and then let me go to columns and check if everything is fine all right so I have all my columns here let’s click on okay you can see I have a message here which says import undor export all right so here you can see successfully completed we can verify this by using select star from employees again if I run this all right let me close this there you go it says 150 rows affected which means we have inserted 150 rows of information to our employees table you can see we have the employee ID these are all unique we have the employee name the email we have the address and the salary let me scroll down so that okay you can see we have 150 rows of information that means means we have 150 employees in our table okay now we are going to use this employees table and explore some Advanced SQL commands now there is an operator called distinct so say if I write select address from employees this is going to give me 150 address of all the employees there’s some problem here I did a spelling mistake there should be another D if I run this again AL query will return 150 rows you can see we have the different country names under address that is Russia we have France the United States we have Germany okay and I think we have Israel as well yeah now suppose you want to display only the unique address or the country names you can use the distinct keyword before the column name so if I write select distinct address from employee it will only display the unique country names present in the address column if I run this see it has returned us six rows of information so we have Israel Russia Australia United States France and Germany all right now as I said there are a few null values which don’t have any information so you can use the isnull operator in SQL to display all the null values that are there suppose I want to display all the employee names where the email ID has a null value so I’ll write select star from employees where email is null so this is another way to use your wear Clause if I select and run this there you go so you see here for all these employee names there was no email ID present in the table so it has written us 16 rows of information so around 10% of employees do not have an email ID and if you see a few of them do not have an email ID and also they don’t have a department so if you want to know for those employees which do not have a department you can just replace where department is null instead of where email is null now if I select this okay it has written us nine rows of information which means around 5% of employees do not have a department moving ahead now let me show you how the order by Clause Works in SQL now the order buy is used to order your result in a particular format let’s say in a sending or descending order so the way to use is let’s say I want to select all the employees from my table so I’ll write select star from employees order by I want to order the employees based on their salary so I’ll write order by salary let me select and run it okay there is some problem I made a spelling mistake this should be employees let me run it again okay now if you mark the output a result has been ordered in ascending order so all the employees which have salary greater than $445,000 appear at the top and the employees with the highest salaries appear at the bottom so this has been ordered in ascending order which means your SQL or post SQL orders it in ascending order by default now let’s say you want to display the salaries in descending order so that all the top ranking employees in terms of salary appear at the top so you can use the dec keyword which means desending if I run this you can see the difference now so all the employees with the highest salary appear at the top while those with the lowest salaries appear at the bottom so this is how you can use an order by Clause okay so now I want to make a change in my existing table so here if you see under the address column we only have the country names so it would be better if we change the name of the address column to Country so I want to rename a column you can do this using the alter command in post SQL so let me show you how to rename this column that is address so I’ll write alter table followed by the table name which is employees then I’m going to use rename column address I’ll write two I want to change it to Country if I give a semicolon and hit execute it will change my column name to Country now you can verify this if I run the select statement again there you go earlier it was address column and now we have successfully changed it to Country column okay let me come down now it’s time for us to explore a few more commands so so this time I’m going to tell you how an and and an or operator Works in SQL so you can use the and and or operator along with the wear Clause so let’s say I want to select the employees who are from France and their salary is less than $80,000 so let me show you how to do it I’ll write select star from employees where I’m going to give two conditions so I’ll use the and clause or the and operator here I’ll write where country is equal to France now Mark here I’m not using address because we just updated our table and changed the column name from address to Country so I’ll write country equal to France and by next condition would be my salary needs to be less than $80,000 I’ll give a semicolon let me run this all right so it has returned 19 rows of information you can see all my country names are France and the salary is less than $80,000 so this is how you can use or give multiple conditions in a we Clause using the and operator now let’s say you want to use the or operator and let’s say you want to know the employees who are from country Germany or the department should be sales so I’ll write select star from employees where country is equal to Germany and instead of and I’m going to use or their depart M should be sales okay now let’s see the output I’ll hit F5 this time to run it all right so we have 23 row of information now let me scroll to the right you can see either the country is Germany or the department is sales you see one of them in the table so here for the first record the country was Germany the second record the department was sales again sales again for the fourth record the country is Germany so this is how the or condition works so if one of the conditions are true it will return the result it need not be that both the conditions should satisfy now in post SQL there is another feature that is called limit so post SQL limit is an optional clause on the select statement now this is used as a con ST which will restrict the number of rows written by the query suppose you want to display the top five rows in a table you can use the limit operator suppose you want to skip the first five rows of information and then you want to display the next five you can do that using limit and offset so let’s explore how limit and offset works I’ll write select star from employees let’s say I’ll use my order by Clause I’ll write order by salary let’s say in descending and limit it to five this is going to display the top five employees which have the highest salary if I run this there you go you see it has given us five rows of information and these are are the top five employees that have the highest salary okay so this is one method of or one way of using the limit Clause now in case you want to skip a number of rows before returning the result you can use offset Clause placed before the limit Clause so I’ll write select star from employees let’s say order by salary descending this time I’m going to use limit five and offset three so what this query will do is it will skip the first three rows and then it will print the next five rows if I run this there you go so this is how the result looks like okay now there is another class which is called Fetch let me show you how that works I’ll copy my previous SQL query I’ll paste it here and here after descending I’m going to write fetch first three row only so my fetch is going to give me the first three rows from the top there you go it has given us the first three rows and you can see the top three employees that have the highest salary since we ordered it in descending order of salary all right you can also use the offset along with the fetch Clause I’ll copy this again and let me paste it here now after descending I’m going to write offset let’s say three rows and fetch first five rows only so what this SQL query is going to do is it will skip the first three rows of information and then it is going to display the next five rows it is going to work exactly the same as we saw for this query let me run it there you go so these are the first five rows of information after excluding the top three rows all right we have another operator that is called as like in post SQL so like is used to do pattern matching so suppose you have a table that has the employee names you forgot the full name of an employee but you remember the few initials so you can use the like operator to get an idea as to which employee name it is now let’s explore some examples to learn how the like operator Works in post SQL so suppose you want to know the employees whose name starts with a so for that you can use the like operator let me show you how to do it so I want to display the employee name and let’s say I want to know their email IDs from the table name that is employee where since I want to know the employees whose name starts with a so I’ll write employee name like now to use the pattern is within single course I’ll write a and Then followed by percentage now this means the employee name should have an e in the beginning and percentage suggest it can have any other letter following a but in the beginning or the starting should be a if I run this so there is an error here the name of the table is employees and not employee let’s run this again there you go you can see there are 16 employees in our table whose name starts with a you can see this column employee name all of them have a letter A in the beginning okay now let me just copy this command or the query I’ll paste it here let’s say this time you want to know the employees whose name starts with s so instead of a I’ll write s so this means the starting letter should be S and followed by it can have any other letter if I run this so there are 10 employees in the table whose name starts with s okay let’s copy the query again and this time I want to know the employees whose name ends with d now the way to do it is instead of a percentage I’ll write this time percentage D which means at the beginning it can have any letter but the last letter in the string or in the name should be ending with d now let me copy and run this so there are 13 employees in the table whose name ends with a d you can see it here all right now let’s say you want to find the employees whose name contains ish or have ish in their names so the way to do is something like this so I’ll copy this now here instead of a percentage I’ll replace this with percentage ish percentage now this means that in the beginning it can have any letter and towards the end also it can have any letter but this is message should appear within the name let me run and show it to you okay so there is one employee whose name contains ish you can see here there is an ish in the last name of the employee all right now suppose you want to find the employee name which has U as the second letter it can have any letter in the beginning but the second letter of the employee name should have U now the way to do is I’ll copy this and instead of a% I’ll write underscore U followed by percent now this underscore you can think of a blank that can take any one letter so the beginning can start with a B C D or any of the 26 alphabets we have then then it should contain you as the second letter followed by any other letter or letters let me run this okay so there are 10 employees in the table whose name has a u as the second letter you can see these okay now moving ahead let me show you how you can use basic SQL functions or inbuild functions so we’ll explore a few mathematical functions now so let’s say you want to find the total sum of salary for all the employees so for that you can use this sum function that is available in SQL so I’ll write sum and inside the sum function I’ll give my colum name that is salary from my table name that is employees let’s see the result this will return one unique value there you go now this is the total salary since the value is very large it has given in terms of E now one thing to note here is if you see the output the column says sum real so this output column is not really readable so SQL has a method which can fix this that is called an alas so since we are doing an operation of summing the salary column we can give an alas to this operation by using the as keyword so if I write sum of salary as let’s say total salary then this becomes my output column you can see the difference if I run this okay you can see now in the output we have the total salary now this is much more readable than the previous one so this is a feature in Excel where you can use or give alas names to your columns or your results now similarly let’s say you want to find the average of salary for all the employees now SQL has a function called AVG which calculates the mean or the average salary if I write AVG and I can edit my alas name as well let’s see I’ll write mean salary let’s run it you can see the average salary for all the employees it’s around $81,000 okay now there are two more important functions that SQL provides us which is Max and minimum so if I write select maximum or Max which is the function name of salary as let’s say instead of total I’ll write maximum so this will return me the maximum salary of the employee let’s run it and see what is the maximum salary that is present in the salary column all right so we have 9,616 as highest salary of one of the employees similarly you can use the minan function as well I’ll just write minimum and this will return me the minimum salary of one of the employees in the table I’ll replace the alas name as minimum okay now run it this will give me the minimum salary that is present in our table so it is $ 4,685 okay now let’s say you want to find the count of Department in the employees table you can use the count function so if I write select count let’s say I want to know the distinct Department names so I can write inside the count function distinct Department as total departments from employees let’s run this this will return me the total number of departments that are there so it gives me there are departments okay now let me show you one more thing here if I write select Department from employees let’s run this okay so it has returned me 150 rows of information but what I’m going to do is I’ll place my distinct keyword here just before the call name so that I can verify how many departments are there in total there you go so there are 13 departments and one of them is null so moving ahead we’ll replace this null with a department Name by updating a table okay so now let’s update our department column so what we are going to do is wherever the department has a null value we are going to assign a new Department called analytics so earlier we have also learned how to use the update command so I’m going to show it again so we’ll write update followed by the table name that is employees I’m going to set my column that is Department equal to within single codes my name of the department would be Analytics where department is I’ll say null so wherever the department has a null value we’ll replace those information with Department that is analytics let’s run this you can see query returned successfully now let’s say I’ll run this command again and this time you can see the difference there you go so we have 13 rows of information and there is no null department now we have added a new department that is analytics okay now we are going to explore two more crucial commands or Clauses in SQL that is Group by and having so let’s learn how Group by Clause Works in post SQL so the group by statement groups rows that have the same values into summary rules for example you can find the average salary of employees in each country or city or department so the group by Clause is used in collaboration with the select statement to arrange identical data into groups so suppose you want to find the average salary of the employees based on countries you can use the group by Clause so let me show you how to do it I’ll write select I want the countries and the average salary for each country so I’ll use the average function that is AVG and inside the function I’ll pass my column that is salary I’ll give an alas name as let’s say average uncore salary from my table name that is employees next I’m going to use my group by Clause so I’ll write Group by since I want to find the average salary for each country so I’ll write Group by country name let’s give a semicolon and let me run it I’ll use F5 there you go so here on the left you can see the country names we have Israel Russia Australia United States France and Germany and on the right the second column you can see the average salary for each of these countries now you can also order the result in whichever way you want suppose you want to arrange the results based on the average salary so you can use the order by Clause after the group by Clause so I’ll write order by here you can use the alas name that is average salary this is actually average uncore salary and let’s say I want to arrange it in descending order so I’ll write DSC now let’s run this you can mark the difference in the average salary column there you go so as per our result in United States the average salary is the highest and if I scroll down the average salary is the lowest in Germany now let’s see one more example using group buy suppose this time you want to find the maximum salary of male and female employees you can do that too so let me show you how to do it so I’ll write select this time we want to find the max salary based on gender so I’ll select my gender column comma and this time I’ll use my Max function since I want to find the maximum salary for male and female employees I’ll give an alas name as maximum underscore salary from my table that is employees Group by I’ll write gender okay so let’s run this there you go you can see so one of the female employees had a highest salary of $11 19,618 while of that of a me was $ 17,6 54 all right now suppose you want to find the count of employees based on each country you can use the count function along with the group by Clause so so I’ll write the select statement select since I want to count the employees based on each country so I’ll first select my country column and then I’m going to use the count function I’ll write count empore ID from my table name that is employees I’m going to group it by country so this query will give me the total number of employees from each country you can see here Israel there are four employees in Australia there are four employees in Russia we have 80 employees in France there were 31 in United States we have 27 so on and so forth let me scroll down okay now it’s time to explore one more Clause a very important Clause that is used in post SQL that is having so the having Clause works like the wear Clause the difference is that wear Clause cannot be used with aggregate functions the having Clause is used with a group by Clause to return those rows that meet a condition so suppose you want to find the countries in which the average salary is greater than $80,000 so you can use the group by clause and the having Clause to get the result so I’ll write my select statement as select country comma I want the average salary so I’ll write AVG of salary I can give an alas name as average salary from employees now I’m going to group it by each country so Group by country column since I want to find the countries in which the average salary is greater than 80,000 so I’ll use having Clause after the group by Clause I’ll write having average of salary is greater than 880,000 now this condition cannot be specified in the wear Clause so we need a having Clause you cannot use aggregate functions along with wear Clause let me just run it now there you go so we have Russia and United States where the average salary is greater than $80,000 all right now let’s say you want to find the count of employees in each country where there are less than 30 employees so for this I’m going to use the account function first let me select the country column then I’m going to use the count function and in the count function I’m going to pass my employee ID so that we can count the number of employees from my table that is employees now if you want you can use an alas name for this as well but I’m just skipping it for the time being I’ll write Group by country next I’ll write having count of employee ID less than 30 so this will return me the countries in which there are less than 30 employees let’s run it you can see here Israel Australia United States and Germany are the countries in which there are less than 30 employees okay now if you want you can use the order by Clause as well so suppose I’ll write here order by count of employee ID so what this will do is it will arrange my result in ascending order of employee ID count there you can see we have successfully arranged our result in ascending order of employee IDs okay next we are going to explore one more feature of post SQL that is of using a case statement now in post SQL the case expression is same as IFL statement in any other programming language it allows you to add ifls logic to the query to form a powerful query now let me just scroll down and I’ll show you how to use a case statement this is very similar to your eel statement that you use on Excel in C++ in Python and or any other programming language so what I’m going to do is I’m going to write a SQL query that will create a new column and the name of the column would be let’s say salary range so I’m going to divide my salary suppose if the salary is greater than $45,000 and if it’s less than $55,000 in the new column that is salary range we are going to assign a value low salary now if the salary is greater than $55,000 and if it is less than $80,000 we are going to assign a value that is medium salary if the salary is greater than $80,000 we’ll assign a value High salary so all this we are going to do using our case expression in post SQL so I’ll start with my select statement but before that let me show you how to write a comment in post SQL so you can write a comment by giving a Double Dash comments are very helpful because they make your codes or the scripts readable I’ll write case expression in postc SQL similarly if you want you can go to the top and let’s say here you can write with Double Dash having Clause okay let’s come down so I’ll write my select statement as select I want the department the country and the salary column I’ll give a comma and I’ll start with my case statement I’ll write case when my salary is greater than 45,000 and my salary is less than 55,000 then the result would be B within single codes I’ll write low salary so this is exactly like an if else condition next I’ll write another case when salary is greater than 55,000 and salary is less than let’s say 80,000 then then the result would be medium salary and finally I’ll give my last condition that is when salary is greater than 80,000 then the result will be high salary let me write this in a single line then High salary now one thing to remember in post SQL the codes are insensitive so you can write your select statement in capital in lower case or in sentence case similarly I can write case as small C or you can write as capital c all right now moving ahead after this I’m going to write end I’ll give an alas name as salary range now this is going to be my new column in the output let me just come down after this we need to give our table name from employees I’ll order it by salary descending okay so what I’m going to do here is I’ll first select Department country and salary column from my employees table and then I’m creating a new column that is salary range and I’m specifying the range so I have three conditions here for low salary for medium salary and high salary so let’s run this and see the output there you go here you can see we have added a new column known as salary range and we have order our salary in descending order so all the highest salaries appear at the Top If I just scroll down you can see we have medium salaries here and if I scroll down further you can see these low salaries so case statements are really useful when you want to create a new column based on some conditions in the existing table all right now moving ahead we are now going to see how to write subqueries in post SQL so subqueries we write a query inside another query which is also known as nested query so suppose we want to find the employee name Department country and salary of those employees whose salary is greater than the average salary so in such cases you can use subqueries now let me show you how to write a query inside another query first I’ll write the select statement I’m going to select the employee name comma I want the department comma also want to display the country name and the salary from the employees table where my salary should be greater than the average salary so after this be salary greater than I’m going to use brackets and write my subquery that is Select average salary from employees now let me break it down for you so first we are going to select the average salary from the employees so this particular SQL statement will find the average salary from the table we’ll compare this average salary with salaries of all the employees so whichever employee has the salary greater than the average salary will display their names the department country and their original salary so if you want you can run this statement as well let me select this statement and run it for you you can see we have returned the average salary of all the employees which is nearly $81,400 employees whose average salary or whose salary is greater than the average salary all right now moving ahead this time I’m going to tell you how to use some inbuilt functions we’ll learn some inbuilt mathematical functions and string functions that are available in postris SQL so I’ll just give a comment there’s another way to write a comment instead of a Double Dash you can use the forward slash an asteris and inside the asteris you can write let’s say SQL functions and you need to close this so I’ll give another ASX and a forward slash so this is also a comment in postris SQL all right so first of all we’ll explore a few math functions so there is a function called ABS which is used to find the absolute of a value so if I write select abs of let’s say minus 100 it is going to return me positive 100 or just 100 because as you know the absolute of any value will remove the negative sign involved in that value there you go so our original input was – 100 the absolute of- 100 is + 100 next let’s see another function that is called greatest so the greatest function in postcript SQL will return the greatest number in a range of numbers so suppose I write select greatest inside the greatest function I’ll pass in a few numbers let’s say two I’m just randomly passing a few numbers let’s say 4 90 let’s say 56.5 and let’s say 70 I’ll give a semicolon let me run this you will see the greatest function will return the greatest integer value or greatest number that is present in the range of numbers that we have provided so in this case 90 was the largest number or the greatest number so we got the result as 90 again you can use an alas for each of these statements now like greatest we also have a function called least which is going to return the least number present in a range of numbers if I run this so the result is two because two is the least number that is present in this selection all right now there’s a function called mod which is going to return the remainder of a division so suppose I write select mod and this takes two parameters let’s say 54 divided 10 as you can guess the remainder is 4 and so is our result you can see it has return the remainder 54 divided by 10 the remainder is 4 all right if I scroll down now let’s see how to use the power function so I’ll write select power let’s say I want to know power 2 comma 3 which is 2 Cube that is 8 let me just run this there you go so the result is 8 you can also check let’s say power of 5 comma 3 it should be 125 all right next you can use the sqrt function that is available in post SQL to find the square root of a number I’ll write sqrt and let’s say I want to find the square root of 100 you can get guess the result the output should be 10 if I run this you can see the output here 10 let’s say I want to find the square root of let’s say 144 you can again guess the result it should be 12 let’s verify it okay there is some error let me verify it again there you go it is 12 now there are a few trigonometric functions as well you can use the S function the COS function and the tan function let’s say I want to know the sign of 0 if you have studied High School mathematics you would know the sign of 0 is 0 you can see the result it is zero let’s say you want to know s 90 if I run it you can see the output here 89 all right now there are other functions like C and floor that you can use so let me show you what the ceiling and floor function does I’ll write seiling let’s say I’ll pass my floating value as 6.45 and let me run it you can see the ceiling function Returns the next highest integer that is seven in this case since the next highest integer after 6.45 is 7 let’s see what the floor function does and let me run it as you can see the floor function Returns the next lowest integer that is six in this case or the nearest lowest integer to any provided decimal value okay now that we saw how to use mathematical functions there are a few string functions available in postr SQL so let’s explore them as well I’ll write string functions okay we scroll down cool there’s a function called character length that gives you the length of a text string suppose I write select give the function as character length and inside this function I’m going to pass in a text let’s say India is a democracy this is my text let me run this okay you can see the result here which is 20 since there are 20 characters in my string that I have provided all right now there’s another function called concat in po SQL so concat is basically used to merge or combine multiple strings so I’ll write select concat within brackets I’ll give the text string now let’s say I want to combine postest SQL I’ll give a space comma I want to merge post SQL is I’ll give another comma and write my final word that is interesting now what we have done is inside the concat function we have passed in separate strings and now using the concat function we want to merge the three strings let’s see what the result is I’ll run it all right let me just expand this you can see here we have concatenated the three string successfully so the output is post SQL is interesting okay now there are functions like left right and mid in postc SQL so what the left function does is it will extract the number of characters that you specify from the left of a string let’s say I’ll write select left and I’ll pass in my text string as India a democracy I’ll copy this and I’ll paste it here let’s say I want to extract the first five characters from my string so I’ll give five so what it will do is it will count five characters from left so 1 2 3 4 and five if I run this it should ideally print India for me there you go it has printed India for us all right similarly you can use the right function to extract few characters from the right of a string let’s say you want to extract let’s say I’ll give 12 characters from right so from here onwards it will count 12 characters I’ll change left to right now let me select this and run it so you can see here this is the output from the right it has counted 12 characters and returned a democracy okay now there is a function called repeat so the repeat function is going to repeat a particular string the number of times you specify let’s say I want to select and use my repeat function and inside the repeat function I’m going to pass in let’s say India and I want India to be displayed five times I’ll give a semicolon and run it in the output you can see India has been printed five times okay let’s scroll down there is another function a string function in postc equl called as reverse so what reverse function is going to do is it is going to print any string passed as an input in reverse order so if I write select reverse and inside the reverse function I’ll pass in my string that is India is is a democracy I’m going to use the same string I’ll copy this and I’ll paste it here I close the codes and the brackets let’s print this you can see it here India is a democracy has been printed in reverse order there you go all right now this time we explored a few inbuilt functions that are already present in postris SQL now post SQL also has the feature where you can write your own user defined functions so now we will learn how to write a function of Our Own in post SQL so let’s create a function to count the total number of email IDs that are present in our employees table so for this we’ll write a function a user defined function so let me give my comment as user defined function okay so let me start by first writing create so this is the syntax to write a function in post SQL so I’ll write create or replace function then I’ll give my function name as count emails and as you know functions have brackets then I’ll write Returns the return type as integer then an alas with dollar symbol I’ll write total emails since I’m going to display the total number of email IDs that are present in my table I’ll close the dollar symbol then I’m going to declare a variable the variable name is going to be total underscore emails this is of type integer I’ll write begin and inside begin I’ll write my select statement so I’ll write select I want to count the email IDs that are present so I’ll pass my call column name that is email into total emails from my table name that is employees I’ll give a semicolon and then we’ll write return total emails as you know user defined functions often return a value so hence we have mentioned the return statement as well and now I’m going to end my function then the next syntax would be let me just scroll down okay so here I’ll give my dollar symbol again followed by total underscore emails next I’ll write my language as post SQL so the way to mention is PL p g SQL let’s give a semicolon and end it so this is my user defined function that I have written so I created a function with the function name countor emails and this would return integer as an alas which is total _ emails we declared that variable as an integer then we started with a begin statement that has my select statement where I’m selecting the count of email IDs that are present in the employees table and I am putting the value into total _ email so I’ve have used the into keyword and this Returns the result as total _ emails and I have ended let’s run this okay there is some problem there is an typo so this should be integer okay let me run it once again there you go so youve successfully created a user defined function now the final step is to call that function now to call this function I’m going to use my select statement and the function name that is countor emails I’ll give a semicolon let’s execute this there you go so here you can see there are 134 email IDs present in our employees table now one thing to Mark is there are total 150 employees in the table but out of them 134 employees have email IDs the rest of them don’t have so they would ideally have null values all right so that brings us to the end of this demo session on post SQL tutorial let me go to the top we have explored a lot so we started with checking the version of post SQL then we saw how to perform basic mathematical operation that is to add subtract multiply then we saw how to create a table that was movies we inserted a few records to our movies table then we used our select Clause we updated a few values then we deleted one row of information then we learned how to use the we Clause we learned how to use the between operator we also learned how to use the in Operator Let Me scroll down we created a table called employees and then we learned how the distinct keyword works we also learned how to use isnull with wear Clause we learned about the order by Clause we saw how to alter or rename a column then we explored a few more examples on wear Clause we learned about and and R operator then we learned how to use limit and offset as well as the fetch operator or the fetch keyword in postr SQL moving further we learned about the like operator in SQL which was used to perform pattern recognition or pattern matching you can say here we saw how to use basic inbuilt post SQL functions like sum average minimum count maximum next we saw how to update a value in a column using post SQL update command we learned how to use Group by then we learned how to use having Clause then we learned how to use case expressions in post SQL so we saw how case expression is similar to our ifls in any other programming language we explored a few mathematical and string functions and finally we wrote Our Own user defined function so that brings us to the end of this tutorial on postris SQL now if you want to get this SQL file that we have used in the demo you can give your email IDs in the comment section and our team will share this SQL file with you over email so what exactly is a CT you ask now if you are a beginner in sequence let’s say you wanted to Club two different tables or more different tables maybe three or four right so you will be using one keyword which is join right and let’s say you may have to create a query in such a way that you have to Club different tables and you have to extract the results from one table into another and finally create a output table right so this might be sounding a little too complex so basically Al what CTE does is it acts as a temporary table right now you can write a query and save it as a CTE right and that particular resultant table from CTE will not be created but will be in the memory as a temporary data or an intermediate resultant data right now whenever you want to use a join or whenever you want to use the same query inside a bracket or inside something in your query you can just simply use the name of the CT and then the data you require the columns you require and done you will get the data now this might be a little too complicated to understand in just m words now let’s just go through the formal definition of what exactly is a CTE and what it does and then let’s quickly so it’s a little too complicated to understand it just with m words so let’s get started with a practice iCal examples but before that let’s understand a formal definition of what exactly is a CTN SQL there CTE also known as or also called as the Common Table expression or some people also are used to call it as a width expression so the keyword is withth so a comma table expression in SQL is a temporary result set that you can Define within a query as I said it helps to break down the complex queries make the the code more readable and allows you to reuse the result set multiple times within the same query just you need to use the name of the CTE in the places where you want in your query and it reduces the code length as well as the execution time now CTE are defined using the width keyword as we discussed before followed by the CTE name right so for every uh column name or anything in your set you give a name right similarly when you are using CTE in SQL you also need to give a name to the CTE and that particular name will be used in your subquery positions that will reduce the query length and execution time so you should be giving a name and the query that generates the result set the CTE is available only during the execution of that particular query or specific query right so as I said the CTE table the resultant table which is created while you are using the CTE will not be created as a permanent table in the datab base right it will be a temporary or intermediate result which will be active as long as your current query which is using the CTE is active now let’s go to the demonstration mode then we will try to create some simple queries right and and we will understand how exactly a CT can be beneficial in those situations now let’s go to the MySQL workbench this is my my SQL workbench so I have a lot of tables here we have the credit card data set we have the sakila data set SLP data set says Superstar World Etc right so we will be using the Superstar data set uh I mean the database so firstly we need to write in the query which means that I am going to use the superstore database right sorry Superstar so I uh prefer using uh smaller case or lower case for database names and column names and uh uppercase for the keywords for example here use is uppercase and Superstar is the name of the keyword right so uh that is for uh identifying or easy readability which is a keyword and which is a name right so let’s execute this query and have access to the superstore data set and in Superstore data set I have one table called as Excel data now let’s quickly check what we have in Excel data select star from Excel data here we have R the order right ID audit dat ship mode customer everything right so we have region we have uh sales quantity discount profit rate so we have a number of possibilities and number of reports that we can generate but let’s try to keep it simple let’s try to find out unique regions right select unique of regions right or just regions Exel data Group by regions so let’s quickly execute this statement and see the output or maybe we can make some modifications to it right instead of that you might want to use you might want to use distinct function so that you don’t get all 10,000 plus rows so basically uh this particular data set has about 10,000 or more rows in it and it’s not real it’s completely made up report using artificial intelligence so we use chat GPT to create 10,000 rows of data for 30 years maybe from 2000 or 2001 to up to 2030 or 31 right so we don’t want all those 10,000 plus columns sorry rows so let’s use a distinct here and uh try to exit this statement so that we get U five uh of uh the regions what we have so there you go we have um five regions as expected NorthEast Southwest and Central now you can also uh select uh kind of maybe average of sales uh maximum of sales and total sales so so uh this is bringing us somewhere we can you know try to find out regionwise sales right so region wise sales Group by years like 30 years what was the sale happened in the year 2021 sorry 2001 right we begin from 2000 or 2001 to all the way up to 2030 or 2031 right so we can see if there is an increase in the year on-ear sales a decrease in the year on year sales you can identify the best performing eror the worst performing eror right so uh this sounds like a good use case now let’s go to the code where I’ve written it as a CTE and understand the workflow so here I have uh named my CTE as sales CTE so I’m starting it with the keyword with right so with sales CTE as now this is our query right what am I doing I’m extracting so according to the data set we have the date right so the date is year month and date of that particular day right but we want just the year so we’re using the ear function to extract the Year from the date as sales ear region uh sum of sales right we want you to find out the total sales happened in that particular year as total sales from the data set Excel data and appr by a right we wanted it in increasing order so 2000 to all the way up to 230 or 20031 correct so that’s how it is and I’m saving all this as a CTE named as sales CTE now I want to select some parts of that particular CTE so I want to select sales air region total sales from sales CD which is right over here and and order it in form of sales and region right now let’s try to copy this code and run this in our workbench right now let’s Okay let me close this quickly so that we have a complete view of the code right so let’s now select all the code so now we have selected this particular code let’s try to run this and see the output there you go we okay we have the output but there is something wrong we did not get uh the ears right so all the 30 years of data here it is Group by region which is fine okay we don’t want region we want to group it by ear that’s okay and the thing is we need to fix this particular year so maybe there is something wrong with the ud date right so I think uh the database has saved this particular oh okay okay since this is generated by chart jpd maybe the data type of the date is other than data right other than date data type it may be string now we might have to do some type casting to change the data type of the audit date and let’s quickly do that so now we have updated the ear so so what we have done is just uh cast here right so we have changed the string type of date to the normal date which follows by year month and date so this is a simple type casting that you can do and uh rest everything and we’ve also added a where condition so where uh date is not added or date is equals to null then you can just uh ignore that and uh now let’s try to execute this query and we have also removed that region thing right Group by region or order by region so we want that to be ordered according to the uh year which should start with uh 2001 or the first ever year at to the last ever year according to dat set now let’s select the entire CT query and run that and check our outputs so there you go so you have the year on-ear sales from 2001 to all the way up to the year 2030 and 2031 right so that’s how the CTE or common uh table expressions and SQL or the width query in SQL can be used so welcome to the demo part of the SQL project so in this we will do digital music store analysis okay so this SQL Pro is for the beginners so what you will learn from this uh project main thing is like so what’s the objective of this project this particular project so this project is for beginners and we’ll teach you how to analyze the music playlist database and you can examine the data set with SQL and help the store understand its business growth by answering simple questions so as you can see I will show you so I have three set of questions first one is easy okay and the second one is moderate and the third one is advanced level so we have three set of questions easy set moderate and the Advan okay so every set is of three three questions I guess yes in every set there is three three questions so okay in easy one there are five so we have 5 + 3 8 8 + 3 11 we have 11 questions to solve okay from this you will understand how you can you know analyze data with SQL how you can extract something from database how you can store something like this okay so and one more thing I will show you the schema of the particular uh data set which we will you know soon we will will restore so we have the tables in this artist album track media type genre invoice line invoice customer employee ID playlist playlist track and all okay so this is the music playlist database schema so without any further Ado let me create one database so here just right click create database okay here I will write music okay and save so now our database is created okay so if you will go to schema and if you go to tables there is no tables in it means there is no there is database but nothing is there the database is empty so now what I will do just go to your database just right click here you can see the restore option okay restore so format as it is then here file name go to this music store database I will put this database Link in the description box below don’t worry open then restore process started process complete some people will face this uh that the process is failed or something okay so for that what you have to do just go to file then preferences here you have to set the path just binary path okay see I am using the 15th version okay so I have set the path here also and this also but you have to set this path is important okay if you will not set this edv Advanced server path it’s fine but this part is most important okay but for the future reference I have added on the both what you have to do you have to just see where you will find this path just go to this PC then OS then program files here you will find this post G SQL then I’m using C5 15 then bin so you have to copy this path right you have to just copy it and paste it here and then select this one after that just save you won’t find any fail thing okay the process will complete right so now let’s move forward and see the tables okay it’s still empty while just refresh it see now you can see all the you know columns in my tables okay so what I will do for the checking I will run one query here okay let me close it okay I will write here select star from album okay let me run it so now as you can see here my table is working fine everything seems good okay so now what we will do we will solve question one by one okay so the first question let’s see the first question easy one who is the senior most employee based on job title okay who is the senior most okay so I will write here like the first question is who is the Senor most employee based on job title okay so this is our question so we know we have the table name called employer so we will select that table first so I will write here Select Staff from employee so you should know uh which table should to select okay so here as you can see in this question there is you know t uh word employee who is the senior most employee based on the job title most employee means means employees and employee table right so I will run it okay so what I will do I will just select this and run it okay so now you can see there in employer there is employee ID last name first name title report levels bu date higher date and all the details of the particular okay so we will do so there is one more thing you can see the levels okay level one level two so we have to who is the senior most employee based on the job title so what I will do I will write here order by levels and decreasing order okay so first I will do so now you can see the levels are in the descending order from senior to this okay L7 to L L1 so what we want we want only one uh employee name so what I will write here limit is one okay I will copy this and done it okay so now you can see the last name is Madan moan sorry moan Madan this is last name this is first name so Mohan Manan is the senior most employee based on the job de so question first is done so the second question is which countries have the most invoices okay first I will write down the question which country has the have the most have the most invoices okay so for this what we have to do see just first check first we have to check from which table you know we will get the solution so here you can see the word invoices Okay so we have one table invoice and invoice line we have to select it from this okay so I will write here Select Staff from invoice okay so we have customer ID invoice date billing address billing city billing State and everything so here you can see we have the billing country as well okay because we need the country name so we will take this column right so I will write here so I will write select we change it select count star from the select star billing country from invoice Group by billing country so why I’m doing this group by because as you can see uh we have USA multiple times USA USA USA then Canada also and the other countries as well so from this I will get only the one okay I will group them and I will get the one fine so from this we will uh get the count so after this I I will write order by so here I will write see see descending okay let me run it so now you can see the billing this is the billing order okay so or you can see the on voices USA got the 131 and Canada 76 Brazil 61 if I will write here again the limit one what I will get see USA we got the USA so us is the country which have the most invoices okay if you will remove this limit so you will get the other country as well second in Canada third is Brazil and like this okay and the third question is what are the top three values of total invoices okay again we need the same table okay first I will write the question third question is what are are the top three values of total invoices top three value of total invoices okay I know I can just solve this question by the second one but I want to do it from the starting okay so first I will take select stuff from invoice let me run it so first we will sort the data here I will write order by total because the last you know this is a table name okay total and the descending order so first I will select so we need just the top three so first I will do everyone know limit three okay okay so here I have done I have wrote this star that is why it’s giving me the all the values if I want this only this value so I can write select total from invoice order by this okay I will say and to run it so I have this total like 23.75 999 and 19.8 and 19.8 so these are the top three values of total invoices okay so here the fourth question is which city has the best customer we would like to throw a promotional music festival in the city we made the most money write a query that returns one city that has the highest sum of invoice Total return both the city name and some of the all invoice total so let me write the question first okay I’m writing question for you know your better understanding okay question fourth which city has the best customers we would like to throw a party uh promotional promotional music festival in the city we made the most money we made the most money write a query that it does one city that has the highest sum of invoices has sum of invoices total both the city name and sum of all invoices okay so we have this question okay so which city has the best customer we would like to throw a promotional music festival in the city we made the most money write a query that returns one city that has the highest sum of invoice Total return both the city name and the sum of all the invoices okay so first what we will do we will select select stuff from invoice okay sorry we select this okay so first we will select the billing city we have to focus on this and the total in this this two table we have to just focus on okay so here I will write some of total as invoice total comma billing city from invoice so this time we will do group by pilling City because we need the city names uh then I will addite order by invoice total and the descending order seems good select some total as invoice Total Building City from invoice building okay so let me select this so as you can see the highest billing city is parag Prague and the best customer is from the parag city okay so this city has the best customer obviously parag pragu or sorry for the you know mispronunciation okay so this is how we have solved our fourth question as well okay because WR both the city name and the sum of all the inv you know these is the city names and then inv voice total okay moving forward to our fifth question which is again the long one who is the best customer the customer who has spent the most money will be the declared the best customer write a query that Returns the person who has spent the most money okay so I will write here who is the best customer the customer who has spent
the most money will be declare the best customer so write a query right that returns that Returns the person who has spent most money okay yeah so who is the best customer the customer who has spent the most money will be declared as the best write a query that Returns the person who has spent the most money okay so for this we have to take this customer Data customer table data okay so I will write as select stuff from customer okay I will select this and I will run it okay so this is our know data table data of customer okay so we have the country facts emails state city address last name first name okay so as you can see there is nothing uh like no detail of invoice or the money okay which have spent by the customer so what we will do we will look at our schema so now what we can do if we can’t solve a particular question from with one table we have to you know join the table to the other table so here we have to join customer table to invoice table so in this you can see there is customer ID and here also customer ID so on the basis of customer ID we can join the join both the table and with the help of this total we will sort out the uh that guy okay that customer right so for this I will write here select customer Dot customer ID comma customer Dot first name comma customer dot last name because we need need the full name of that guy comma sum invoice do total as total okay okay let me can P okay I don’t need the search pad right then I will write from customer okay my bad then join invoice on customer Dot customer ID equ alss to invoice do customer ID then I need Group by okay Group by customer Dot customer ID after this uh uh let me order it by the descending order so the most you know spend customer will come up so I will write here order order by total the descending order then limit equals to one fine let me run it let’s see what output should okay okay some error is coming okay sorry okay so as you can see the customer ID is five first name is R the last name is m our m is spent the highest value 14454 0 and two so who is the best customer M our mad sorry my bad our ma right our mother has spent the most money okay so this is how we are done with our easy set of questions now let’s jump into the moderate one okay so let me write the question first for the moderate so I will write here moderate questions so these analytics skill help you in the data analytics to become a data analyst or to become a data scientist okay so the question first is write query to return okay write query to return the email qu to return the email comma first name first name comma last name and genre of all do music list okay then return your list ordered alphabetically by email starting with a okay let yeah so for this okay let me open this first yeah okay fine so first what I will do so now in this question as you can see we need the we have to return the email first name and the last name and the J of all rock music listeners so if you will see select stuff from customer okay let we run this and if I will see there is no column name genre okay if I will show you the schema of this see the genre is here and the customers is here okay we need the first name last name and the email ID and the genre okay and the genre is Will should be Rock okay so what I can do I can connect this genre with track that because here is also track ID and here is also track ID then track ID to invoice line then invoice line to invoice then invoice to customer with the customer ID okay this pattern I have to follow right so for this I will write select just copy this okay just follow the steps select distinct email comma first name comma last name from customer join invo voice on customer Dot customer ID equals to invoice do customer uncore ID then join invoice underscore line on invoice do invoice ID okay then invoice _ ID then where check ID should be in here I will do select track ID okay from track then join then join genre yeah on track dot genre dot ID equ to genre dot genre ID where this is important genre name like rock because we need as you can see right a quy to return this is this and genre of all rock music listeners okay rock right then order by email okay before that let me show you this track okay select star from track okay let me show you this table you can see the name the track ID album ID Media type genre ID okay then the composer this this this bites and the unit price right okay so you know this we have then this customer okay invoice ID we to right fine so now what I will do I will just select this and okay invoice ID okay inv voice it is ambiguous here I have to write invoice line do invoice ID okay let me now run let me run it okay one more join genre on track. genre ID there is entry for table genre but it cannot be referenced from this part of the query okay okay as you can see the have the table name is Jore ID that was the mistake okay one more JRA do name spelling mistake sorry my bad guys no shes it happens okay now you can see we have all the people who love rock music and we have the email then first name then the last name see Adan Mitchell Alexandra Roa a grber like this cam Dan Edward like this okay so there are total 59 people who loves rock music from this particular database okay now question two question two is let’s Okay first let me show you let’s invite the artists who have written the most rock music data set write a query that Returns the artist name and the total track count on the top 10 rock bands okay so let’s invite the artist who have written the most rock music in our data set so write write a query that Returns the art this name and and the total count of track count of top 10 rock band so now what we need here okay let me do this so what we need here so let’s invite the artists who have the written the most rock music first we need the artist okay and the second is rock music then we need track okay and the total count total track count means we will get from the track so here we have track column track uh table and we have the artist so now let’s see the schema part so we have we need genre okay for the you know uh rock music then we have to combine this with the track ID because JN R is there from track ID to album because we need the artist name see artist ID and artist ID so this is how we have to connect the table now so for this I will write here just follow the steps select artist dot artist ID comma artist dot name comma count artist. artist ID as number of songs because we need the total number okay who have written the most rock music number of songs find from track now we have to join album on on album do album ID equals to track dot album ID okay then we have to join the artist with artist ID so join artist column on the basis of artist AR equals to then album to album. artist ID okay so here I have joined the artist to the album colum table okay then I have to join johra to the track table with the track table okay so here I will write join genre on genre do genre ID equ to JRA ID okay sorry track ID track. J okay so here I will write where where genre dot name name like shock okay rock fine then I will Group by my B group by artist do artist ID I need the ID as well then order by order by number of songs the descending then limit I need only 10 rock bands limit will be 10 let me run it okay let me run it okay album okay now let me run it okay now you can see this guy let zeppin AR side is 22 and wrote the most songs 144 then U2 122 d purple 92 then then this this this then this okay so this is how we solved our second question right so now the third question okay return all the track names names that have a song Length longer than the average song Length return return the name and the millisecond of the each track order by the song Length okay so first I will write this question Q3 so return all the track names that have a song Length longer than the the average song length Okay as we return all the track names that have the song Length longer than the average song Length okay then return the name and milliseconds for each track fine after that order by them order by the songs with the longest s listed first okay fine so we have to return all the track names that have song length and the okay first we will find the total length of this songs then we will do the where then we will put the V Clause to find out the particular uh longest song okay so this is this we’ll do in the two you know step first you will find the average strike length Okay so I will write here select select name comma millisecond okay from track where milliseconds here I will write select average from the millisecond okay then I will write here as average track length Okay then here I will write from track after this I will write here order by milliseconds I need in the descending order okay so let me run it so now you can see see first I will uh read it again so return return all the track names that have a song Length longer than the average song Length return the name and the millisecond for each Strat order by the song with the longest song listed first okay so this is the longest song okay so we have all the songs which are the longer than the average song Length right so now moving forward we have jumped into the advanced set of questions okay so now we will do the advanced questions okay so let’s see first find how much amount spent by each customer on artist write a query to return customer name artist name and total spense okay so first we will write down the questions okay then question one question one okay find how much amount spent by each customer on art is just write a query to return customer name comma artist name comma total spend and total spent okay so how to solve this so first find which artist has earned the most according to the invoice lines okay first uh let me show you the schema okay we need the artist name we need the customer name and we need the total spend okay with the invoice line because the quantity should be there okay so first we’ll see how to join these three table artist table customer invoice and invoice line like this okay this is how we will you know join the table fine so now I will tell you the you know steps so first find which artist has earned the most according to the invoice line okay the second now use the artist to find which customer spend the most on the artist so for this query you will uh be need to use the invoice invoice line track customer album and the artist table so just remember this one is tricky because the total spent in the invoice table right let me show you so total spent on the invoice table might not be a single product so that is why I was saying we need the quantity so we need the invoice line table to find out how many each product was purchased then we have to multiply this by the price of each artist okay fine so now so this is the lengthy one I will just you know write it for you and get back to you yeah so this is how you can see okay Group by five I have wrote this you can just you know write it okay like this okay we took artist name then sum of invoice line unit price into invoice line the quantity that I showed you okay we have multiply this total with the quantity okay then we join the table track with invoice album with track artist with album okay so now let’s run it yeah so now you can see this H or queen amount spent 27 the customer ID is this okay then Nicholas scer then 18 okay we have the the everything okay customer name artist name and the total spend this is the customer Name the artist name and the total amount this spent fine so now let’s move forward to the next one which is okay okay yeah so the second one is this we want to find out the most popular music genre for each country we determine the most popular genre as the genre with the highest amount of purchase so write a query that returns each country along with the top genre for countries with the maximum number of purchases shared return all the genres okay so what I will do first I will write the question okay so we okay question two so find how the most popular music music genre for each country okay with the mine determine the most popular genre as the genre with the highest amount of purchase okay then write a query that returns each country along with the top genre for countries where the maximum number of purchase okay so so there are two parts in this question first the most popular music genre and the second is the need of data at the country level okay so we can do it from the two methods okay using CT and the using the recursive method so I will use the using City I will do this city so for that you have to write with popular genre as select count invoice line dot quantity okay as purchases comma customer dot country comma genre do name comma genre dot genre ID okay then here I will write row underscore number number then I will write over Partition by customer. country order by count voice line dot quantity okay into descending order as row number okay so from invoice line okay yeah so here I will join the tables join invoice on invoice do invoice ID equals to invoice line do invoice ID okay then again join customer on customer. customer ID do idore idals to invoice Dot customer ID fine then again we have to join track track on track. track ID equals to invoice uncore line Dot trackcore ID then join genre on genre. JRA ID okay then track do John Ry okay then I will do group by Group by 2 comma 3 comma 4 then I will do order by two then ascending order and then one to descending order okay okay then now I will write select star from popular genre where row number less than greater than one okay now let me run it so now you can see we have okay I will let me read so we have to find the most popular music genre for each country okay so now we have the Contin margentina the most popular is alternative and punk John R is this store number is this okay purchases this then the Australia this rock rock rock rock rock okay certain Rock USA Rock and everything is there right so this is how you can find the most popular music genre for each country okay the last question is the here now the last question is write a query that determines the customer that has spent the most on the music for each country write a query that Returns the country along Ong with the top customer and how much they spend okay for the countries where the top amount of spent is shared right and they provide all the customer who spend this amount okay so for this um this is like a similar to this question okay so there are two parts in this question find the most spent on music for each country and the second is the filter the data for the resp customer it’s very easy okay so okay I will write the solution okay you can check the question from there I’ll write customer with country as as uh I will here select customer do customer ID comma first name comma last name comma billing billing country comma sum should be total as total spending right then I will write zow number same over we have also written here now right the same we have to write here over then Partition by billing country order by by some total descending order as row number okay so after this I will write here from invoice you have to fetch then again the same thing we have to join the table join customer on customer Dot customer ID equals to invoice do customer ID okay then here I will write Group by by 1 comma 2 comma 3 comma 4 comma okay that’s it okay then I will write here order by four ASC ascending order comma five to descending order fine so now I will write here select start from customer with country where row number is one fine so let me run it see we have first name last name billing country total spting R number and the customer ID let me show you the question here write a query that determines okay let me make it okay yeah so write a query that determines the customer that has spent the most on the music so customer we have the customer name for each country write a query that result the country along with this so we have the country name with the top customer how much they spend we have the total spending for the countries where the top amount is shared provide all the customer who has customer who spent this amount okay so we have everything here right we have this Le from Brazil this this this this this okay with the customer so this is how you can solve these questions so till now I can say you have a good data analytics skills so for this I can say this will help you in the interview of data analyst in data science or any SQL okay picture this you are in the interview and the interviewer ask can you write a query to find the top five sales records you freeze for a moment thinking am I ready for this or not don’t worry SQL might sound complicated but it’s actually a super useful tool that lets you interact with databases have you ever wondered how all those apps and websites stores and organize their data well that’s where SQL comes in SQL which stands for structured query language is a universal language for talking to databases it’s super powerful and lets you do things like pull out specific information add new data update existing stuff or even delete things you don’t need it’s basically your magic key to manage huge amounts of information with ease exactly and if you’re aiming for a career in Tech whether it’s a database administrator data analyst or software developer SQL is a must-have skill databases are at the heart of almost every application so knowing SQL can unlock some really exciting opportunities now here’s the exciting part this video is your secret weapon to master SQL interviews we have packed it with 45 carefully chosen SQL interview questions that everything you need to raise those tough questions so we’ll be starting with the basics like how databases work and then diving into advanced query challenges and by the end you’ll be fully prepared to tackle any SQL question thrown at your way so let’s dive in and get you closer to your dream job so let’s get started so now let’s start with a SQL interview question we’ll cover every question starting from basic level to advanced level so now let’s look at our first question which is very basic what is SQL so we all know that SQL stands for structured query language and it is the language which is used talk to databases think of it like giving instructions to a computer system that stores and organizes data for example if you want to find out all the customers who ordered a specific product then SQL can help you do that with a simple command you can also use SQL to add new data like entering a new customer details into database if you want to update someone’s phone number SQL has got you covered or maybe you want to delete old records that are no longer needed SQL can handle that too here’s a quick example if you want to find all the customers in New York you could write something like select star from customers where city is equals to New York so we are using this command to find all the customers in New York remember if you want to find out all the specific data from the table you have to use the Star Command and if you want to add new customer you can just simply write in insert into customers name City and then you can also insert value name which is John or and you can just enter the specific location so SQL works the same way across many popular databases like my SQL post SQL or SQL Server which is why it’s such an important skill for anyone working with data so now let’s look at our second question which is what are the different types of SQL commands so SQL commands are like instructions you give it to a database to tell it what to do there are different types of commands and each one has a specific purpose so let me explain these in simple terms remember if an interviewer asks you such questions simply explain using the proper keywords and uh use proper definitions and you know easy language that’s it so the ddl command we have which stands for data definition language it basically defines the structure of the database for example if you want to create a table or if you want to alter a table or if you want to drop a table then we have DML which stands for data manipulation language it deals with the actual data in the database for example insert update delete all of these things then we have DCL which is data control language it will manage permissions and access control so if you want to manage permission or access control then you have to use this particular type of SQL command which is DCL which is Grant and Revo Grant will provide access rights and ROK is used to remove the access rights we also have TCL which stands for transaction control language it will manage transactions in the databases for example commit commit is used to save changes rback is used to undo changes and save point is used to create intermediate points in a transaction so for instance in a schema with customers table and an order table data definition language commands are used to Def find the table whereas data manipulation commands which is uh select insert and delete it is used to update customer or order data DCL is used to control access and TCL which is transaction control language is used to manage transactions that’s it it was very simple now let’s look at your third question which is what is a primary key in SQL a primary key in SQL is like a unique ID for each record in a table think of it as a way to ensure that no no two rows in a table have the same value remember that no two rows must have the same value it is also a rule that the primary key column can’t have empty or null value so these are the basic criteria for a key to be a primary key for example in a table of customers you have a column called customer ID as the primary key then each customer have a unique customer ID like 1 2 3 and so on this makes it easy to identify Y and retrieve specific customers from database here’s a simple example suppose we have created this table create table customers and we have given the customer ID as primary key we have given name as Vare the city name as well so the primary key will ensure that each customer ID is unique no duplicates are there no customer ID is left blank that is there should be no null values and primary keys are also important when linking tables together for example if you have orders table you can use the customer ID as a reference to connect each order to a specific customer this help maintain data Integrity across the databases now the fourth question is what is a foreign key a foreign key in SQL is like a connection or link between two tables it’s just like a field in one table that refers to the primary key in another table this creates a relationship between the tables and ensures that the data stays consistent for example let’s suppose you have two tables a customer table with a primary key called customer ID and a sales table with a field called customer ID which is a foreign key linking back to the customer ID in the customer table so here’s how it will look like we have created this table and you can see in this example that suppose we have customers and sales table so we have used this customer ID in our customer table as well so here customer ID is the foreign key and in the customer table the customer ID which we had used is the primary key so now let’s move on to our fifth question which is delete and trunk it command what is the difference between delete and truncate commands so delete and truncate commands in SQL both remove the data from a table but then they work in different ways let me break it down for you the delete command so what delete command will do is basically this is used when you want to remove specific rows from a table based on a condition for example if you want to delete all all the customers from a specific City then you have to use this delete command it will allow you to be selective but it’s slower because it logs each row deletion which also makes it possible to roll back the changes if needed if you’re using transactions moving on to trunade command trunk gate will remove all the rows from a table at once without allowing any condition for example if you just want to remove all the rows just in a one go you have to use this truncate command just simp write this query as trunk table suppose the table name is customers is much faster because it doesn’t log individual road deletions and it simply clears the entire table in one go however you can’t roll back a trunk operation in most databases once it’s done so the key differences is delete is for specific row trunk it is for clearing the entire table trunk it is much more faster because it uses fewer system resources delete can be rolled back if used within a transaction trunade usually cannot delete logs each rout deletion and trunade doesn’t so this was all for this trunade and delete commands so anytime if the interviewer asks you such questions just simply explain this now let’s move on to the sixth question which is what is a joint in SQL and what are its types so this is one of the most important question you’ll be getting to know in the interviews you’ll be asked such questions in the interviews so basically a chin and SQL is used to combine a data from two or more tables based on related column like a column key that links them together it’s just like connecting pieces of puzzles join help you see the bigger picture by merging related data for example if you have a customer table and a sales table you can use the join to see which customer placed which order by linking them through a common column such as the customer ID so you all know what a join and SQL and let’s discuss its type so joint types are basically there are four types of joint which is inner joint left joint right joint and full outer joint as well so what inner joint will do is it will combine rows from both tables where there is a match in the common column think of it as the overlapping section in the v diagram only rows that exist in both the tables are included the left join or we can call or the left outer joint it will retrieve all the rows from the left table and the matching rows from the right table remember the left joint will retrieve all the rows from the left table and only the matching rows from the right table if there’s no match the result includes null values for the right tables column think of it as including the entire left Circle in the vent diagram along with any matches in the right Circle right join or the right outer joint is similar to the left joint but it will retrieve all the rows from the right table and matching rows from the left table if there’s no match null values are included for the left table column think of it as including the entire right Circle in the vend diagram along with any matches on the left Circle then we have the full joint full joint will combine rows when there’s a match in the either table if no match is found it includes null or the missing values from the either table think of it as combining both circles in the v diagram everything from both tables are included now let’s move on to the seventh question which is what do you mean by a null value in SQL it’s very easy null value in SQL means that a column has no data it’s missing or unknown it’s not the same as an empty string or the number zero those represent actual value while null represent no value at all for example if you have a table of customers and one of the row doesn’t have a phone number then the phone number column for that row would be none see we have listed this in the table here you can see if you do not have any data just simply write none so the next question is Define a unique key in SQL so unique key in SQL ensures that all values in a column or a combination of columns are unique that is no duplicates are allowed it’s like a having a rule to make sure that no two rows in a table must have the same value in that column for example in a user table the email column can have a unique key to ensure that MO two users can register with the same email address remember the key points unlike a primary key a table can have more than one unique key unique Keys allow null values while primary keys do not so these are very important to remember so if you’re ask a difference between a primary key and a unique key just simply say that unlike primary key a table can have more than one unique key and unique key allows null values while primary key doesn’t so here is a table we have listed below that is create table users and we have given user ID as integer primary key and then we have email Vare as a unique key so here the email column is a unique key so that each email must be different it should not be the same now let’s look at our next question which is what is the database a database is organized way to store and manage data think of it like a digital filling cabinet where information is Neely arranged in tables with rows and column each row represents a record and each each column represents a specific detail about that record for example a database for a library must have a table for books then the rows could represent individual books and the columns could include the book title author and the publication year the main purpose of a database is to make it easy to store manage and quickly retrieve data whenever you need it databases are used in everything from apps and websites to banking system and e-commerce platform now let’s look at our question number 10 which is explain the differences between SQL and no SQL databases so here’s a simple explanation SQL databases are structured which means they can store in tables with rows and column like a spreadsheet they follow predefined schema meaning the structure of a data is fixed and you need to Define it before adding any data these databases are great when you need consistent and reliable data like for banking system or inventory management examples are MySQL Oracle Ms SQL post SQL Etc and SQL databases are also known as rdbms which is relational database management system let’s talk about nosql databases so nosql databases are flexible and do not use stable instead they can handle unstructured or semi structured data so no SQL database is dynamic where data is primarily stored in Json objects key value pair graph nodes Etc they don’t have a specific ific structure the such databases are mostly not preferred for performing complex query operations and the examples include mongod DB couch DB elastic search Etc so now let’s move on to question number 11 which is what is a table and a field in a SQL so a table is like a spreadsheet that stores data in organized way using rows and columns each table contains records and the details for example a table name employees could store information about employees in a company whereas a field is a column in a table and it represents a specific attribute or property of the data for example in the employees table Fields could be employee ID name and department so here’s a simple example of the table you can see here the fields name or we can say column and we also have the records or the rows we can see that so in this table the entire table is called employee each row or record stores information about one employee and each column of field represents specific details like employee ID name and the department now let’s move on to a question number 12 which is describe the select statement well the select statement in SQL is used to retrieve data from a table or multiple tables it’s like asking databases show me this specific information here’s how it works you can specify which columns you can see for example to retrieve all customer names from a customer table you can select name from customer if you want to retrieve all the data just write this query select star from customers remember I told you before in the first question we using start if you want to retrieve all the data from the table and if you want to just retrieve from a particular row or a column just simply write select name from customers the field name you can also apply filters you can use a wear Clause to filter the results for example you can write select name from customers where the city name is New York you can also sort the results use the order by to sort the data for instance to sort customers by the name you can just write select name from customers and then order by name ASC ASC means ascending order so in short the select statement lets you choose what data you want to see now let’s talk about what is a constant in SQL and name a few so if you ask this question just simply answer a constant in SQL is a rule applied to a table that ensures the data stored is accurate and consistent it also help in maintaining data Integrity by restricting what values can be added or modified in a table here are some common constraints primary key we have foreign key then we also have unique key check not null and default so we have already discussed about primary key it ensures that each row in a table has a unique identifier and the column can’t contain null values foreign key links to a column in one table to a primary key in another table to maintain relationship unique key ensures all the value in a column are distinct that is there are no duplicates the check ensures that data meets a specific condition before being inserted or updated not null ensures that a column cannot have null values the constraints are essential for maintaining reliable and valid data in your database now let’s talk about what is normalization in SQL normal I ization in SQL is a process which is used to organize data in a database to make it more efficient and reliable the goal is to reduce R deny which is duplicate data and Ure data consistency this is done by splitting a large table into smaller related tables and then linking them using relationship like primary and foreign key for example imagine a single table that stores customer details and the orders if the same customer places multiple orders then their information like name and address would be repeated for each order now using normalization you would separate this into two tables first we would have customer table which will store customer details like customer ID name and the address and then we have order table which will store order details like order ID customer ID and the order table now by linking these tables using customer ID you can also reduce duplication and ensure that any changes to customer details are updated in just one place now let’s talk about question number 15 which is how do you use the wear Clause it’s very easy so just answer the we Clause within SQL queries serves the purpose of selectively filtering rows according to a specified condition thereby enabling you to fetch exclusive those rows that align with the criteria you define for example select star from employees where department is equals to HR now let’s move on to question number 17 which is difference between Union and Union or so Union is used to merge the contents of two structurally compatible table into a single combined table the difference between union and Union all is that Union will omit duplicate records whereas Union all will include duplicate records very easy Union will omit duplicate records and Union all will include duplicate records the performance of Union all will typically be better than Union since Union requires the server to do the additional work of removing any duplicates so in cases where is certain that there are not any duplicates or we having duplicates is not a problem then we can use Union all it would be recommended for performance so now let’s move on to the question number 18 so here a table is given below and you will have to see what will be the result of a query the query is Select star from Runners where ID not in select winner ID from races so the answer is given the simp data provided the result of this query will be an empty set so the reason for this is as follows if the set is being evaluated by the SQL not in condition contains any value that are null then the outer query here will return an empty set even if there are many Runner IDs that match winner IDs in the races table question number 19 is what are indexes in SQL indexes in SQL are just like having a shortcut to quickly find data in a table instead of searching through every Row one by one an index creates a sorted structure based on one or more columns making data retrieval much more easier for example you can think of an index in a book if you’re looking for a specific topic you can go to the index at the back and find the page number in stad flipping through every page similarly in database an index help the system quickly locate the rows you need so here’s how it works if you often search for customers by the name created an index will speed up those queries you can just write create index idx customer name on customer and then the customer name the database uses the index to find the row so you just have to run a query which is Select star from customers where name is John and then you can use the index to find a row with name is equals to John much faster let’s move on to question number 20 which is explain Group by in SQL the group by clause in SQL Will Group rows with the same values in a column allowing you to apply functions like sum count or average to each group for example in a sales table to find total sales by region you just simply have to write this query which is Select region some amount as total sales from Sales Group by region so the group the sales by region and calculates the total for each it’s a quick way to summarize data by categories so now let’s talk about question number 21 which is what is SQL Alias a SQL Alias is a temporary name you can give it to a table or a column in a query to make it easy to read or work with it’s like giving a nickname to something for clarity for example if you have a column named first name you can use an alias to rename it as first name in the query results you just simply have to write this query as select first name as first name in capital letter last name as last name from employe here the as keyword assign the Alias and the output will show The Columns as first name and last name aliases are also useful for tables so for this you can just write the code AS select e first name from Department table so this shortens table name for easier referencing alyses are not permanent they only exist while the query is running now let’s talk about the question number 22 which is explain orderby in SQL so you can answer this question like the order by clause in SQL is used to sort the result set of a query based on one or more columns you can specify each column sorting order ascending or descending for ascending you have to use ASC and for descending you have to use the ESC okay so just have to Simply write this query as select star from product order by Price DEC now let’s talk about question number 23 which is differences between where and having in SQL the where Clause is employed to restrict individual rows before they are grouped such as when filtering rows prior to a group by operation conversely the having Clause is utilized to filter groups of rows after they have been grouped like filtering groups based on aggregate values the having Clause it cannot be used without the group Clause whereas the where Clause specifies the criteria which individual records must mean the selected query it can be used with the group by Clause question number 24 is what is view in sec one more important question so and SQL view is essentially a virtual table that will derive its data from the outcome of a select query view serve multiple purposes including simplifying intricate queries enhancing data security through an added layer and enabling the presentation of targeted data subsets to users all while keeping the underlying table structur hidden now let’s move on to question number 25 which is what is a store procedure so if you asked this question just simply say a sequel stored procedure comprises of prec compiled SQL statements that can be executed together as a unified entity these procedures are commonly used to encapsulate business logic improve performance and also ensure consistent data manipulation practices that’s it now let’s move on to question number 26 which is one more important question which is what what is triggers in SQL a SQL trigger consists of a predefined sequence of actions that are executed automatically when a particular event occurs such as when an insert or delete operation is performed on a table triggers are employed to ensure data consistency conduct auditing and streamline various tasks so you can use insert trigger update Trigger or delete trigger accordingly now let’s talk about what are the aggregate functions and if you know them name a few it’s very easy to answer aggregate function and SQL perform calculations on a set of values and return a single result at first we have minimum which will get the minimum value from the resultant set then we have the max function which will give you the maximum value from the resultant set the sum will give you the sum of values from the resultant set average will give you the simple average of the resultant set and the count will count of numbers records from the resultant set now let’s talk about question number 28 which is how do you update a value in SQL the update statement serves the purpose of altering pre-existing records within a table it involves specifying the target from the update the specific columns to be modified and the desired new values to be applied for example if you want to update you can use Query like update employees set salary is equals to 6,000 where the department is ID now we’ll be moving on to some intermediate mediate SQL interview question and answers so one of the question is what is a self join and how would you use it I would like to repeat again these join types of question is very important these are often asked in interviews so talking about what is a self joint a self join and squ is a type of join where a table is joined with itself it’s useful for comparing rows with the same table or exploring hierarchal relationship such as finding employees and the managers in an organization so imagine if you have an employee table so you have employee ID name and the manager ID so if you want to find each employee and the manager you can use a self jooin you can just simply write a query as select e name as employee M name as manager from employee left join employees on manager so I’ve already discussed with you before what is the meaning of Left Right and self jooin so here the table joined with itself using manager ID to link each employee to the manager a self joint is helpful for comparing rows in the same table or working with hierarchial data so now let’s move on to question number 30 which is explain different types of joints with example at first we have inner joint the inner joint will gather rows that have matching values in both the tables then we have the right joint it will gather all the rows from the right table and any matching rows from the left table left join will gather all the rows from the left table and any matching rows from the right table and the full joint will gather all rows where there’s a match in either table including unmatched rows from both the tables very easy now let’s move on to question number 31 which is what is subquery and provide it using an example so subquery basically refers to a query that is embedded within another query serving the purpose of fetching information that will subsequently be employed as a condition or value within the encompassing out a query so you can just use this uh query which is Select name from employees where salary is greater than select average from salary from employees now the next question is how do you optimize SQL queries so basically the answer to this question would be something like SQL query optimization involves improving the performance of SQL queries by reducing resource usage and execution time strategies include using appropriate indexes optimizing very structured and avoiding cost operations like fully table scans now let’s talk about question number 33 which is what are correlated subqueries it’s a type of subquery that makes reference to columns from the surrounding outer query this subquery is executed repeatedly once for each row being processed by the outer query and its execution depends on the outcomes of the outer query now we’ll be talking about what is a transaction in SQL and it’s very important one of the most important question asked every time in SQL interview questions so basically a transaction in SQL is a group of one or more SQL commands that are treated as a single unit it ensures that all the operations in the group either succeed completely or fail entirely this guarantees the Integrity of the database imagine you’re transferring money from your bank account to a friend’s account that the bank first deducts the amount from your account account and then it adds the same amount to your friend’s account these two steps together form a transaction if one of these steps fails example the system crashes after deducting money from your account but before adding it to your friend’s account then the entire transaction is rolled back meaning no money is transferred and the database returns to its original state so you can also explain this question with the help of example that would be more you know clear to the interviewer now let’s talk about what are asset properties in SQL so basically asset stands for atomicity consistency isolation and durability and these are Key properties that ensures database transactions are reliable and maintain data Integrity atomicity you can think of it as All or Nothing a transaction is a single unit of work if any part of the transaction fails then the entire transaction is rolled back and no changes are made to the database for example if you’re transferring money between two accounts either both the debit and credit operations happen or neither does the second we’re going to talk about is consistency the database must always be in valid State a transaction takes the database from one valid state to another following all the rules and constraints for example if a transaction adds a record that violates a rule like a duplicate primary key then the transaction fails key keeping the database consistent isolation transactions don’t interfere with each other even if multiple transactions are running at the same time each transaction works as if it’s the only one happening example if you two people are updating the same record then one transaction will wait until the other is complete talking about durability once a transaction is committed it’s permanent even if there’s a power outage or system failure the data is saved and it won’t be lost after you complete an online purchase the transaction is stored securely even if the server crashes immediately after so this was for the asset properties and now we’ll be moving on to our next question which is how to you implement error handling in SQL error handling in SQL is a process to manage and respond to errors that occur during query execution different database system have specific ways to handle errors in SQL server the TR catch block is commonly used the tri block contains the main operation while the catch block handles errors if they occur for instance in a transaction you can use roll back in a catch block to undo changes if something goes wrong similarly in Oracle the exception block within PL SQL is used to handle errors if an error arises the exception block executes rolling back the transaction and the logging the error message by implementing error handling you ensure that operations fail gracefully without corrupting data making the database operations more reliable and secure next question which is describe the data types in SQL SQL supports various types of data types which Define the kind of data a column can hold these are broadly categorized into numeric character data type and binary types so we have numeric data types like integer float then we have character string like Car Bar we also have uni code character string like N N Text then we have binary which includes binary image date and time which includes date and date and time then we also have some miscellaneous data types which is XML and Json so the next question is explain normalization and denormalization often this question is asked in this way also or it could be asked something like explain the difference between normalization and denormalization so to answer this you have to just simply explain what normalization is which I have already discussed before once again I’m seeing you normalization and denormalization are ways to organize data in a database normalization is all about breaking big tables into smaller ones to remove duplicate data and improve accuracy for example instead of repeating customer details in every order you create one table for customers and another for orders linking them with a key denormalization on the other hand is when you combine or duplicate data to make it faster and retrieve for instance you might add customer details directly to the c table so that you don’t need to join tables during a query normalization help you space and maintain consistency while denormalization makes data retrieval quicker depending on what the database needs let’s move on to a next question which is what is a clustered index it’s very easy just simply answer by saying that a cluster index in SQL determines the phys physical order of the data rows in a table each table can have only one clustered index which impacts the table storage structure rows in a table are physically stored in the same order as the clustered index key now we have next question which is how do you prevent SQL injection so talking about this question SQL injection is a security risk where attackers insert harmful code into SQL queries potentially accessing or tampering it with your database to prevent this you can use parameterized queries or repair statements to handle the user input safely you can validate inputs to allow only expected values used store procedures to separate logic from data limit database permission non Escape special characters these steps help you secure that your database is free from SQL injection attacks the next question on the list is explain the concept of database schema in SQL a database schema functions as a conceptual container for housing various database elements such as tables views indexes and procedures its primary purpose is facilitate the organization and segregation of these databases elements while specifying their structure and interconnections next question is how we data Integrity insured in SQL just simply answer by saying that data Integrity in SQL is ensured through various means including constants example primary Keys foreign Keys check constants normalization trans actions and referential integrity constants as well these mechanism prevent invalid or inconsistent data from being stored in the database question number 42 which is what is an SQL injection we have already discussed about how we can protect our data from SQL injections so now let’s discuss what is basically a SQL injection so SQL injection in cyber security attack that involves insertion of malous SQL code into applications in input fields or parameters this unauthorized action enables attackers to illicitly access a database extract confidential information or manipulate the data the next question is how do we create a stored procedure you use the create procedure statement to create a stor procedure in SQL a stor procedure can contain SQL statements parameters and variables so here’s a very simple example you can just simply create by writing this query as create procedure get employ by ID add employee ID integer as begin select star from employees where employee ID is equals to add employee ID and then you have just have to write end that’s it so next question is what is a deadlock in SQL and how it can be prevented one more important question often asked an interview so you have to answer something by saying that a deadlock in SQL happens when two or more transactions are stuck because they are waiting for each other to release resources it’s just like two people trying to go through a narrow door at the same time each refusing to step back and let the other pass transaction a locks table one and weights to access table two transaction B locks table two and weights to access table one this is just a simple example so we can see that both the transactions are waiting for each other neither can proceed creating a deadlock so it’s very simple and how we can prevent this deadlock is by locking hierarchies always access resources in the same order so that transactions don’t block each other timeouts set a time limit for transaction to wait out for the resources you can also use deadlock detection and resolution system to detect Deadlocks and cancel one transaction and let the other proceed now let’s move on to a last question on the list which is difference between in and exist in basically works on list result set it doesn’t work on subqueries creating a virtual table with multiple columns Compares every value in the result list performance is comparatively slow of a large result set of subquery whereas the exist works on Virtual tables it is used with correlated queries exist comparison when matches found and the performance is comparatively fast for larger result set of subquery so guys that’s it for this video on the top 45 SQL interview question asked in SQL interviews ever wondered how seems to know exactly what you want before you do that’s the magic of data analytics imagine you’re shopping for a camera and suddenly Amazon suggests the perfect lens tripod and memory card all before you even think of them it’s not magic but the power of analyzing massive data sets to track what millions of Shoppers like you search for and buy together this helps Amazon create a personalized shopping experience that boosts sales and keeps your coming back from predicting Trends to fine-tuning their stock Talk data analyis is a secret Source behind their seamless shopping experience hey everyone welcome back to Simply n’s YouTube channel today we have got an exciting topic lined up the top 10 data analytics certifications I will be walking you through the expanding scope and financial growth of data analytics worldwide why pursuing a data analytic certification is essential and finally the top 10 data analytics certifications that can supercharge your carrier that can open doors to exciting opportunities let’s Dive In and explore the world of data analytics together now let us explore the expanding scope and the financial growth of data analytics the scope of data analytics is worst promising Financial growth and Rising salaries for data analytics scientists and Engineers as Industries digitalize demand surges and finance for fraud detection healthc care for predictive diagnosis retail for personalized marketing and Manufacturing for productive maintenance Innovations like augmented analytics and realtime processing enhances importance companies like Google Amazon Microsoft and IBM consistently higher analytics experts in India entry level salaries range from 4 to six lakhs with perom with experienced professionals earning 10 to 20 lakhs perom in USA entry level salaries are1 60,000 to1 80,000 with experience roles at do$ 100,000 to1 15,000 plus the future promises greater advancements making data analytics a lucrative field with work potential now let us see why is pursuing a data analytics certification essential pursuing a data analytics certification is crucial as it validates your expertise boost your credibility and lights up your resume in a competitive job market certifications provide you with in demand skills like data visualization statistical analysis and machine learning keeping you current with the industry Trends they can lead you to paying high paying job roles and career growth as employers favor certified Professionals for job data driven positions whether you’re starting or advancing your career or certification showcases your commitments and skills enhancing job prospects in fields like Finance Healthcare retail and Tech as well so all right guys the moment you have been waiting for is here it’s time to reveal the top data analytics certifications by simply learn buckle up and let’s dive into this carrier boosting programs that will set you on the path of success coming to the number one that is a post-graduate program in data analytics boost your career with simply Lars postgraduate program ineda analytics offered in partnership with bir University and in collaboration with IBM this comprehensive 8mon live online course is perfect for professionals from any background and covers crucial skills like data analysis visualization and supervised learning using python R SQL and powerbi the program features master classes by Purdue faculty and IBM experts Hands-On projects with real world data sets from Google Play Store lift and more and exclusive hackathons and AMA sessions receive joint certifications from Padu and simply learn IBM recognized certificates and benefit from carrier Support Services like resum building and job assistance through simply learns job assist no prior experience required just a bachelor’s degree with at least 50% marks is required enroll now to gain industry relevant experience and stand out to the top employers like Google and Amazon to check for the coast Link in the description box and pin comments below now moving on to the number two that is calch postgraduate progr in data science Advance your career with simply learns postgraduate program in data science in collaboration with calch ctme and IBM this comprehensive 11 month live online course covers essential skills and tools including python machine learning data visualization generative AI promt engineering chat juty and more with master classes by Caltech instructors and IBM experts you will G hands-on experience to 25 plus industy Rel projects Capstone projects across three romens and seamless access to integrated Labs on a tees program completion certificate and up to 14 counting education units from CTIC ctme along with the NY recognized IBM certificates enhance your career with job assistance master classes and exclusive hackathons with no prior work experience required this program is suitable for professionals from any background who hold a bachelor’s degree enroll now to become a data science expert and stand out to top employers to check for the course Link in the description box below and pin comments now moving on to the number third that is professional certificate programming data analytics and generative Advance your career with professional certificate program in data analytics and generative AI by simply learn in collaboration with E and ICT Academy IIT goti and IBM this comprehensive 11mon live online program is designed to equip you with cutting a skills in data analytics and generative AI covering essential tools like SQL Excel python W power VI and more learn from distinguished I faculty and IBM experts through interactive master classes Hands-On projects and Capstone experiences gain practical expertise with exposure to jni tools such as chaty and Gemini and earn industry recognized certifications from IVM along with the executive alumni status from I goti enhance your Professional Profile with simply learn job assess resume building and job placement support to get noticed by the top hiring companies enroll now to elevate your career and join network of Industry leaders do check for the co Link in the description box below and pin comments moving on to the number four that is professional certificate course in D s Master data science with a professional certificate course in data science by simply learn in collaboration with ICT Academy I kpur this comprehensive 11 month live online program equips with essential skills and tools such as python power BW chat jity and more benefit from the master classes delivered by distinguished IIT kpur faculty gain practical experience with 25 plus Hands-On projects and access integrated La for real world training with dedicated modules on generative AI prompt engineering and explainable AI you will stay ahead in the rapidly evolving AI landscape ear a prestigious program completion certificate from E and ICT Academy IIT kpur and take advantage of Simply Lars job asset to enhance your Professional Profile and stand out to recruiters apply now to enhance your career in data science and AI do check for the course Link in the description box below and pin comments now moving on to the fifth one that is the postgraduate program in data science supercharge your career with the postgraduate program in data science by simply learn in collaboration with bird University and IBM ranked as the number one data science program by Economic Times this 11 month live online program equips with with the in demand skills including python machine learning deep learning NLP data visualization generative Ai and chargeability benefit from the master classes led by Purdue faculty and IBM experts engageing Hands-On training with 25 plus projects and free Capstone projects and gain access to Industry leading tools such as T flow carers powerbi and more earn dual certificates from perue University online and IBM boosting your Professional Profile and carrier prospects the simply learns job assess receive guidance and resume support to stand out to the top employers applications close on November 8 2024 and enroll now to transform your career in data science and AI to check for the course Link in the description box below and pin comments now moving on to the sixth one that is applied Ai and data science Advance your career with applied Ai and data science program offered by Brown University’s School of Professional studies and collaboration with simply learn this 14 week CPL program empowers you with essential skills in AI generative Ai and data science including handson learning and Industry Rel projects learn from Steam Brown faculty through top not video content and monthly live master classes covering tools and Concepts such as python machine learning neural lent walking and jpt models benefit from a curriculum design to refine your expertise supported by integrated labs and exclusive content on generative AI andn a prestigious certificate of completion from Brown University and a credly badge upon program completion enhance your profile with simply L job asset resumee building support and exclusive I IM job membership to stand out in today’s competitive job market enroll now to gain The Cutting age knowledge and take your carrier in Ai and data science to the next level do check for the course Link in the description box below and pin comments now moving on to the next that is the data analyst elevate your career with simplys data analyst certification rank number one by carrier Karma this comprehensive 11 month program is designed to transform you into a data analytic expert with practical training and SQL R python data visualization and predictive analystics learn through live interactive classes Capstone projects and 20 plus Hands-On projects that ensure Real World Experience G industry recognized certifications from Simply learn and IBM access exclusive master classes and am sessions by IBM experts and receive dedicated job assistance to help you stand out to the top employers like Amazon Microsoft and Google start your journey to becoming a data analytics professional today with simply learns trusted and robust training program to check for the course Link in the description box below and pin comments now moving on to the next one that is data scientist Advance your career with simply learns industry leading data scientist certification program now ranked number one by carer Karma this 11 month course in collaboration with IBM equips you with the essential data science skills including python SQL machine learning generative Ai and W gain practical Real World experience to 25 plus Hands-On projects and a Capstone project benefit from master classes by IBM experts interactive live sessions led by industry professionals and lifetime access to the self placed learning content simply lears job assess program further boost your carer prospects helping you stand out to thep employers like Amazon Microsoft and Google to check for the course Link in the description box below and pin comments now moving on to the second last one that is the professional certificate program in data engineering launch your data engineering career with simply launch professional certificate program in data engineering offered in partnership with P University online this 32e program accuses with the indman skills covering python SQL nosql Big Data AWS Azure and snowflake fundamentals aligned with industry recognized certifications like AWS certified data engineer Microsoft 203 and snow Pro core this course ensures comprehensive learning through live online classes practical projects and a Capstone experience gain access to puru Alumni Association exclusive master classes and simplys job asset for carer support join now to become a certified data engineer and FASTT trck eradio to high impact roles in the field do check for the course Link in the description box below and pin comments now moving on to the last but not Le is Microsoft certified as your data engineer associate dp23 Advanced your carer will simply learns Microsoft certified Azure data engineer associate dp23 training aligned with official certification Master essential Azure skills like data integration transformation and storage while gaining hands-on experience with the key services such as Azure signups analytics data Factory and Azure data braas benefit from live online classes led by Microsoft certified trainers access to official Microsoft handbooks practice lab and comprehensive practice test to help you excellent dp23 exam this course designed for real world application ensures you develop job ready skills and earn a official course completion batch hosted on the Microsoft learn portal enroll now to elevate your data engineering expertise do check for the course Link in the description box below and pin comments so getting a data analytic certification can be a game changer for your growth however choosing the right certification is crucial it’s like finding the perfect key to unlock your potential select the one that best aligns with your career goals and S SK to maximize your journey in data analytics so that’s a WRA so that concludes our SQL full course if you have any doubts or question you can ask them in the comment section below our team of experts will reply you as soon as possible thank you and keep learning with simply staying ahead in your career requires continuous learning and upscaling whether you’re a student aiming to learn today’s top skills or a working professional looking to advance your career we’ve got you covered explore our impressive catalog of certification programs in cuttingedge domains including data science cloud computing cyber security AI machine learning or digital marketing designed in collaboration with leading universities and top corporations and delivered by industry experts choose any of our programs and set yourself on the path to Career Success click the link in the description to know more hi there if you like this video subscribe to the simply learn YouTube channel and click here to watch similar videos to nerd up and get certified click here

By Amjad Izhar
Contact: amjad.izhar@gmail.com
https://amjadizhar.blog
Affiliate Disclosure: This blog may contain affiliate links, which means I may earn a small commission if you click on the link and make a purchase. This comes at no additional cost to you. I only recommend products or services that I believe will add value to my readers. Your support helps keep this blog running and allows me to continue providing you with quality content. Thank you for your support!

Leave a comment