📱

Get Our Mobile App

Take your business learning on the go!

Download on the App StoreGet it on Google Play

SQL Full Course In 10 Hours | SQL Tutorial | Complete SQL Course For Beginners | Edureka

edureka!9:59:23

Transcription

[Music] Did you know SQL is a high-demand technical skill? Due to its data analysis capabilities for businesses in a wide range of areas, robust and easy to learn SQL is requested by many job profiles since it goes hand in hand with technologies. Indeed.com, one of the largest employment portals, examined over 32,000+ data job listings and discovered that SQL is listed in 42.7 percent of them, making it a current most in-demand technical talent for potential employees.

Hello everyone, and welcome to this session. We are currently watching an edureka SQL full course video. By the end of this video, you will have a thorough understanding of SQL, all the way from theory to practical application that will help you master it. If you love watching videos like these, then subscribe to edureka's YouTube channel and click the Bell button to never miss out on any updates from us. Also, if you want to learn more about SQL after watching the session and wish to obtain edureka's SQL training and certification course, please see the link in the description below. Now let's begin with our agenda, where we'll have a brief overview of what we'll cover in this SQL full course video. We'll start by seeing what is SQL. Next, we have SQL Basics, followed by SQL operators. Now is the time to study deeply into SQL's technical components. We'll start with understanding what is normalization and triggers in SQL. Now, once this is done, we'll understand what are joins and functions in SQL. We will then compare SQL to MySQL and subsequently SQL to NoSQL. We hope that the session assists you in getting jobs in the industry. In order to accomplish this, we will look at how a career in SQL works, followed by some essential SQL interview questions. Now, after all this, we'll head over to how SQL is required in data science, followed by PostgreSQL and SQL Server. At last, we'll look at some SQL Server interview questions with answers. Please take till the end. Now let's start with our first topic, that is what is SQL.

[Music] The first topic is the traditional file system. In today's computing world, managing data is a huge task. For our convenience, we store the data and documents in different locations, and this is called a file system. Without a file system, information placed in the storage medium would be one large body of data; we won't be able to tell where information stops and where it begins. Let's look at the formal definition: a file system is one which controls how the data is stored and retrieved. It is nothing but information stored in different computer files. Usually, while storing a small amount of data, the file system is effective, but when it comes to storing an enormous amount of data, the file system fails. Let's look at some of the problems of the file system. The first problem is data redundancy. When we store similar data in different locations of a computer, data gets duplicated, and this will lead to data redundancy. This will increase the storage size and also leads to the failure of security features. Because of this, the file system is highly vulnerable in nature. Data redundancy will cost a user not only in terms of security but also economically. The second problem is limited data sharing and lack of security. Data sharing and security are closely related. Sharing data among multiple users introduces a lot of security risk in terms of spreadsheet data and other documents. The inbuilt file system programs provide only the basic security options, but they are not used most of the time. Because of this negligence, we might face some bigger problems in the near future. The third problem is the difficulty of getting quick answers. This is one of the major problems in the file system because the file system doesn't allow multiple users to access the same data at a given point in time. This means that multiple users at different work locations cannot access the same data simultaneously. This will limit the access to important data if multiple users search for the same data at a given point in time. The next problem is data dependence. In the file system, files and records are described by a specific physical format that is coded into the application by the programmers. If the format of any one record was changed, then we need to make sure that all the remaining records' format is updated. This information has to be updated in the system also. Any changes in storage structure or access methods could greatly affect the process. This might result in the failure of that particular application. So these were a few problems that were faced using the file system, and the solution for this is SQL and database. Let's now look at the evolution of SQL. SQL was developed at IBM by Donald D. Chamberlain and Raymond F. Boys in the early 1970s. It was initially called SEQUEL, that is Structured English Query Language, but later it was changed to SQL because SQL was a trademark of a UK-based engineering company. In the year 1986, the American National Standards Institute (ANSI) and the International Standards Organization (ISO) have deemed the SQL language as a standard language in relational database communication. This is how SQL evolved. Since we have understood the evolution of SQL, let's head to the next topic, that is what is SQL. People from technical backgrounds may find this silly, but for a beginner, it is really important to understand each and every aspect of this topic. The main focus of this entire session will be on this part, so now let's understand what is SQL. SQL is an abbreviation for Structured Query Language, which also goes by the name SQL even today. It's a language used by the database domain. SQL can be used only for relational-type databases and not for others. A relational database is a database which has the tabular method of storing data. Usually, it consists of rows and columns. Let's now see what SQL can do. SQL is a core of a relational database which is used for accessing and managing the database. With the help of SQL statements, you can add columns, update or delete rows of data. We can also retrieve information, modify the database, and perform many more actions. The different subsets of SQL commands are as follows: DDL, that is Data Definition Language. It simply deals with the description of the database schema and is used to create and modify the structure of database objects in the database. It allows you to perform various operations on the database such as create, alter, and delete objects. DDL is very popular and extensively used when compared to other commands. Moving on to the next command, DCL, that is Data Control Language. It allows you to control access to the database. Grant or revoke are the DCL commands. Grant gives user access privileges to the database, while revoke withdraws user access privileges given to the user with the help of the Grant command. So the next command is DML, that is Data Manipulation Language. It allows you to access and manipulate data; you can insert, update, delete, and retrieve data from the database. So what does each of these commands do? So the insert command is used to insert data into the table, while update is used to update existing data within the table, and at last, delete is used to delete records from the database. The final command is TCL, that is Transaction Control Language. It allows you to deal with the transaction of the database. A few of the TCL commands are commit, rollback, savepoint, and set transaction. So these were the SQL commands. To understand SQL in a better way, let's use an analogy. If two people want to communicate with each other, then they have to use a language that is understood by both of them. Here, John wants to start a conversation with Dave, and he uses the English language to start his conversation. This language is known to Dave as well, so they will continue their conversation. But what if one of them didn't understand what the other person spoke? There won't be any conversation at all. Relating this analogy, if we consider these two people, one as a user and the other as a database, then that language which is used to communicate between these two is called SQL. Similarly, how a language has a grammar and various rules on how it should be used, even SQL has its own directives. I hope you have clearly understood what exactly SQL is. Let's now head to the next topic, that is advantages of SQL. So the first feature is SQL has well-defined standards. As it says, developers of SQL have clearly mentioned how exactly each and every query has to be written. There is no room for ambiguity when it comes to writing a query; the standards have to be followed. The second advantage is SQL is easy to learn. Yes, SQL is a language that is used to work with a database. Since SQL has a large user base as well as well-defined standards, for a beginner, it is really easy to learn. The next one is in SQL; we can create multiple views. This is one of the unique and early features that SQL came up with. A view is nothing but creating a virtual table. A virtual table is a temporary table for certain use. By doing this, we can protect the integrity of the data. SQL has the ability to not only create a single view but can create multiple views. Fourth one is SQL queries are portable in nature. It means we can execute the SQL query in one system and execute the same query in another system without changing the format, but the condition is that the environment setup of these two systems has to be the same, else the query won't be executed. The next advantage is interactive. The main purpose of SQL is to communicate with a database. We can write complex queries to fetch the results from the database, and these queries can be easily understood by anyone. So these were some of the advantages of SQL. Let's head to the next topic, that is SQL in real time. Since SQL is a language that is used to operate on the database, we need to look at the bigger picture of the data management industry here. If I say database, it includes the SQL language as well. The database is used in different verticals like online stores, healthcare providers, libraries, the financial industry, the retail industry, government agencies, and many more. Now let's consider some real-time examples of the use of SQL and database. The first one is the education sector. Database systems are frequently used in schools, colleges, and universities to store and retrieve data. This data may be regarding student staff details, course details, exam details, attendance details, and fees details. There's a lot of interrelated data that needs to be stored and retrieved efficiently. To understand the magnitude of impact that the database has made in this field, try to imagine the days when the results were only declared on the school notice board. Isn't it easier now to access your exam results with just one click? Who wouldn't say no to such a drastic change? Also, nowadays, the online exams have increased significantly. This has increased the speed of assessment when compared to the olden days. All these are possible because of SQL and database technology. The next sector is the healthcare sector. There were days when people used to stand in front of the clinics and hospitals to get an appointment with a doctor, but now the time has changed. In hospitals and medical institutions, maintaining data related to doctors, patients, and staff is a huge task. Effectively coordinating among these three has to be handled seamlessly with the help of SQL and database. This industry has gained a lot with the introduction of SQL and database; inventory management has been effective. The next one is the retail industry. Every year, leading e-commerce trends come up with great offers, discounts based on your personalized shopping. To come up with all this, they use databases and other technology. The industry utilizes the database and SQL technology extensively, and retail industry customer data has to be managed effectively. There's no scope of error when it comes to handling the data. With the instigation of SQL and database systems, the retail industry can not only secure the data but also can get real-time analysis, which in turn helps them to make a lot of profit. And the final one is the financial sector. When we speak about this sector, it's really hard to even imagine what goes behind the scene; only the experts know how much data will be processed every second. Managing money, assets, shares, etc., in real time is a tedious task. SQL and database technology is helping the financial sector to achieve its primary task. SQL queries can be also used to check fraudulent activities. Looking at the issues of fraudulent activity, effective fraud detection requires a financial organization to process a huge amount of customer purchasing data. So these organizations have to store and retrieve data effectively without causing any burden on another branch of the same organization. These were the few sectors and industries where SQL is used in day-to-day transactions. This brings us to the end of this session. I hope you have clearly understood what is SQL, its evolution, and its application.

[Music]

Do you know when SQL was born? Well, let me answer that question for you. SQL was developed at IBM by Donald Lee Chamberlain and Raymond F. Boys in the early 1970s. It was initially called SEQUEL, that is Structured English Query Language, but later it was changed to SQL because SQL was a trademark of a UK-based engineering company. SQL is said to be a powerful language; the reason for that is it uses very simple English sentences and also uses very few lines. It uses common words such as select, insert, update, and many more to perform its core functionalities. SQL is known to be a declarative language. When you write a query, you have to describe what needs to be done, and you don't have to worry regarding the flow of the query; it will be handled internally by the DBMS that you are using. Now let's look at some of the features of SQL. So the first feature is SQL has well-defined standards. As it says, developers of SQL have clearly mentioned how exactly each and every query has to be written. There is no room for ambiguity when it comes to writing a query; the standards have to be followed. SQL is easy to learn. Yes, SQL is a language that is used to work with the database. Since SQL has a large user base as well as well-defined standards, for a beginner, it is really easy to learn. The next one is in SQL; we can create multiple views. This is one of the unique and early features that SQL came up with. A view is nothing but creating a virtual table. A virtual table is a temporary table for certain use. By doing this, we can protect the integrity of the data. SQL has the ability to not only create a single view but can create multiple views. Finally, SQL queries are portable in nature. It means we can execute the SQL query in one system and execute the same query in another system without changing the format, but the condition is the environment setup of these two systems has to be the same, as the SQL query won't be executed. So these were some of the features of SQL. Now let's look at the next topic, that is data and database. Firstly, let's look at what is data. So the standard definition for data is values from differences which has been translated for some purpose, and this purpose can be anything. The source for the data can be like temperature readings, financial data, videos, blogs, text, etc. It goes on; in the end, it should make a meaningful sense; only then can we consider it as data. This image clearly depicts the different sources of data, so we can clearly understand that the data source can be anything. Since we are clear about what data is all about, let's head to the next topic, that is what is a database. Firstly, let's look at the formal definition for a database. A database is an organized collection of data where the data is stored and accessed electronically from a computer system. To make you understand what it means, let me use an analogy to explain the concept of a database. Consider a library; usually, the library contains a huge collection of books of different genres. Here, the library is a database, and these books are the data. In the image, we can see a person performing an action on the data, and those actions can be like create, store, update, etc. When the user sends the instruction as well as the data, it will be stored inside the database after certain processes, and this entire process is bi-directional, that is, control flows on both sides. Next, I'm going to talk about different types of databases. There are different kinds of databases that are in use today, and these databases are classified based on capabilities, features, functionality, size, and performance. So a few of them are distributed database, object-oriented database, centralized database, operational database, graph database, cloud database, NoSQL database, and finally, relational database. Among these databases, the two popular types that are widely used are first, relational database, and second, NoSQL database. Relational databases generally use the SQL language, and we are going to learn more about it in the coming modules. Moving on, let's look at some of the popular databases that are widely used today. So they are MongoDB, PostgreSQL, Microsoft Access, Microsoft SQL Server, MySQL, and Oracle DB. These are a few popular databases that are used today; each one of them has its own pros and cons. Since we have already started the topic of database, it wouldn't be fair to drop this topic abruptly, so I shall discuss a few basic database-related queries. The first query is how to create a database. To explain this, let me jump into MySQL Workbench. This is the interface of MySQL Workbench. On the left side of the screen, we can see the database. In the center area, we are going to write our queries. At the bottom part, we are going to get the status of the query that has been executed. So you might wonder why I'm using MySQL Workbench for executing SQL queries. Well, SQL is a language that is used to communicate with the database, whereas MySQL Workbench is a database management system. So MySQL Workbench allows us to use SQL queries to communicate with the database. Can't we use other DBMS? Yes, we can, but the syntax of the queries may slightly vary. So let me explain to you the first topic, that is how to create a database, and the syntax for this is: CREATE DATABASE are the keywords used to create a database. Following that, we have to specify the name of the database. Here, I'm using edureka as a name for my DBMS. So let me select this entire statement and click on the lightning icon, so I can see at the bottom that the database with the name edureka has been created. So let me refresh it, so we can see that the database with the name edureka has been created. So the next topic I'll be discussing is how to delete a database, and the syntax for this is: DROP DATABASE are the keywords used to delete a database, and following that will be the database name. So let me select this entire query and click on the lightning icon, so we can see that the database with the name edureka has been deleted. So these were a few queries related to the database. The next topic that we are going to learn is tables. So what is a table? A table in a database is nothing but a collection of data in a tabular way. It consists of rows and columns. The table contains data elements, also known as values, using a model of vertical columns and horizontal rows. The point of intersection of a row and a column is called a cell. A table can have any number of rows but should have a specified number of columns. To understand the concept of a table in a better way, let's look at the image. So the name of the table here is person. When we create a table, it has to have a name; a table without a name doesn't exist. So what are tuples? A single row of a table which contains a single record for that relation. Here, there are six tuples. Next is attributes; features of an entity are called attributes. An attribute has a name and a data type. Here, there are four attributes: those are ID, first name, last name, and date of birth. So I hope you have understood the concept of a table. Let's now understand the table constraints. So what are table constraints? In simple words, it is a restriction that is specified by the user while creating a table. So you may wonder why these kinds of constraints are required. The answer for that is, even though a table stores the data, that data has to be of a certain format. To ensure data integrity, we use constraints. These constraints have to be decided during the creation of a table. If we want to change the constraint, then we have to delete the table, and then we have to create a new table using the new constraints. A few of the constraints that are used most of the times while creating a table are CHECK, DEFAULT, PRIMARY KEY, FOREIGN KEY, NOT NULL, INDEX, and UNIQUE. Since we have understood what a table is, let's look at some of the SQL queries related to the table. The first one is how to create a table. To understand this, let's head to the MySQL Workbench. To create a table, we need an active database. Since we had deleted the previously created database, let me create the database once again. So we can see that we have a database with

The name is Edureka. So now let me create the table. The syntax for creating a table is: `CREATE TABLE` is a keyword used to create a table. Followed by that, we have mentioned the table name. We need to make sure that the table name is unique. Keep in mind that in a database, there cannot be two tables with the same name. Inside the table, we have declared the columns along with the data type, and we have to end the query with a semicolon. So let me execute this query. So we can see that the table EMP has been created.

So the next query I'm going to discuss is how to delete a table. The syntax for this is: we shall use `DROP TABLE` keywords to delete a table, and followed by that, we have to specify the table name. So let me select this entire query, and we can see that the table with the name EMP has been deleted.

With all the basic introduction understood so far, let's now understand some SQL basic queries. Let me begin this by introducing the most basic and widely used query, that is, the `SELECT` statement. The syntax is: `SELECT column name FROM the table name`. We can specify the name of the columns that are present in the table. Also note that if you want to display all the columns of a table, then use the star operator.

Now let's jump into the execution part to explain the entire SQL queries. I'm using the `student` table, and the `student` table has `student ID`, `first name`, `last name`, `address`, `City`, and `marks` as its columns. So the syntax for the `SELECT` statement is: `SELECT * FROM student`. Since we have to display all the columns, I'm using the star operator. So let me select this entire query, so we can see that the entire table has been displayed. So this is one of the ways in which we can use the `SELECT` statement. The another method is if we want to select a particular column, then we have to specify that column name. The syntax for that is: So we can see that from the table, we have selected only `first name` and `last name`. Usually, the `SELECT` statement is used to select the data from the database.

The next SQL query that I'm going to discuss is the `WHERE` clause. The `WHERE` clause is used to filter records. The `WHERE` clause is used to extract only those records that fulfill the specified condition. To demonstrate the `WHERE` clause, let me assume the scenario: if I want the name of the students who are from the city Goa, then my `WHERE` clause query will be something like this: `SELECT first name FROM student WHERE city = 'Goa'`. So let me select this query and execute it. So this is the output.

Now let's look into `AND`, `OR`, `NOT` statements. If we need to add two or more conditions in the `WHERE` clause, then we can use the above-mentioned operators. These keywords will add more complexity to the query. So the first operator is the `AND` operator. This operator displays a record if all the conditions separated by the `AND` operator are true. Let's look at the syntax: `SELECT columns FROM table WHERE condition 1 AND condition 2` has to be true. To understand the example, let's dive into the demo part. I want to display the details of the student who has the first name as Bharat and last name as Singh. To achieve this, I am using the `AND` operator. So let me execute this query. Yes, I got the output for the student name Bharat Singh.

The next operator I'm gonna discuss is the `OR` operator. The `OR` operator usually displays a record if any of the conditions separated by `OR` is true. The syntax for this is: `SELECT columns FROM table WHERE condition 1 OR condition 2` is true. To understand the example, let's dive into the demo. I want to display the details of a student who has the first name as Bhuvi or the last name as Kumar. To achieve this, I am using the `OR` operator here. Any one of the conditions has to be true. So this is the query to execute a scenario. So we have got the output for the student with the name Bhuvi Kumar.

So let's head to the next operator, that is, the `NOT` operator. So this operator displays a record if the condition or conditions are not true. So the syntax is: `SELECT columns FROM table WHERE the condition is NOT true`. Let's see how this example works. Here, I want to display the details of the student who does not have the first name as Ashok. To achieve this, I'm using the `NOT` operator. In this, we can see the details of all the students except Ashok.

The next query I'm going to discuss is `INSERT INTO`. If we want to insert any record or data into a table, then we can use the `INSERT` query. The syntax for this is: `INSERT INTO` is a keyword that is used in the `INSERT` query. Followed by that, we have to specify the table name and columns. After that, we have to specify the values. Let's look at the example to clearly understand how exactly this query works. So this is the example for the `INSERT` query. So we're gonna insert `first name` as Manoj, `last name` as Sharma, `address` as 07 MG Road, and `city` as Jaipur. Also, the `marks` is 438. So let me execute this query. So we can see that the data has been inserted. To check whether the data has been inserted or not, let me use the `SELECT` query. So we can clearly see that Manoj Sharma details has been added to the table.

Next, I'll be discussing a few aggregate functions. An aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria, and a single value is written. We often use aggregate functions with the `GROUP BY` and `HAVING` clauses of the `SELECT` statement. So we will be discussing `GROUP BY` and `HAVING` in the later part of the session. Some of the aggregate functions are `COUNT`, `SUM`, `AVERAGE`, `MINIMUM`, and `MAXIMUM`. So let's discuss each one by one.

So the first one is `COUNT`. This function returns the number of rows that match specified criteria. So the syntax is: `COUNT` of `column name` `FROM` table `WHERE` the condition. So now let's try this example in MySQL Workbench using this query. I will calculate the number of `student ID` that is present in the table. So let me select this query. In the output, we can see that the count of the `student ID` is 6.

The next aggregate function is `AVERAGE`. An `AVERAGE` function returns the average value of a numeric column. So the syntax for this is: `SELECT AVERAGE` of `column FROM` table `WHERE` condition. Let's execute this example. Here, I am trying to find the average marks scored by all the students. So let me select this query. So the average mark scored by all the students is 480.3333.

The next aggregate function is `SUM`. Usually, the `SUM` function returns the total sum of that particular column. The syntax is: `SELECT SUM` of `column FROM` table `WHERE` condition. So let me execute this example. In this example, I am trying to find the total marks scored by all the students. So let me select this query. The total marks scored by all the students is 2882.

Moving on to the next aggregate function, that is, `MINIMUM`. The `MINIMUM` function will return the smallest value of the selected column, and the syntax is: `SELECT MIN` of `column FROM` table `WHERE` condition. So let me execute this example. If I want to know the student name who has scored minimum marks, I'll use this query. So let me select this query. Ashok Sinha has scored 385 marks, and this is the minimum marks in this entire table.

And the last aggregate function that we are going to discuss is `MAX`. The `MAX` function returns the largest value from the selected column, and the syntax is: `SELECT MAX` of `column FROM` table `WHERE` condition. Let's execute this example. So this is the example for the maximum function. So let me execute this query. So we get the output that is Bharat Singh has scored 580 marks. So 580 marks is a maximum marks in the entire table.

The next SQL query is `GROUP BY`. `GROUP BY` is a functionality used to arrange a similar type of data into a group. For instance, if the column in a table consists of similar data or values in different rows, then we can use the `GROUP BY` function to group the data. The syntax is: `SELECT column FROM table WHERE condition GROUP BY` the same column. Let me execute this example. I want to count the number of students who are from different cities. If there is any student from the same city, then the count will be incremented. At the end, the output will have all the city names with the count of the students from that particular city. So let me execute this query. We got the count of students from different cities. Since all the students are from different cities, we can see that the count is 1 in all the cases. If the data is large, we can clearly get to know how effective this query is.

The next query is `HAVING`. This clause is used to place a condition where we need to decide which group will be part of the final result set. The `HAVING` clause was added to SQL because the `WHERE` keyword could not be used with aggregate functions such as `SUM`, `COUNT`, `MIN`, `MAX`, etc. So the syntax is: `SELECT column FROM table WHERE condition GROUP BY` the column `AND HAVING` condition. So let me execute this example in MySQL Workbench so that you'll get an idea about the `HAVING` clause. From the table, if I want to display the students who have scored more than 500, then I'll specify that condition after the `HAVING` keyword. So let me execute this query. So we can see that there are two students, Ashok and Bhuvi, who have scored more than 500 marks.

Moving on to the next query, that is, `ORDER BY`. The `ORDER BY` keyword is used to sort the result set in ascending or descending order. This keyword is used to sort the result set in ascending or descending order. The `ORDER BY` keyword shall sort the record in ascending order by default. If we want to sort the record in descending order, then we need to use the `DESCENDING` keyword. So let me explain the syntax: `SELECT columns FROM table ORDER BY columns` either by ascending or descending. Let me execute this example. In this example, we will get the count of students from different cities, and we are arranging the city in descending order. So let me execute this query. We can see that the cities are arranged in descending order based on the starting alphabet.

The next SQL query that we're gonna learn is null values in SQL. We use a `NULL` term to represent a missing value. A `NULL` value in a table is a value that appears to be blank. A field with a `NULL` value is a field with no value in SQL. Keep note that a `NULL` value doesn't mean that the value is equal to zero. To check the `NULL` value, we are not supposed to use the operators such as greater than, less than, equal to. These operators are not supported in SQL. We have special keywords; those are `IS NULL` and `IS NOT NULL`. First, let's look at the `IS NULL` operator. The `IS NULL` operator is used to test the empty values, and the syntax for this is: `SELECT columns FROM table WHERE column IS NULL`. So let me execute this example. I want to display the student's name whose marks is `NULL`. So let me select this query and let me execute this. Since all the students have marks and none of them has a `NULL` value, in the output we don't have any student names.

The next query is `IS NOT NULL`. The `IS NOT NULL` operator is used to test for non-empty values, and the syntax is: `SELECT column FROM table WHERE column IS NOT NULL`. So again, let me execute this example. I want to display the student names whose marks is not `NULL`. So let me execute this query. Since all the students have marks, all the student names are displayed.

Let's move to the next query, that is, `UPDATE`. Generally, the `UPDATE` command is used to modify rows in a table. The `UPDATE` command can be used to update a single field or multiple fields at the same time. Let's look at the syntax for the `UPDATE` statement: `UPDATE table SET column = Value WHERE condition`. Let's execute this example. Here, I want to change the name of the student with `student id` 1. Previously, the student with `student id` 1 was Ashok Sinha. Now I want to change his name to Amar Kumar. So let me execute this query. So we can see that the student name has been updated. To check the student table, let me execute this query, and we can see that the name of `student id` 1 has been changed from Ashok Sinha to Amar Kumar.

In the next query, we are going to discuss `DELETE`. The SQL `DELETE` command is used to delete rows that are no longer required from the database tables. It deletes the whole row from the table. The syntax is: `DELETE FROM table WHERE condition`. So let me execute this example. If we want to delete a record from the `student` table where the city is Mumbai, let me execute this query. So we can see that the query has been executed. To check the table, let me execute the statement, and the student with the id 1 has been deleted.

Next, let's discuss `IN` and `BETWEEN` operators. The `IN` operator is used to specify multiple values inside the `WHERE` clause. It acts as multiple `OR`. Let's look at the syntax: `SELECT column FROM table WHERE column IN value`. Let me execute this example. If we want to display the record of a student who are from certain cities, then we can use the `IN` operator. In the given example, let's display the name of the students along with their IDs who are from Delhi, Goa, Pune, and Bengaluru. Let me execute this query. In the output, only those students from the specified city names are displayed.

The next operator is `BETWEEN`. The `BETWEEN` operator will select a particular value within the specified range. It's compulsory to add the beginning and the end value. Let us look at the syntax: `SELECT column FROM table WHERE column name BETWEEN value 1 AND value 2`. Let's execute this example. If we want to display the record of students whose marks are in a certain range, then we can use the `BETWEEN` operator. In the given example, let's display the name of the student along with their ID who has scored in the range of 400 and 500. So let me execute this query. In the output, only those student records who have scored in the range of 400 and 500 have been displayed.

So the next topic we're gonna cover is aliases in SQL. An alias is a process of giving a table or a column a temporary name, so that it helps when the query is complex. It increases the readability of the query. This renaming is temporary, and the table name does not change in the original database. We can alias a column or a table. So the first concept is column aliasing, and the syntax is: `SELECT column name AS Alias name FROM table`. So let me execute this example. In the `student` table, the column name `student ID` is bit long. When we write a nested query, we might face some trouble. In order to tackle such situations, alias that `student ID` column as ID. So let me execute this query, and we can see that the column `student ID` has been aliased to ID.

Next is table aliasing. Now let's look at the syntax for table alias, and the syntax is: `SELECT column FROM table AS Alias name`. So let's execute this example. We generally use the `AS` keyword in aliasing. So let me execute this query. By using the technique of table aliasing, I have displayed the names of the students from the `student` table. So that was a basic concept of SQL. [Music]

`NOT IN`. So `NOT` keywords is `NOT` is basically logical operators, and it is used along with other operators like `IN` and others. So we've just seen one example where we want to show the departments which are not in Hyderabad. So this is the repetition of the same example in the previous example which I showed. I included only one location, but we can use multiple keywords. If you're using the `IN` keywords, we'll see the example just now. The `IN` operator fetches values from a set of literals. So this condition is generally used when we want to fetch values from multiple values in a single statement. It's not that I can use only `IN`. I can use `OR` operators. So if there are only one or two conditions, I can either use the `OR` operator or the `IN` operator, but if the values are more, it is not a good idea to use so many `OR` operators or logical operators. Let's assume I want to see the results in intensities. So if I write, if like `WHERE location = 'Mumbai' OR 'New Delhi' OR 'Hyderabad' OR 'Bangalore' OR 'Chennai'`, it is not readable; it's not good. So instead of writing so many `OR` operators, we can use `IN` operators. So the `IN` operator, we basically include all the values out of which we want to filter our results. So we want to fetch our values. So let's see with an example. So let me open a new query window. I'm going to select some departments. So if I want to see the results or see the departments which are either in Chennai or Bengaluru, so I'll write and write `SELECT * FROM department WHERE location IN`. It can be in any one of these locations; that's how we are. Bangalore. Don't forget to include strings or characters in single codes in SQL. So this will fetch the desired results. So we can use multiple values in the parenthesis if we use `IN` comparison operator. So if I use `NOT IN`, then this will go in a negation and will show the opposite of what the `IN` operator is doing. So we have discussed `NOT IN` as well as `IN`. So if there are multiple values, so instead of `OR`, we have to use it. It is good practice to use the `IN` keyword.

Then basic compression operators we have greater than, equals to, less than, greater than equals to. So this is pretty much self-explanatory. So if I want to select the employee whose salary is greater than 20,000, so let's see how we'll get the results. So I can use the previous window. So there's salary. Instead of this, I can write `salary > 20000`. So I'm getting three results. So I have three records or three rows or three employees whose salary is greater than twenty thousand. So if I include greater than or equals to, then I guess I'll get four results. Oh, I don't think so. We have a salary of twenty thousand. Yeah, no we don't have. So let's let's take the example of thirty thousand here. So we'll get the three results, but if I remove the equals to keywords, then of course we'll get only two rows in the result set. And if I use the equals to, then we'll get the only single row which will satisfy the desired or required condition. So this is how we use various operators: greater than, equals to, less than, greater than equals to. Again, this example we can use the equal operator; it will satisfy the desired conditions, fetch the results.

Comparison operator is a like how we use the `LIKE` keywords in the comparison operator. So generally, we use `LIKE` operators to perform wildcard searches of valid search string values. As I mentioned earlier that the `LIKE` keyword is generally used when we are filtering or fetching the strings. So it used with two wildcards: one is a percentage. Percentage denotes zero or many characters, and underscore denotes one character. So that's it. So in the first example, as you can see, I'm getting the values from the `department` table whose locations start with C or the C alphabets. Let's see how we can use it. So we'll first see how we use the percentage wildcard. So if I want to know that what are the different departments where the locations start with the alphabet C, so we will write `SELECT * FROM Department`. We have loc. I have to use the `LIKE` keyword, `LIKE (%)`, and then the keyword C with a percentage sign, that is, the wildcard, will get the results. So if I'll just change the order, if I write the wildcard first and then C, it means I have to show the departments whose location ends with C. So if I'll write it I here, then again I'll get the desired cell because I am fetching the rows whose location ends with the I keyboard or I alphabets. So if I use first wildcard and then alphabet, it means it ends with. If I'll first use the alphabet and then wildcard, it means it starts with. If I write something like this, it's C then wildcard and I, it means it starts with C and it ends with I. So fetch me the locations who start with C because I'm using the C before the wildcard, and since I'm using I after the wildcard, so it ends with I. If I'll execute this query again, it will show me the same results because, but if I change it, for example, I'm starting with h and ending with I, so there is no department with such a condition, so we'll get an empty result set. Now if I need to show that show me the department who starts with h, in that case, all I have to do is that we have to remove the I. So we have to use the keyword

Before the wild card, and it will show us the result itself. So, along with percentage science, we use underscores also as a wild card. So, in this example, as you can see, the second example select department or location from department for locations like so. It means the first three words should be c-h-e-n; then we can use underscore. So we have to first satisfy the first keyword; so the first three should be this. So this is how we use the underscore wildcard.

The last topic of this module is the case expression. So, case Expressions helps us to kind of, you know, simulate the if then else statement like in most of the programming language. We use if else; so this helps us to write the same. Only point with a case statement is that, as you can see in the node, we cannot use null values in the case statement because it always uses the equals to operator, and we cannot use equals to operator with the null keyword. We have to use is null, that I will show you after this example.

So let's assume I'm fetching values from employee. So if I'm looking for the salary column, there are few rows which are having null values, and there are few rows which having values in it. So if I want to see that what are the different employees which have uh null values for the salary column, so if I try to write where salary equals to null, then I won't get any result here because equals to operators does not work with null. So if I'm checking now, we have to use is null. If I'll execute this query again, I'll get the desired result. If I want to check if I want to fetch the columns which do not have null values for the salary column, then we have to use is and then we have to use the not logical operator, is not null. So, not logical operators is always used in combinations with other operators. We get all the employees do not have null values for the salary column. So that is the reason we are using case expression. So we cannot use the null values; otherwise, it will break because we use the equal operators, and equal operators not used along with null. So this is how the syntax of case Expressions.

As you can see, we have declared a variable int input; its type of end, and we have set the values is equals to two. It's just an example; so we have hard coded the value here in this example. So we are selecting case; I am just selecting that if the value is 1, then we'll show the output as 1; when it is 2, then we are showing the output as 2; when it is 3, then we are showing output as a 3; and if it is not out of any these three values, one, two and three, then we'll show the messages your message. This is how we are doing this example. So let me give you one example for that. Let me do one thing; let me find out the states, the cities where my department is. So as we know the Chennai is in Tamil, and Bangalore is in Karnataka. So let's see how we can do that using a case statement. So we have to write select then case keyword, and the case keyword will Define which columns you want to fetch. So I am fetching the location, and then we'll write the band condition. So I'm writing when Chennai then show the result as Tamil Nadu; when Bangalore then let's say Karnataka; and I'm writing an else condition if it is not part of anything. So let's just write no idea. So we have to end the when condition; then we have to write from which tables we are basically fetching this. If I'll execute this query, I'll get the field is Chennai; I'm getting the results seminar; and if it is Bangalore then I'm getting as KR; and since there's some departments which do not have any values like hyderabads, we are getting is just no idea. So this is how we can use if else conditions in SQL statement or select statement by using case expression. Important point is that we should not deal with we'll be using null because we use equals to operator.

What is normalization? Database normalization is a technique of organizing the data in the database. It is a systematic approach of decomposing tables to eliminate data redundancy. It is a multi-step process that puts data into Tableau form, removing the duplicated data from its relational tables. On the screen, we just saw that the table is getting decomposed into two smaller tables. Is it really necessary to normalize the table that is present on the database? Well, every table in the database has to be in the normal form. So normalization is used mainly for two purposes. So the first one is it is used to eliminate repeated data. Having repeated data in the system not only makes the process slow but will cause trouble during the later part of transactions. And second one is to ensure the data dependencies make some logical sense. Yes, usually the data is stored in database with certain logic. Huge data sets without any purpose are completely waste; it's like having an abundant resource without any application. The data that we have should make some logical sense. Normalization came into existence because of the problems that occurred on data. Now let's look at those problems, and these are known as data anomalies.

If a table is not properly normalized and has data redundancy, then it will not only eat up the extra memory space but will also make it difficult to handle and update the database. Let's look at the first anomaly, that is insertion anomaly. Suppose for a new position in a company, Mr. Rakshit is selected, but the department has not been allotted for him. In that case, if we want to update his information to the database, we need to set the department information as null. Similarly, if we have to insert data of thousand employees who are in similar situation, then the department information will be repeated for all those thousand employees. This scenario is a classical example of insertion anomalies.

The next one is update anomaly. What if Mr. Rakshit leaves the company or is no longer the head of the marketing department? In that case, all the employee records will have to be updated, and if by mistake we miss any record, it will lead to data inconsistency. This is nothing but updation anomaly. And the final one is deletion anomaly. In our employee table, two different pieces of information are kept together, that is employ information and Department information. Hence, at the end of financial year, if employee records are deleted, we will also lose the department information. This is nothing but deletion anomaly. So these were some of the problems that occurred while managing the data. To eliminate all these anomalies, normalization came into existence. There are many normal forms which are still under development, but let's focus on the very basic and the essential ones only. So we will be talking about First normal form, Second normal form, Third normal form, and finally end this session with Boyce-Codd normal form. So without wasting further time, let's proceed to First normal form.

In First normal form, we tackle the problem of atomicity. Here, atomicity means values in the table should not be further divided. In simple terms, a single cell cannot hold multiple values. If a table contains a composite or multi-valued attributes, it violates the First normal form. So the following functions will be performed in First normal form: The first one is it removes repeating groups from the table; and next it creates a separate table for each set of related data; and finally it identifies each set of related data with the primary key. To understand this in a better way, let's look at the given table. In the employee table, we have employee ID, employee name, phone number, and salary as columns. We can clearly see that the phone number column has two values; thus, it violates the First normal form. Now if we apply the First normal form to the above table, we get the following result. In this table, each and every row is this thing, that is no cell has multiple values. The table has achieved atomicity. First normal form is simple and can be easily identified in the table. We can clearly see there is no multiple values in each and every column; thus, the First normal form is achieved. Now let's move to Second normal form.

Second normal form was originally defined by E.F. Codd in 1971. A table is said to be in Second normal form only when it fulfills the following condition: The first condition is it has to be in First normal form; second one is the table also should not contain partial dependency. Here, partial dependency means the proper subset of a candidate key determines a non-prime attribute. So what is a non-prime attribute? Let's understand this in a simple way. Attributes that form a candidate key in a table are called Prime attributes, and the rest of the attributes of the relation are non-prime. For a table, Prime attributes can be like employee ID and Department ID, and the non-prime attributes can be like office location. To understand Second normal form, let's consider this table. This table has a composite primary key, that is employee ID and Department ID makes the primary key. The non-key attribute is office location. In this case, office location only depends on Department ID, which is only the part of primary key; therefore, this table does not satisfy the Second normal form. So what to do in such scenario? The answer is simple: split the table accordingly. To bring the stable to Second normal form, we need to break the table into two parts, which will give the following tables. The first table has employee ID and Department ID as columns; the second one has Department ID and office location as columns. As you can see, we have removed the partial functional dependency that we initially had. Now in the table, the column office location is fully dependent on the primary key of that table, which is nothing but Department ID. I hope you have understood Second normal form.

Now that we have learned First normal form and Second normal form, let's head to the next part of this normalization. Next topic is Third normal form. Third normal form is a normal form that is used in normalizing the table to reduce the duplication of data and ensure referential integrity. The following condition has to be met by the table to be in Third normal form: And the first condition is the table has to be in Second normal form; and the second condition is no non-prime attribute is transitively dependent on any non-prime attribute which depends on other non-prime attributes. I know it's bit confusing, so let me make it simple for you. It's like if C is dependent on B, and in turn B is dependent on A, then transitively C is dependent on A. This should not happen in Third normal form. All the non-prime attributes must depend only on the prime attributes. So these are the two necessary conditions that needs to be attained. So why was the normal form designed? Firstly, to eliminate undesirable data anomalies; the next one is to reduce the need for restructuring over time; and finally to make the data model more informative.

Since we have understood the Third normal form, let's look at the example table. In the about table, student ID determines subject ID, and subject ID determine subject; therefore, student ID determine subject via subject ID. This implies that we have transitive functional dependency, and this table does not satisfy the Third normal form. Now in order to achieve the normal form, we need to divide the table as shown below. Firstly, let's divide the table and store student ID, student name, subject ID, and address in it. All the columns are referring to the primary key which is student ID. Let the second table have subject ID and subject column. So subject is dependent only on subject ID and not on student ID. As you can see from the about table, all the non-key attributes are now fully functionally dependent only on the primary key. In the first table, columns such as student name, subject ID, and address are only dependent on student ID. In the second table, subject is only dependent on subject ID. With this being understood, now we can proceed further to next normal form, that is Boyce-Codd normal form. This is also known as 3.5 normal form. It is the higher version of Third normal form and was developed by Raymond F. Boyce and Edgar F. Codd to address certain types of anomalies which were not dealt with Third normal form. Before proceeding to Boyce-Codd normal form, the table has to satisfy Third normal form. In Boyce-Codd normal form, if every functional dependency, that is A implies B, then A has to be the Super Key of that particular table. So what is a Super Key? A Super Key is a group of single or multiple Keys which identifies rows in a table. Let's look at the table to clearly understand Boyce-Codd normal form. In the given table, one student can enroll for multiple subjects; there can be multiple Professor teaching one subject; and for each subject a professor is assigned to the student. These are the necessary condition of this table. In this table, all the normal forms are satisfied except Boyce-Codd normal form. Why? As you can see that student ID and subject form the primary key, which means that the subject column is prime attribute, but there is one more dependency that is Professor is depending on subject, and while subject is a prime attribute, Professor is a non-prime attribute, which is not allowed by Boyce-Codd normal form. Now in order to satisfy the Boyce-Codd normal form, we will be dividing the table into two parts. The table at the top will hold student ID which already exists, and we will create a new column that is Professor ID; and in the second table which is below will have the columns Professor ID, professor, and subject columns. Why do we need to have a new column that is Professor ID? By doing this, we are removing the non-prime attributes functional dependency. In the second table, Professor ID will be the Super Key of that table, and remaining column will be functionally dependent on it. By doing this, we are satisfying Boyce-Codd normal form.

What are triggers? Triggers are the SQL code that are automatically executed in response to certain events on a particular table. These are used to maintain the Integrity of the data in a given table. A trigger in SQL works similar to real-world trigger. I know this is a formal definition, but let's try to understand it in a better way. Here we can see Anna is asking Sharon about triggers. Shouldn't imagine trigger to a falling dominoes. How does a falling Dominos is related to a trigger? Let's move further and see the explanation given by Sharon. Anna is a marketing officer in a company. When a new customer data is entered into the company's database, she has to send the welcome email to each and every new customer. If it is one or two customer, Anna can do it manually, but what if the count is more than a thousand? It will be a repetitive and tiring job; efficiency of Anna may drop. Well, in such scenario triggers come in handy. Anna can easily create a trigger which will automatically send a welcome email to new customer once the data is entered into the database. After creating a trigger in the database of the company, she doesn't have to monitor the trigger frequently. The efficiency of the work is increased with this analogy given by Sharon. I hope you're clear with the introduction of trigger. Let's head to the next topic, that is syntax and example of a trigger.

On the screen, we can see the syntax of a trigger, and let me explain each and every part in detail. The first part is CREATE TRIGGER; these two keywords are used to specify that a trigger block is going to be declared. The next one is trigger name; it specifies the name of the trigger. Trigger name has to be unique and shouldn't repeat. The next one is BEFORE or AFTER; this specifies when the trigger will be executed. It tells us the time at which the trigger is initiated, that is either before ongoing event or after the ongoing event. BEFORE triggers are used to update or validate record values before they are saved to the database, while AFTER triggers are used to access Fields values that are sent by the system and to affect changes in other records. The records that activate the AFTER trigger are read only; we cannot use AFTER trigger if we want to update a record because it will lead to a read-only error. The next part of the syntax is INSERT, UPDATE, or DELETE; these are the DML operations, and we can use either of them in a given trigger. Next is ON table name; we need to mention the table name on which the trigger is being applied. Don't forget to use ON keyword, and also make sure the selected table is present in the database. The next part is FOR EACH ROW or FOR EACH COLUMN; row level triggers get executed before or after any column value of a row changes, while column level triggers get executed before or after the specified column changes. The final part of the syntax is trigger body; it consists of queries that needs to be executed when the trigger is called. So this was a brief introduction to syntax of a trigger. On the screen, we can see an example for a trigger. In the given trigger, we are trying to calculate the marks of a student as soon as his details are upgraded to the database. Here we are adding 100 marks to the marks column of each new record. Also make a note, NEW keyword refers to the row that is getting affected. So this was all about a simple trigger, but we can also create a nested trigger that can do multiple process. Also handling it and terminating it at the right time is very important. If we don't end the trigger properly, it may lead to an infinite Loop. You might be wondering in which scenario we can use the nested trigger. Rather than giving you a tailored answer, let me share a scenario with you which will help you in understanding the nested trigger in a better way. Continuing from the earlier scenario, Anna sent an email for every new customer that was added to the company's database. Now what if she wishes to keep a track of numbers of customers to whom the email was sent? Now Anna needs to create a nested trigger to keep the drag of the count along with sending an email. Doesn't it sound simple? So that was all about the syntax of trigger. Let's now try to implement an example of trigger in SQL. So the next topic is operations in trigger. We can perform many operations using triggers; some may be simple and some may be little complex, but once if we go through the query it's easy to understand. The first operation is DROP; we can use DROP command to remove a trigger from the database, and the Syntax for this is DROP TRIGGER trigger name. To understand this in a better way, let's head to MySQL workbench. I hope you know how to use MySQL workbench; if not, then check SQL basics for beginner video by edureka for better understanding of how MySQL workbench will work. To drop a trigger from the database, the trigger has to be present in our database. So this is the syntax used to drop a trigger. So let me execute this query. So we can see in the status bar the trigger with the name sample trigger has been dropped. Let's head to the next operation, that is DISPLAY. We can use SHOW command to display the triggers from the database, and the Syntax for this is SHOW TRIGGERS in database name. So let me head back to MySQL workbench to execute this command. To display a trigger, the trigger has to be present in the database. So let me execute this SQL query to display the triggers that are present in my database. I can see that the trigger with the name sample trigger is present in my database at edureka. So let's head to the next operation. The next operation is INSERT, and the first variant is BEFORE INSERT triggers. BEFORE INSERT triggers are used to update or validate record values before they are saved to database, and the Syntax for this is CREATE TRIGGER calculate; here calculate is the name of the trigger; BEFORE INSERT ON the table name; FOR EACH ROW; and SET operation. So let me head back to MySQL workbench to execute this query. Before explaining BEFORE INSERT trigger, let me explain something else. I will be using student table, and The Columns of this table are: it has student ID, first name, last name, address, City, and marks. I will be creating a trigger with the name sample trigger here. BEFORE INSERT trigger is used to set 100 marks extra for each and every student marks column when the new student value is added to the table. So let me execute this trigger, and we can see that the trigger has been created. Now let me insert a record into the table. I'll be using INSERT INTO command to insert a record into the table. So let me execute this query, but before that make sure to remember I will be adding details of Wamshi K; his marks will be 478, but as we have created a trigger, it has to add 100 marks extra, and the resulting marks

Has to be 578, so let me execute this query. Okay, the query has been inserted, so let me check the table, and we can see that the marks of Vamshi K is 578. So we can clearly say that the trigger has worked.

The next variant of insert is after insert triggers. After insert triggers are used to access Fields values that are set by the system and to effect changes in other records. The syntax is: CREATE TRIGGER name of the trigger, that is total_Mark AFTER INSERT ON student. Student is a table name for each row INSERT INTO final_marks value of the column.

So let's head back to my SQL workbench to execute this example. To use this variant, we need one more table, that is the final_marks table where the trigger will store the results. This SQL query will create a table with the name final_marks. So let me execute this query. So we can see in the status bar the table with the name final_marks has been created. Whenever we insert data to the student table, the previous trigger, that is sample_trigger, will be executed. Now, with the help of after insert trigger, let's show the marks of the student table in a final_Mark table. This will be the after insert trigger, and the name of this trigger is scal. We will be updating total_marks from the student table to the final_marks table. Let me execute this trigger, and we can see that the trigger with the name Cal has been created.

To check the working of a trigger named Cal, let me insert the data of Rachit Kumar into the student table and make a note: his marks is 500. So we can see that the data has been inserted into the student table. Let me execute this query, and we can see that the student name Rachit Kumar has 600 marks.

Let's move to the next topic, that is advantage and disadvantage. Let's look at the advantages of a trigger. First one is forcing security approvals on the table that are present in the database. The next one is triggers provide another way to check the integrity of the data. The third one is triggers counter react invalid exchanges. The fourth one is triggers handle errors from the database layer. And the final one is normally triggers can be useful for inspecting the data changes in the table.

Let's look at a disadvantage of a trigger. Triggers can only provide extended validation; that is not all kind of validations. For simple validations, you cannot use NOT NULL, UNIQUE check, and foreign key constraints in a given trigger. The next one is triggers may increase the overhead of a database. The final disadvantage is triggers can be difficult to troubleshoot because they execute automatically in the database. This may not be visible to client applications. [Music]

What are SQL joins? So if someone asks you what are joins in SQL, joins in SQL are commands which are used to combine rows from two or more tables based on the related column between those tables. The joins are predominantly used when a user is trying to extract data from a table which have one-to-many relationships between them or many-to-many relationships between them. Joins in SQL are basically commands, guys, by which you can join two tables and you can get the rows of two tables based on a related column.

Now, if you ask me what are the different types of joins in SQL, there are mainly four types of joins in SQL: that is the inner join, the left join, the right join, and the full join. So let's look into each one of them one by one, starting with the inner join.

The inner join is a type of join that returns those records which have matching values in both the tables. So if you consider table A and table B and you apply and you know join on both these tables, then all those records would be returned which have matching values in both these tables. So for our understanding, I am going to consider two tables, that is the employee table and the projects table. So when I apply the inner join on the employee table and the project table, all the steppers which have matching values in both the tables will be given as output.

So the syntax for inner join is as you can see on the screen, that is SELECT table_one.column_one, table_two.column_two, table_two.column_one and so on. So basically these are the various columns that you want to retrieve from the respective tables from table level 1 INNER JOIN table_2, that is basically you're applying the inner join on table_1 and table_2, and then you have to mention the related column. So that will be mentioned after the ON statement. So you'll mention INNER JOIN table_2 ON table_one.matching_column_name = table_two.matching_column_name. So if I have to just repeat the syntax for you, it's SELECT all the columns basically whatever columns that you need from table_one INNER JOIN table_two ON table_one.match_column_name = table_two.match_column_name.

So if you want to see how INNER JOIN can be applied practically, let's move on to my MySQL workbench where I've created these two tables, that is the employee table and the projects table, and let's apply the join statements on both these tables. Okay, so before I move forward with this, let me just open a new query Tab and let me just clear all the action outputs. So now what I'll do is I'll just write a statement that is SELECT * FROM employee. Right, so I'll just execute this particular statement, and you'll see that you know you'll get the output as all the details from the employee table that I've already created. I have around five rows with five employee IDs and their first name, last name, age, email ID, phone number, and address added into this table. So similarly, I'll show you the projects table, right? So let me just remove this and let me type in Project and just execute this particular statement, and you'll see the different column attributes in the project table. So as you can see, I have the project ID, the employee ID, the client ID, project name, and the project start date. Client ID can be basically considered for all those clients. So you can have a separate table for the client IDs.

So guys, if you see in both these tables there is a matching column, that is the employee ID, right? So the basic relation between both these tables is that a specific employee having a specific employee ID can work on N number of projects. Right, he can either work on the project number one, two, three, four, five, six and so on, right? So as you can see, my employee ID 3 works on two projects, that is the Triple Three project and the Triple Four project. And similarly, you can see that you know there are employees with the employee IDs 978, but yes, their information was not present in the employee table, right? So let's apply the join statements on these tables and understand what we get as output. So initially I had explained you what the inner join was. So when you apply inner join and two tables, you can clearly see that you know you get matching values from both the tables. So what I'm going to do is I'm going to apply inner join on both these tables. So for that you simply have to write a query. So what I'll do is I've already executed it before. I'll just copy and paste the query over here so that I can explain it for you guys. So what I've done is I've just selected the employee ID, the employee first name, the employee last name, the project ID, and the project name to be retrieved from both the employee and the project table, and then I've applied an inner join on the employee and the project table. So for that I've just written a query as you can see on the screen: it's SELECT employee.empid, employee.mfname, employee.mlname, that is basically the first name and the last name, then project.project_ID, project.project_name FROM employee INNER JOIN project ON employee.emp_ID = project.empid because empid is basically a matching column in both the tables, right? So let's just execute this particular query. So when you execute this particular query, you can clearly see that all the matching values from both the tables have been retrieved; that is basically all the employees working on a specific project and their respective employee ID, employee first name, last name, project ID, and the project name has been retrieved.

So guys, that was about inner join. Now let's move forward to our next type of join, that is the left join. Now as you can see on the screen, now the left join or the left outer join returns all those records from the left table and also those records which satisfy a condition from the right table. So if you consider table A and table B as two tables on which you want to apply the left join, then table A would be considered as the left table and table B would be considered as the right table. And when you apply a left join on table A and table B, you will clearly see that you know all the records from the left table would be retrieved and also the records with satisfy a condition from the right table would also be retrieved. Also, let me tell you that you know the records which have no matching values in the right table, the output or the result set will contain the null values, right? So basically, if you have around three rows from the left table which have no matching request from the right table, then those records will have null values.

So the syntax for left join is as you can see in the screen: it's just similar to inner join; you just have to replace the word INNER JOIN to LEFT JOIN. You can change the syntax like you know SELECT table_one.column_one, table_two.column_two and so on; that is basically the different column attributes that you want to retrieve from table_one LEFT JOIN table_two ON table_one.matching_column_name = table_two.matching_column_name. So guys, that was about left join. So now let's just again shift back to my MySQL workbench, and then I'll show you how you can apply the left join. I'm just going to use the similar query. So what I'm going to do is I'm going to retrieve the first name, the last name, the project ID, and the project name from both the employee and the project table and then apply a left join on it. So for that I've written a query as you can see on the screen, that is SELECT employee.mp_name, employee.mpl_name, project.project_ID, project.project_name FROM employee LEFT JOIN project ON employee.empid = project.empid, right? So basically, that is because you know this is the matching column between both the tables. So I'm gonna just execute this particular query. So once you execute this query, you can clearly see the output: all the records from the left table, and for those records which do not have any matching record for the right table, we have a null value present. So if you remember, we had five employees in the employee table, right? So basically, that was Warden, Himani, Ayushi, Swathi, and Famous. And if you remember, Ayushi worked on two projects, so both the project details are present over here, and Heyman worked on no project, right? So since he worked on no project, the values present in the project ID and the project name are null values by default.

So guys, that was about the left join. Now let's move forward to the next type of join, that is the right join. So the right join or the right outer join returns all the records from the right table and also those records which satisfy a condition from the left table. So I know all right, this sounds quite similar to the left outer join. Yes, it definitely is. The only difference between both of them is that you know the right outer join returns all the records from the right table and also the records which satisfy a condition from the left table. Coming to the left outer join, the left outer join returns all the records from the left table and also those records would satisfy a condition from the right table. So it's just wise words of both of them. And also, you know, the records which have no matching values in the left table, the output or the result set would contain the null values. So guys, that was about the right join. Now the syntax of right join is as you can see in the screen; it's again really similar to the left join. It's simple: it's SELECT table_one.column_one, table_two.column_two and so on. So basically all the column values from both the tables that you want to retrieve from table_one RIGHT JOIN table_two ON table_one.matching_column_name = table_two.matching_column_name. So the only difference between the syntax, if you've seen the three joins that you saw till now, was the word INNER, LEFT, and RIGHT; else everything else would be the same. So you just have to apply the same logic. So for that what we'll do is we'll again shift back to my MySQL workbench. Now what I'll do is I'll just copy the query; I'll paste it over here again, and then I'll just change this word to RIGHT. So I'll just apply RIGHT JOIN. Now I'll just execute this query again. So when we execute this query, you'll clearly see that you know the employee first name, last name, project ID, and project name are retrieved from both the tables. All those records from the right table are retrieved, and the records which satisfy conditions from the left table are also retrieved. But yes, those records which have no matching values from the left table have null values present in the record. You can clearly see that you know Warden, Himani, Ayushi, and Swati worked on projects, and then they had their specific project IDs and project name. But yes, they were employees who worked on project six, seven, eight, but their employee information was not present in the employee table. So that's the reason there is a null value present in the records of six, seven, eight projects.

So guys, that was about RIGHT JOIN. Now moving forward to the final type of join, that is the full join. So the full join or the full outer join returns all those records which either have a matching value in the left table or in the right table. So basically, if you consider table A and table B and you apply full join on both these tables, then it will return all those records which either have the matching value in table A or in table B.

Now the syntax for full join is really simple; it's again the same as the other three joins, but you just have to mention the word FULL JOIN. So the syntax is SELECT table_one.column_one, table_two.column_two, table_two.column_one and so on; basically, different column attributes from table_one FULL JOIN table_two ON table_one.matching_column_name = table_two.matching_column_name. So that's basically again the related column; that is basically a matching column. Now to see how full join works, let me just shift back to my MySQL workbench. Now let me just tell you one thing over here. Now since I am showing you how to apply joins on SQL, let me just tell you that you know on MySQL the full join is not applicable. So that's the reason, since I'm showing you on MySQL workbench, the word FULL JOIN will not work. To just show you the working of FULL JOIN, I'm just going to use the word UNION in between both these queries. So what's gonna happen is we're going to retrieve all the values from the left table and the matching value to the right table, that is through the left join, and then we're going to UNION it with all the matching values from the right table and also the values with satisfy a condition from the left table. This is nothing but FULL JOIN, but since we're working on MySQL workbench and the word FULL JOIN doesn't work, so I'm going to just use the word UNION. I'm just going to retrieve the project ID, the employee first name, and the employee last name. So what I'm going to do is I'm going to just execute this particular query. So when I execute this particular query, you'll clearly see that you know we're getting all the values from the left table which satisfy a condition from the right table and also all the values from the right table which again satisfy a condition or match the values from the left table, right? So if we consider the first left join condition where we got all the employee details and the project details, you'll see that you know we've got Warden, Himani, Ayushi twice, Swati, Haman, and the respective project details. Since Heyman did not work on any project, the project ID was null over here. Now similarly, if we consider the output for the right join where you know we took all the records from the right table and took matching values from the left table, we saw that you know for the project ID is triple six, triple seven, triple eight, there was no employee information present, right? So that's the reason there is a null value present in the records of six, seven, eight projects.

So guys, that was about full join. So I hope you've understood the different types of joins. The syntax is really simple for all the different types of joins, guys. You just have to change the word in all the different types of joins. For inner join, you use the word INNER; for the left join, you use LEFT JOIN; for the right, you use the RIGHT JOIN; and for the full join, you use the word FULL JOIN. So if you just want to apply left join, what you simply do is you mention all the columns; that is you mention the keyword SELECT and mention the table_name.column_name, and then you mentioned FROM table_one LEFT JOIN table_two ON, and then you mentioned the matching column names from both the tables, right? So you mentioned table_one.matching_column_name = table_two.matching_column_name. So guys, that's how you can use the different types of joins. I hope it's really clear to you guys. If you have any further queries, then you can definitely let us know in the comments section.

Now that you know the different types of joins in SQL, let me just cover a few important questions that are generally asked in interviews about joins. So the first question is what is a natural join, and in which situations is a natural join used? A natural join is also a join operation that is used to give an output based on the columns in both the tables between which the join operation is implemented. So that's what a natural join is, guys. It basically aims to give you output based on the columns between which this join is applied. Now basically, natural join is used when you want to make sure that you know the number of columns returned are less. So for example, if you see on the screen, we have two tables, right, that is table one having two columns and table two having two columns. Over here, the table one had column names column_one, column_two, and table two again has column names column_one and column_three. Now if you apply a natural join on both these tables, you'll clearly see that you'll get an output as column_one, column_two, column_three, and the respective records. But in the same scenario, if you apply an inner join, what you will clearly see that you know you'll get an output like one.column_one, that is basically for table_one.column_one, and then one.column_two, that is table_one.column_two, and their respective records would be stored. Now if you see over here, you'll clearly see that you know when you apply the inner join, you'll have a redundancy of data; that is you know the column_one data is getting repeated again; that is basically it is repeated twice. But in this case of natural join, it's just mentioned once. So this was a scenario of two tables where you know the output was so simple, but yes, if you look into a daily basis where you know database administrators deal with N number of tables and then they want to apply the join operation on these two tables, you'll clearly see that you know if they apply an inner join, then that would create a lot of problems of redundancy of data and obviously more number of columns would be generated. But yes, in the same scenario, they apply a natural join; the number of columns would be reduced at a maximum extent. So that's the situation, guys, where you apply a natural join. So if you're ever asked you know in which situations do you apply a natural join, you can just answer this question by simply saying that you know you can apply a natural join when you want the number of columns to be less. So I hope I'm clear with this point. Now moving on to a

Second question: that is, how to map many-to-many relationships using joins? Now, it's a known fact that you know the joins are basically used to map one-to-many relationships. But yes, if there's a confusion, you know how to map many-to-many relationships, let me just tell you that you know you need to use two join statements.

So, to explain why two join statements are required, you can consider a scenario when you have three tables: the employee table, the projects table, and the Technologies table. Now, let's assume that you know each employee is working on a single project. So this obviously means that you know one project cannot be assigned to more than one employee. Now, similarly, if you consider a project can be based on multiple Technologies, and any technology can be used in any number of projects, this kind of relationship is basically a many-to-many relationship.

Now, to apply the join operation on the many-to-many relationships, what you can simply do is you can have three tables: the projects table and the Technologies table itself. So basically, these are the two tables which have many-to-many relationships between each other, and also we can have an extra table, that is the project_Technologies table. Now, the project_Technologies table will hold a combination of project and technology in every row. Now, let's say we have a project A. Let's say this project A has three technologies: that is, DevOps, microservices, and Hadoop. Now, you have to map these Technologies to the project, right? Now, this project_to_technology table will hold the record of every project-technology combination. So it will hold a record of project A to DevOps, and then project A to again Hadoop, and project A to micro-services. Similarly, it will have n number of records for n number of projects and m number of Technologies. So this table is really, really important in this scenario, and this table basically aims to map the items on the projects table to the items on the Technologies table so that multiple projects can be assigned to one or more Technologies.

So now that you have three tables: the project table, the Technologies, and the projects_to_Technologies table, you need to use two join statements to link all these tables together. That is, use the first join statement to join the project_to_Technologies to project table, and then we have to use the second join statement to join the project_technology table to technology table. Now, this is how all the projects and the Technologies which have a many-to-many relationships between them will be linked with each other. So it's really simple, guys. Whenever you have a many-to-many relationship between two tables and you want to apply a join operation between these two tables, you just have to create another table, you know, which can have all the combinations of the previous tables, and then you apply a join operation from table A to table C and then table B to table C. So I hope I'm clear with this point. Now, let's move forward with our next question.

That is, what is a hash join? Now, hash joins are also a type of join which are used to join large tables or an instance where the user wants most of the join table rows. So whenever the user wants most of the join table rows or when you want to join two large tables, you basically use this type of join, that is basically the hash join. Now, the hash join algorithm is basically a two-step algorithm. So it has mainly the build phase and the probe phase. So in the build phase, you basically create an in-memory hash index on the left side of input, and in the probe phase, you go through the right side of input each row at a time and then find the matches using the index created in the build phase. So hash join is again a type of join which is used to join large tables, and it has mainly two steps: that is, the build phase and the probe phase. In the build phase, you basically create an in-memory hash index on the left side of input, and in the probe phase, you go through the right side of input, each row at a time, and find the match using the index created in the build phase. So guys, that was about the hash join. Now, let's move forward with the next question.

That is, what is a self join and a cross join? So the self join, in other words, is a join of a table to itself. So this basically means that you know each row in a table is joined with itself. So when you apply a self join to a table, just remember that you know each row in a table is joined with itself. Now, coming to cross join, the cross join is a type of join in which a join clause is applied to each row of a table to every row of the other table. So whenever you apply a cross join to two tables, then just remember that you know a join clause is applied to each row of a table to every row of the other table. Also, when the WHERE conditions use this type of join, it behaves as an inner join, and when the WHERE condition is not present, it behaves like a Cartesian product. So you just have to remember two points: the first point is that whenever you apply a cross join on specific tables, a join clause is applied on each row of a single table to every row of the other table, and also when the WHERE condition is present, this type of join behaves as an inner join, and when the WHERE condition is not present, it behaves like a Cartesian product. Now, let's move forward with a final question.

That is, how to perform a join operation on three tables? Now, if you remember in the previous questions, I discussed a question where you know we understood how to map many-to-many relationships using join operations, right? So over there, if you remember, we used three tables: that is, a project table, the Technologies table, and the project_Technologies table. Now, to apply a join operation on three tables, we use two join statements, right? That is to join table A to table C and then table B to table C. So basically, to apply a join operation on three tables, you need to use two join statements.

Built-in functions are used to calculate values and manipulate data. These functions can be used anywhere as expressions. When we say anywhere, it means we can use them in the SELECT query; we can use them in WHERE clause; we can use them in HAVING clause. So these built-in functions can be used anywhere based upon the business requirement or based upon the type of functions which we are using. So we broadly categorize the various built-in functions into the following categories, as you can see on the screen. So we can divide the built-in functions into conversion functions, where we convert the values from one data type to another data type; we have logical functions; math functions to play around with the data, mathematical operations; we generally use math functions; aggregate functions, if you want to calculate, for example, average; we want to calculate sum or total of a salary of all employees, then we use aggregate functions; string functions help us to play around with various strings or characters in our data; most of the string functions are somewhat similar to the string functions which we have in other programming languages or the basic programming languages like C, C++, C#, or Java; date functions have all the basic functions which we can use to manipulate date or retrieve date from our database. So let's discuss all of the functions one by one in coming slides.

As we discussed, that these are the various categories again: conversion functions that support data type casting and converting; logical functions are scalar functions that perform logical operations; these are kind of similar to the math functions; are again the scalar functions which perform calculations, usually based on the input values that are provided as an argument, and most of the times the returns are numeric value; aggregate functions, as I mentioned, we use SUM, we use average, we use maximum of values; so aggregate functions basically perform a calculation on a set of values and they return a single value, except for the COUNT. So COUNT is also an aggregate function; other than COUNT, all other aggregate functions ignore NULL values. In the objective, we saw that we are going to discuss about the GROUP BY and HAVING clause; so aggregate functions are frequently used with a GROUP BY clause of the SELECT statement, or we can say that we use GROUP BY clause only with the aggregate functions, or group functions; some people refer aggregate functions as group functions, so don't get confused; they are one and the same thing; string functions again are scalar functions and they perform operations on a string input value and return strings or numerical value based upon the kind of functions which we are using; date functions straightforwardly manipulate the dates. So let's start with the conversion functions.

As the name itself suggests, these functions help us to convert an expression or a value from one data type to another. So we have three commonly used conversion functions: CAST, CONVERT, and PARSE; and in the bottom three, you can see that we have TRY_CAST, we have TRY_CONVERT, and we have TRY_PARSE. So the top three and bottom three, they give the same results; they work in similar sessions; the only difference here is that the top three functions return a value of specified data type and throw errors on failure, whereas the bottom three they give the NULL values on failure. So we can relate this TRY as like how we have the TRY-CATCH block in other programming languages to handle the exception; same way we use TRY_CAST if you want to get the NULL values if something wrong happened while calculating the expressions or while fetching the results; same is the case with TRY_CONVERT and TRY_PARSE; but if any error happens while using CAST, CONVERT, and PARSE, we'll get an exception; we'll get an error; whereas error can be handled by converting it to the NULL values if we use TRY_CAST, TRY_CONVERT, and TRY_PARSE.

So as you can see on the slide, we are converting the value 10 as INT and we are multiplying by 20. Again, we are converting INT 10 to INT and again we are doing a multiplication of the value after conversion with 20. So that what is the difference between CAST and CONVERT, because the end result is almost similar? So both functions can be used interchangeably in most of the situations; the only difference is that CAST is ANSI SQL compliant; it follows American National Standard Institute, whereas CONVERT does not follow any such compliance. Let's see an example of these basic operations. So I'll open Management Studio of SQL, let open a new query, and let me copy the example. So let me copy both the examples; I increase the font size. So if I'll execute, I'm getting this result. Since we are converting 10 as INT, and again if you'll see the result of CAST function and CONVERT functions is exactly similar; only difference is in the syntax; the syntax of CONVERT function is different from CAST function. So one important point I just want to mention here is that in SELECT operation we can use mathematical operators like we can use plus, minus, divide, and multiplications. So here after converting 10 into INT, we are multiplying it with 20 to get the end result, and this is the alias which we discussed in module 2. So we can change it; we can change it to any value; we can change it; let's say I'm writing it to CAST_result, and I can change it to CONVERT_result. If I'll execute it, I'll get the same results: CAST_results and CONVERT_result here are aliases; these are the aliases for the columns. In the module 3, we saw that we use aliases for the table. So let's say that if there's an issue while casting or converting a desired value, then we'll get an error when we'll use CAST and CONVERT, but we'll get a NULL value when we'll use TRY_CAST and TRY_CONVERT. Let's verify this using an example. So I'm trying to convert character into INT. So we'll get an error that conversion failed when converting the VARCHAR value 'a' to data type INT. Now let's use TRY_CAST. So I'll copy this statement. So let's assume I'll use TRY_CONVERT, and if I'll try to convert a value which is not numeric, and if I'll execute it, we'll get the incorrect syntax near the keyword TRY_CONVERT. Sorry, I forgot to write SELECT, and if I'll execute it now, we'll get NULL value. So instead of error, we are getting a NULL value if we use TRY_CONVERT or TRY_CAST. So based upon the business requirement, we'll choose either the TRY_CONVERT or CONVERT. Let's move to the next function; let's discuss about the logical functions.

So we have two logical functions: CHOOSE and IIF. Logical functions can be used to display one of the several values based on a logical condition. So as we have discussed, we have two logical functions: CHOOSE and IIF. CHOOSE returns a specified index from a list of values and returns NULL if the index is 0 or greater than the number of items, or we can say that the CHOOSE basically acts as an index into an array when an array is composed of the arguments that follow the index argument. So as you can see the instinct syntax, we have the CHOOSE keyword, and in the parenthesis we have index. So this is the index which we have to define, that what value we want to return, and this value 1, value 2, and we can have up to value n. So let's understand CHOOSE by an example. So let me write one example so that it will help us to understand CHOOSE keywords, and all these functions are basically—can you see the color code for the keywords?—we basically have blue colors, but for these functions we have pink color. So we'll define 3; this is the index; and then followed by the various values. Let's say I have 'test' as a one value, I have 'just' as another value; third value I'll be having 'rest'. So if I'll execute this statement, I should get the value 'rest' because this index does not start with 0. Please note it down; in the CHOOSE function, the index starts from 1; this is a one-base index, not the zero-base index like we have in most programming languages. So if I'll execute this statement, I'll get 'rest' because we are instructing the SQL Server that we want the third value after the various values available. So CHOOSE function basically gives an error if you try to use the index as the value 0, or we'll try to provide the index which is outside this range. So let's understand it by an example. So if I provide an index 0, if I execute this, I'll get a NULL value; or if I'll provide the index which is outside the bound of this array—when I say bound, if it is more than the number of values which we are trying to select from—then again it will return NULL value. So this, since there are only three values here, and I'm giving index 5, so since there's no value at the fifth index, it will return NULL; it won't give us 0. So CHOOSE function helps us to select from a given range of values, like how we used to fetch the values from an array. So let's discuss the other logical function. So here, before we discuss the IIF, let's see these examples as well. So in the first example, we are using SELECT CHOOSE, and we are giving index 2, 'a', 'b', and 'c'; these are the three values. So this will—the first example will return the value 'b' in the result set because we'll count from the index 1, as I mentioned, the CHOOSE is based on one index and not the zero index. So let's take the case of the second example; here we have not provided an integer; we provide a fraction value 1.4. So CHOOSE only considers the integer value; in both the cases it will return 'a' in the result set. So now let's discuss the other logical function: IIF. So let's focus on the syntax first. So it's followed by IF keyword, and then we have a Boolean expression, and then TRUE values and FALSE values. So when we execute this function, it returns one of the two values; either it will return TRUE value or either it will return FALSE value. So the output, whether it is TRUE or FALSE, depends upon the evaluation of Boolean Expressions which will provide in the IIF function. So IIF is a shorthand way of writing a CASE expression; it evaluates the Boolean expression passed as the first argument and then returns either of the two arguments based on the results of the evaluation. So we can even provide nesting in the IIF functions; the nesting should be up to 10 levels, similar to the nesting which we can have in the CASE expression, as it is almost similar to the CASE expression. So let's see or discuss the example of IIF logical function. So in this case, it will return FALSE because this Boolean Expression is not satisfying; 1 is not greater than 10; so it will fetch the result FALSE in the result set. Let's execute this example in Management Studio. So let's write IIF; if then you have to write the Boolean expression; then any value; let's say I'm just writing TRUE; and the next value if it turns out to be FALSE. Let's see example… yeah, the example seems to be right; let me copy from here… okay, so we forgot to add the SELECT keywords; it's all about that; and if I'll execute it will return the FALSE. So since there is no header for the column name, we can provide an alias as well. If I'll make this statement as TRUE, if I—if I'll reverse the values here, then I will get TRUE as an output in my result set. So as I mentioned, IIF works like a CASE expression, and we can nest it; nesting can be allowed up to 10 levels. So this is all about logical functions. So let's continue with other categories of functions. So let's discuss about the math functions.

So math functions can be used to calculate business and engineering calculations. So these are various self-explanatory, and we must have used these functions during our engineering classes or any other classes where we do any engineering calculation. For example, when we convert it to an absolute positive value, then we use ABS function; if we want to generate a pseudo-random float values from 0 to 1, then we use RAND function; SEED is an optional value here; if you want to return an exponential value, then we use EXP function; in most of the mathematical values, we need to round up the values when the values are of decimal, then we use ROUND functions; so ROUND returns the numerical value rounded to a specific length of precisions that we need to provide in the functions; FLOOR provides or it returns the largest integer less than or equals to the specified numerical expression; then we have SQUARE ROOT; SQUARE ROOT returns the square root of the specified FLOAT value; CEILING is just opposite of the FLOOR, and it returns the smallest integer greater than or equal to the specified numeric expression; SQUARE again, and as we know the square of 2 is 4, so like we use the SQUARE functions to calculate the square of the specified FLOAT value; POWER; POWER basically returns the value of the specified expression to the specified power. So these are the standard mathematical functions; we have used these functions. So here we can see a consolidated examples of all mathematical functions. So in the first example, we see SELECT ABS(-10). So here we are using absolute value, so it is converting the negative values to the positive value, and all these keywords are—we are using as alias—so we are using ABS_ as alias for the first column; RAND, as we discussed, RAND is basically helps to—uh—get any random values; we can provide the SEED; SEED is optional when we use these functions. So as you can see, we are getting a random value here; EXP(4); it basically helps to get the exponential value; FLOOR; we use FLOOR, so it will get the value 4.66; will get the value 4 here; so FLOOR, we will get the value less than the nearest integer; in the CEILING, will get the values greater than the nearest integer; so if I'll use FLOOR(4.66), I am getting the value 4; when I'm using CEILING, I am getting value 5 here; SQUARE ROOT; the square root of 2.56 is 1.6; so this is the value we are getting; SQUARE is just opposite to the SQUARE ROOT; so we'll get the square of a digit which will provide in the parenthesis; so we have provided a value 4; so we are getting 16 as its result; POWER(2, 3); so we are basically giving power 3; the base value here is the 2, and 3 is its exponential value; 2 to the power 3 will get 8; it's—it's statement; if you want to expand this, it's 2 into 2 into 2; so we are getting 8 as its results; ROUND function is basically—is to round the values, and we are using 2 as a…

Precision value so we have provided so it is basically rounded up to 2.57. So let's execute few of the examples in management studio for better clarity.

Let's use the square function and square root function first. The square root of 16, and always use the select statement or else we'll get an error. So I can even do like multiplications of various uh I can use various mathematical functions and then I can multiply it, or I can use other operators like plus minus. So if I'll execute this, so what I'm doing is I'm taking the square root of 16, that will be 4, taking square 4 that is 16, so end result should be 64. Yep, so we get the result as you can see guys. When we don't give the name of the column, the header is blank, so it is good practice to provide the alias. As of now, I am giving a standard keyword visual set. If I'll execute it now, I'll get 64 instance value. I can even use other mathematical operators. I can use plus, so to provide the sum of these two values, 16 plus 420, so we'll get 20 in the result sets. I'm getting minus 12 its value, and let's see can we collect functions here. So let me write select, and if I use apps function here, so now I should be getting plus 12 because I'm using the absolute function, so it will convert the negative value into positive values. So we can use, we can club, we can nest the functions. So here in the apps functions I'm using sqrt functions and square functions. We can play around with these functions as per our business requirement. Let's use an example of power. Let's let's use the base value as 2 and 2 to power 4, so the result will be 16. So this is equivalent to, sorry, if I'll expand this, power 2 is the base and 4 is the exponential, so I'll get the same results as 16. So this is all about the maths functions.

Let's move to another category: ignore null values. Aggregate functions are frequently used with the group by clause and for a filtering like we used to filter the data using where clause. So if you are using Group by Clause, then we use having keyword to filter the result set. So we have a following aggregate functions: we have average, main, sum, count, and Max. So let's start with the average function first. So average returns the average of the values in a group, as we discuss, null values are ignored. So let's take an example of the average function first. Let me fetch the values from the Department table. Okay, so I I can use the average functions on the department number column. So I can write select average, I'll write the column number from Department. If I execute this, I'll get the average of the values. So let me execute both the queries in Funko so we can compare the results. So 25 is the average of 40 plus 30 plus 20, 10 divided by 4. So we can use average functions with a distinct keyword. We we discuss about the distinct keyword in module two. So distinct keyword helps us to fetch the unique records. So if you want to find the average of the distinct values, then we'll provide the distinct keyword before the column name. So let's take another example of the average function. Let me get the results from the employee table. So as we discussed that average functions ignores the null values, so if I try to get the average of salaries, so we have only three rows where the salaries present, rest all the values are null. Let's see what is the result. Select average, I'll provide the name of the column from employee. So this is the average. So let me execute both the statement in Funko like I did earlier. So you're getting the average of this. So we can use average with the distinct keywords if you want to fetch the results. Okay, let's see whether we can apply the distinct here. So in the department one table we have the repeated values for the Department number. So if I want to ignore the repeated or redundant data or the duplicate data, then I can use the distinct keyword. So if I execute it now, I'll get the average as 25, but if I'll remove the distinct keyword, the result sets will be different. Sorry, my bad, I'm using Department column, I have to change it to Department one. So let's first see the result set without using the distinct keyword. The result is 30. Now I'll use the keyword distinct, so the value is different because I'm just taking the unique values for my result set.

Let's move to another aggregate function. Let's discuss the Min function. Similar to average, Min also ignores the null value and it returns the minimum value in the expression. So if we'll see the values in the department one table and if I try to find the lowest value of the department number, then I have to use the Min function. Okay, so out of all the aggregate functions, count is the only one which considers, which takes into account the null values as well. So let's see the example of count. Let's move to management Studio. So I'll be using the employee table because we have a lot of null values in those like secret this. So let's take the count of the salary column. Select count, I have to write the column name employee. So if I'll execute, I'll get three results, but if I execute star, I'll get nine columns. So even we can use the distinct operation here in the count function. So count basically fetches the count of rows from a table. So let's move to another aggregate function. We have Max. So Max is exactly opposite of Min. We have already shown an example of minimum. So Max, we can use it for numeric as well as with the character data type. If we use for the character data type, it will show the maximum value in the sorting order. If you use with the numeric, then of course it will show the maximum of the value though. Let's see an example of Max as well. So if I'll use Max, we're trying to find the maximum salary from the employee table. So this is the maximum salary, and if I try to find the location, let me first show you the various location from the Department table. So as per the sorting order, we should get Hyderabad if if we'll use Max for this column. So let me write the query: select Max Loc from Department table, and we can provide an alias as location. So I'll get Hyderabad in my result. So we have discussed all aggregate functions. So the common aggregate functions are: average, if you get the average of values; Min, as the name suggests, the minimum value in the expression; sum helps us in finding of the total for a column, sum only accepts the numeric value; count returns the number of items or rows in a group or in a table; Max returns a maximum value in the expression. So let's move to other categories of functions. So these are the various examples before we move to other functions. Let's read the examples here. So in one example we've shown all the aggregate functions. So we can use multiple aggregate functions in the single statement, a single select statement. So in the single select statement we have used average of salary, minimum of salary, maximum of salary, and sum of salary from the employee table. Second example is for the count functions. So we will discuss about the group functions and having functions once we are done with uh most of the out of box functions. Then we have string functions. String functions are again scalar functions and they perform an operation on a string input value and the return string or numeric value based upon the type of functions which we are using. When string functions are passed arguments that are not string values, the input type is implicitly converted to a text data type. So these are the various string functions: Ltrim, it basically returns a character expression after it removes leading blanks; it basically removes the blanks from the left hand side of the string; we have Rtrim, it returns the character string after trimming all the trailing blanks, basically it removes the blank from the right hand side of a string; Char functions converts an INT ASCII code to a character; Charindex finds out and searches an expression for another expression and returns its starting position if found; Str returns character data converted from numeric data; Concat returns a string that is the result of connecting two or more string values. So these functions are almost similar to other string functions which we use in other programming languages. So most of the programming languages we have trim functions, we have uh functions to find out the index of a character, we use concatenation operation. This is a very common uh string function to connect two strings or more than two strings. Then we have replace functions: so replace all occurrences of a specified string value with another specific value; we have substring, it returns part of a character or text based upon the length or the start index which we give in. As we can see in the syntax of the substring, we have a substring a keyword followed by the expression like the string from which we want to find out the part of a character. We'll define the start index and then we'll define the length from start index till how many characters we want to fetch the substring. Then we we have the format functions. We can format strings in the desired format using the culture. Then we have left functions, it returns the left part of a character string; the opposite of left is the right functions which returns the right part of a character string; Reverse returns the reverse order of a string value; Upper functions converts the string into uppercase; a positive which is the lower functions which converts the expression into lower case; and in the end we have length function or Len which basically returns the number of characters of the specified string and it excludes the trailing blanks. So these are the various examples on our slide. So first one is for the replace function. So this is our string and this is string we are replacing CDE with XXX as a replace. So as you can see in the result set here for the replace column, the value CDE is replaced with triple X. We have substring functions. In the substring we are getting out of this ABCDEF which is our main string from index 2 and till length 3 we are getting the substring. So index 2 is start from B and then up to three characters we'll get the substring. So we'll get BCD in our output. Then we have left, so it basically returns the left from a character index. So from index 2 we are getting the values from the left, so it is A and B. From the right we are getting the value of BCD. So in the end we have the examples of date and time and format. So here we have provided the various uh cultural values. So first is for our US English, second is for British English and third is for the German. So based upon the info culture we basically get the different results here. So most of the string functions are pretty much straightforward. So let's discuss about few of them. So we'll discuss about Reverse. I'm adding a string ABC. Again I forgot about the select statement. This will give me an error if I'll try to execute this statement without select, and if I'll execute it now I'll get the reverse of the string. Always good to provide alias. Then we have trim or Ltrim. Select Ltrim. So I have added uh leading blank spaces in this string and if I'll execute this, the leading spaces has been trimmed. Same way I can use Rtrim. So if I'll use Rtrim, then only the trailing spaces will be removed, not the leading one. If I'll execute this, I'll get this result, and if I'll use trim, that will consider for both. We do not have trim here, so Ltrim removes the leading spaces and Rtrim removes the trailing spaces. So this is all about the string functions. You can practice about the other string functions, they are pretty much straightforward. Let's let's see an example for the upper and lower functions as well. So if I use lower here, I'll get the same result, but if I'll use or let me convert, let me first write the uppercase character, so it's convert into lowercase, and if I'll write the lowercase, if I'll use the upper function, it converts it into uppercase. So all other streaming functions are also self-explanatory. Please try all of them so that you will have an idea, and if you will trial all of these, you you will come to know that if the situation arises you can start using those.

Let's move to other functions, the date and time functions. So date and time functions are again scalar functions that perform an operation on a date and time input value and retains either a string, numeric or date and time value. So as you can see in the screen there are various date and time functions. Again we have Getdate, it returns a date time value that contains the date and time; its current timestamp again returns a date time value that contains the date and time; Datepart basically fetches the date part of a date component, day, month, year returns an integer that represents the day, month and year part of the specific date; Datediff returns the number of date or time date part boundaries that are crossed between two specific dates; and Dateadd functions returns a new date time values by adding an interval to the specific date part. So let's see the examples of date and time functions. This Getdate, it returns the system date times, it has date component as well as the time component. Current timestamp also gives the current date and time. Datepart basically provides, if it will provide YYYY here, then it is providing the year of the date part; if I'll provide here the DD, it provides the day; it will provide MM, it will provide the month value of the month. Datediff, so again if we are providing MM, so we are getting the difference of month between these two dates; if I'll provide DD, then it will provide me the difference of days between the two dates. So Dateadd is that I am adding two months. So this is how we have to do, since we have provided MMM, specify for month here; if I'll provide the DD, then it will add two days. Since we have provided MM here, so it will add two months to the current date. So let's see one example here, Datepart here, let's say MM and then we can provide the date. This is returning the month, so 12 months, since I'm using December. If I change it to October and if I'll execute again, it will show me that value 10. So this is how we use the Datepart, and let's see the Dateadd function. So if I execute it now, it will add two months. I can also provide DD here, it's like two days. So this is all about the date functions.

So now let's discuss about the group by clause and having clause. So as you can see we are using Group by keyword here and we are using having keyword here. So let's discuss about the group by and having clause. Let's discuss Group by first. The SQL Group by Clause is used along with the group functions to retrieve data grouped according to one or more columns. The important part here is that the group by Clause should contain all the columns in the select list except those used along with the group functions. So let's see an example of group by functions for better understanding. Let's move to management Studio and we will use the Department one table for group by clause. Let me first execute this query. So what I'm going to do, I'm going to group by the department number. So I'll find select count of rows from Department one, then I'll use Group by keyword and I want to group the data by Department number. So can you see it's grouped, or even I can write the department number and let me write the alias for this and I'm writing the alias here as Department number. If I'll execute this, I'll get, so we have count four for the department number, there are four values for the Department Number 20, same way five values for department number 30, five values of 40, one values for department number 50 and one value for department number 80. So we use Group by functions generally in association with aggregate functions, so it helps us in grouping the data in a table. The important part here is that we have to use all the columns in the group by which are there in a select statement. So if if I'll try to include location here, there's one more column locations in the department one table, but if I try to execute it now I'll get an error because all the columns other than the aggregate functions should be there in the group by clause. So if I'll include the other table as well, then the query will be executed successfully. So to in order to execute Group by successfully, we have to include all the columns which we are including in the select statement in the group by clause, and also we can include multiple columns in the group by Clause. It is not that we have to use only the single column. So Group by helps us to group the data in a single table and it is generally used along with other aggregate functions. So let's see the example. So here we are basically again uh grouping by the department number here. So let me fetch the results from the employee table. So here we can group the records again using the department number or using the job ID. So I'll use for the employee table, I'll write select job ID, job_ID and then again I can use for example, let's say count, it's not that we have to always use the count aggregate function, we can use other aggregate functions also from employee and then I'll write Group by job ID. So this will group the data according to the job. So only for a job ID 7 we have two rows, for all other job IDs we have a single row. So we are clear with the group by now. Let's discuss with let's discuss the having keyword. So the having Clause was added to SQL because the where keyword could not be used with the aggregate function. We cannot use a where keyword with this aggregate function. So having applies to the summarized group records whereas where applies to the individual records. So if it is a summarized record or the group we use Group by, then we have to use having, and if it is the individual records then we'll use the where clause. So if we'll use the having clause, only the groups that meets the having criteria will be returned in the result sets, and having keyword requires that we'll use Group by in our SQL query. So we can say that the having Clause is used in combination with the group by Clause to restrict the group of written rows to only those who whether to only those which is matching the conditions or where the conditions is true. So let's see an example. So here in this example we are selecting the department number, taking the average salary, minimum salary and the maximum salary and and we are finding that if the having the sum of the salary is greater than 3000, it touches only those results. So let's write uh let's see this example in the management Studio and I can write here having salary greater than let's say 30000. Oh, we have to include the where the minimum salary, you have to use the aggregate functions in the having clause. Yeah, so we get only two results. So let me first show you the result sets. So we have uh three rows which are having the value for the salary column, J4 having salary of 40000, J5 is blank, so we have J6 as 500000 and then we have J1 as 30k. So as per our query we should get only the two results that is J4 and J6 because these are the only two rows which are satisfying the having Clause. So having is kind of we used to filter the result sets, but with the aggregate functions we cannot use where command, so we are supposed to use having Clause. So this is it about the various out of box SQL functions and first we will discuss about the store processor. A stored processor is a set of SQL statements with a name that has been created and stored in the database. So when the execute or when we write SQL statement but we are not storing those queries, but in store procedure we can write a set of SQL statements and we can you know execute them and they can store it in a server. So every time I don't have to write SQL queries, I can write my business logic in the store browser. So stored procedures can be defined as a set of logical group of SQL statements which are grouped to perform a specific task. So basically in stored processor we write most of our business logic. It's

Like other programming languages, stored processors accept input parameters. They return multiple values by means of out parameters or output parameters. They contain programming statements. A store processor can call other store procedures or functions. A written status indicates success or failure.

Let's see the syntax of a stored processor first. So this is the syntax we have: the `create` keyword to create a store procedure. We have to write `create` followed by the keyword `procedure`, the name of the store processor which we want to create. If you want to provide any parameter in the store processor, then we will provide the parameter name. If you want to create the parameter as the output parameter, then we have to use the keyword `out` or `output` followed by the `as` keyword. We'll write `begin`, and whatever the statement or computations we want, we'll write that. In the end, we have to write the `end` keyword.

So in the syntax, it is mentioned that it is `create` or `alter`. If we want to modify the existing stored procedure, then we have to use the keyword `alter`. If we are creating the stored procedure for the first time, then we have to use the keyword `create`. So the `alter` keyword is used if you want to modify any existing store processor.

Now, why do we create store processors when we can write SQL queries? Here are some of the benefits of creating stored procedures: all commands in a stored processor are executed as a single batch of code. When we execute queries in SQL, generally each query goes as a single batch. But when we execute a store processor, though it may have multiple SQL statements, all SQL statements are executed as a single batch of code. So by doing this, it reduces the server or client network traffic and improves the performance.

Store procedures help us in achieving strong security in SQL because we can impersonate another user. `EXECUTE AS` can be specified to enable impersonating another user to perform certain database tasks without providing direct permissions to the processor. So it makes our environment more secure.

Reuse of code: store procedures help us in achieving reusability because, as we discussed in the previous slides, we can call other functions or store procedures from one store processor.

Easier maintenance: changes need to be done within the store processor which handles all DB operations, and no changes are required in client applications. So sometimes we move our business logic to the store procedure. So if any changes are required, we need to modify our business logic; then we don't have to change our client applications or our code. We have to just modify the store procedure and execute it again. Also, if there is any error, we know where exactly to look for, and we have to debug only one store procedure instead of looking for multiple SQL statements. That is the reason store procedures are easier to maintain.

Improved performance: all procedures, by default, are compiled in the database the first time it is executed, and it maintains the execution plan for subsequent calls. So if we execute or it will call or run the store procedure again, it will take less time because it is already compiled in that database the very first time. So by doing this, the performance of applications has increased.

On this slide, we can see an example of a stored procedure. So we're creating a store processor. So we have written our first `create` keyword followed by the procedure `SP_get_employee_info`. This is the name of the store processor. This store processor, we are passing a parameter `employee_ID` whose data type is `int`. Followed by the basic syntax, we are defining the keyword `as` in `begin`, and then we are writing the basic query that `select employee_ID, first_name, last_name, manager_ID, phone_number, hire_date, job_ID`. These are the columns of table `employee`, and then we are passing the condition; we are filtering the records from the `employee` table by using a `where` clause, and in the `where` clause we are not hard-coding any value; we are equating it with an `employee_ID`, which is the parameter. So when we will execute the store processor, we will pass the parameter.

Let's see an example of the store procedure. So let me open Management Studio. Let me open the examples I already have. Let's create a store procedure without a parameter first. It is not that every time when we create a store processor we have to define a parameter. So I'm writing the `create` keyword followed by the `procedure`, and all result keywords will be highlighted in blue. Now, importing a name of the store processor, so I can provide any name here. So I'm providing `get_details`, or I can mention it to give it more meaning: `get_Department_details`. In the store procedure, I have simply written a one `select` query that `select * from Department`. `execute` this query; command completed successfully means we have successfully created the store procedure in the database.

Now, where to check for the store processor? So I'll first expand the database under which I am creating the store procedure. An important thing, guys, is that we have to use the database first, that under which database we want to create our store procedure. So always write the name of the database, `use` keyword followed by a `GO` keyword. Now, if we'll try to execute this statement again, I'll get an error that this is already an object name `dbo.get_Department_details` in the database. Since I've already created this store processor, I will try to create it again; it will give an error. So when you provide a name of the store processor, please ensure or please check that the name which you are providing is unique and it does not exist in the database in which you are creating that stored procedure. So if I want to check where exactly the stored procedure has been created, I have to expand the programmability folder. Under the programmability folder, we have a separate folder for the store processors. Let me refresh it. So here we can see the store procedure `dbo.get_Department_details`. From this object explorer, I can modify the store procedure; I can execute the store processor or even I can delete it. So to delete it, we have to simply click delete here. It will again reconfirm whether we actually want to delete this store procedure, and if there are any dependencies of the store procedure, we can check it with the `show dependency`. When we delete something from our database, it is better to check the dependencies. If there are dependencies, we rather not delete that particular object. As of now, we know that there's no dependency, so I'm just clicking OK here, and it will delete the store procedure. Since we have deleted the store processor, and now if I'll execute this statement again, it will be executed successfully as there was no store procedure in the database, and by execution, the statement will again create the store procedure. So if I refresh this store procedure again, I'll see the stored procedure.

Now we have created the store processor, and we'll see how we can execute this store processor. To execute the store processor, we have to write one command. So there are various keywords which we can use to run this store processor. The first one is we have to write this keyword `exec` followed by the name of the store processor. So if I'll execute this, it will execute the store processor, and it will return this query or this result set because in the store processor we have given only one `select` statement that `select * from department`, and the `department` table has three columns, so we are getting all the rows because we have not specified any `where` condition. So this is an example of a store processor without a parameter. Since the stored processor doesn't have any parameter, we are not passing any parameter while executing this stored procedure. It is not mandatory to provide the `exec` keyword while executing the store procedure. Even if we will provide the name of the store procedure and if you'll execute it, it will fetch the same results. The `exec` keyword or `execute` keyword is optional while executing the store processor. So let me again delete this store procedure. So while creating the store procedure again, we can either provide `create procedure` or we can even provide the short form that `create proc`. Even if I'll execute this statement, it will be executed successfully, and if I'll refresh this node, we can see the store procedure has been created successfully. While executing again, it is optional to provide the `execute` keyword. Similarly, while creating the store procedure, we can either provide `create proc` or `create procedure`.

Now let's see how we can create a store procedure with a parameter. So I'm opening a new query window and press the font size for better visibility. So this is an example of a store procedure with the parameter. So here we are providing the parameter `department_number`. Here we have `department_number` as a parameter, and the data type of this parameter is `nvarchar` and length is 30. So in the previous example, we have written a `select` statement but without the `where` clause. Here I am providing or I am filtering the record or rows by using a `where` clause, and in the `where` clause, I am checking the `dept_number` with the parameter which will pass while executing the store procedure. So let me create the store procedure first, and then we will execute it. The command completed successfully means the store procedure has been created successfully. So let's again refresh this node. Yeah, so now when we are executing this stored processor, even like as we saw that we can provide the `execute` keyword or we can even directly write the name of the store procedure, or if you are using Management Studio, we can right-click the store processor and then we can click execute store processor. So the execute store procedure will open this window, and if there are any parameters, it will pass; it will check whether what value we want to pass to this particular parameter. As we know that we have various values of `department_number` starting from 10 to 80. So I am passing 20 as a value for the `department_number`, and I will click OK. The moment I'll click OK, I'll get this result. In an earlier example, we got all the rows in the result set. So if we do not want to execute the store processor from the object explorer, then again we have to write the same command. We have `execute` keywords followed by the name of the store processor, and then we'll pass the parameter. In our case, the parameter is `department_number`. So now this will give the desired result. So this is how we create a store procedure with a parameter, and this is how we execute the store procedure which has a parameter in it. Now if you try to execute this store procedure without providing the parameter, now let's see what happens. See, you will receive an error: the procedure or function `dbo.get_detail` expects parameters which was not supplied. It means when we created the store procedure, we have ensured that the parameter which we are providing in a store procedure is mandatory, why? Because we have not explicitly or defined that this parameter can accept a `NULL` value as well. So if we want to make the parameter `NULL`, then we have to explicitly provide the `NULL` keyword. So let me modify this store procedure, or let me first delete this store procedure, and we will recreate it again. So I'm just deleting the store procedure, and in order to make our parameter optional instead of mandatory, we have to provide the keyword `NULL`, and I'll execute the statement again to create the store procedure. Now if I'll execute this store processor, you won't receive an error, but we won't get the value because we are checking the `NULL` value, and if it is not provided as `NULL`, so it will not return any result, but yes, the error is gone. So this is how we make the parameter optional by providing the `NULL` keyword.

Now let's see how we can create a store procedure with multiple parameters, or is it possible to create a store procedure with multiple parameters? Yes, it is very much possible to create a stored procedure which accepts multiple parameters. So let's see it with an example. Let me open a new query again, and we already have an example handy with us. Let me paste it in Management Studio. So we have this stored procedure, and here in this store procedure, we have defined two parameters: one is `department_number` and `department_name`. We have made both of these parameters as optional by providing the `NULL` keyword. So if you want to create or do you want to define multiple parameters in the store procedure, all we have to do is that we have to separate the two parameters with a comma, that's it. Rest everything is the same; we have to provide an `as` keyword after the parameters, and then we'll write the procedure body. In here, we are again writing a `select` statement, but we are adding a `where` clause to filter the result sets by providing two conditions, and we are using a logical operator that is `AND` to combine two conditions. So let me execute these statements to create a new store procedure with multiple parameters. The store procedure has been created successfully. We'll refresh this node, and this is the store procedure. So let me first see the data in our table so that we can provide the right parameter values to get the values in the result set. Okay, so I'll pass the parameter `department_number` as 50 and `department_name` as `IT`. All I have to do is I have to provide the keyword `execute`, the name of the store procedure `get_details_from`, then we have to provide the value for the first parameter that is `department_number`, its value. So we have decided to pass its value as 50, and then we'll provide the value for another parameter. Since it is a string, we have to enclose it in single quotations. And now I'll execute this, and we'll get the desired result that the `department_name` is `IT`, and it's located in Mumbai. So this is how we'll execute the stored procedure with multiple parameters. So we write the name of the store procedure and follow the first parameter, then write a comma, and then the second parameter, and so on. Parameters are also in other store procedures. If you want to execute it from the object explorer, then you have to right-click the store procedure and click execute store procedure. And get both the names; we'll pass the value here, and we'll click OK. If I'll click it OK now, though there won't be any result in the results, then but it won't throw any error because while creating the store procedure, we have defined that these two parameters can accept `NULL` values, so they are not mandatory; these are optional. That is the reason even though we will provide any value, we won't receive one while executing the store processor.

Now let's discuss about the output parameter in the store procedure. So if we want to return the value of the parameter, then we have to define an extra keyword, that is `out` or `output`. Both keywords are valid; whether we use `out` or `output` against the name of the parameter whose value we want to return. So let's see it with an example. So I'll open a new query. In the store procedure, I have two parameters: one is the `department_number` and one is `count`. We have defined a keyword `output`, which suggests that this parameter will be the output parameter. So we can pass the value to this parameter, and this parameter will also return the value after execution. So we can provide the keyword `output` or `out`; there's no difference; the end result will be the same. The stored procedure is created. We'll refresh the node of the store processor to see the results. Yep, we have the store procedure. Now, in order to execute this, we have to do like this: we have to first declare the `count int` followed by the `execute` name in the store processor; we'll provide the value. This is how we have to define if it is an output parameter, and then we are writing the `select` statement to see the value of the `count`. Let me execute this. So the `count` is 1 because there is only one row with the `department_number` 10. So this is how we use the `output` or `out` keyword against the parameter.

Now let's see how we can add comments in the store procedure. So we can add comments in two ways: one is the line comment and one is block comments. If you need to provide line comments, then we have to use two dashes followed by a statement. And in order to -- forward slash and then stop. In this writing, this is a multi-parameter stored procedure having an output parameter. Again, we write `/*` and a forward slash. So this is how we define the comments in a stored procedure. Note that in stored procedures, we can write or define the comments anywhere in our SQL queries, whether it is functions or normal SQL statements or it is a stored procedure. So line comments or single-line comments, we use two dashes, and for block comments, we use forward slash and star.

Let's see how we can handle the exception in the store procedures. If you have handled the exceptions in your programming languages like C, C++, or like Java or C#, then we use `try-catch` there, and along with `try-catch`, sometimes we use a `finally` block because `finally` always executes. So if you want to close some, like we want to close some connections, or we want that some statement to execute no matter whether there's an exception or not, then we write those statements in the `finally` block. So we do not have any `finally` block in the store procedure or SQL. Let's see how we can define the `try` and `catch` blocks in a store procedure with an example. That we first increase the font size. I am creating this store procedure with the name `dbo.try_catch_test`. To write a `catch` block, we have to provide the syntax `BEGIN TRY`, then in the body, we'll write whatever the statement we want to write, and then followed by the `END TRY`. `END TRY` basically ends the `try` block. After that, we'll provide `BEGIN CATCH`, and in the `catch`, see what we are doing here is that we have written a `select` statement that we are providing: what is the error number, what is the severity of this error, what is the state, the procedure in which line the error is encountered, and the error message. Let's create the store procedure first, and then we'll refresh this node. So we have this store procedure, and now the store procedure did not have any parameter, so I'll execute this store procedure: `execute` keyword followed by the name of the store procedure; no parameters, so we are not passing any parameters while executing it. And see, since we are dividing by 0, it will give an error; it will result in infinity. And see, since it will go to the `catch` block since an error has encountered, so we have written the statement in the `try` block. So in the `catch`, we are handling the exception, and while handling the exception, we have written a `select` statement which provides all these values. So the error number is 8134, error severity 16. So these are the, you know, predefined severity levels. So we can check on Google what the severity error severity 16 means. Then we have error state, in which procedure the error has occurred, so it will give you the name of the procedure; the name of the procedure is `dbo.try_catch_test`, line 4, and the error message that we are dividing by 0. So we'll get the message that divide by zero error encountered. So this is how we mention a `try-catch` block in the store procedure. We have seen various examples of the store procedure. So we have created the store procedure without a parameter, with a parameter; we have created a store procedure with multiple parameters; we have seen that how we can, you know, include comments in the stored procedure using single-line comments or block comments, and we have seen that how we can handle the execution of the store procedure, so this exception handling is not only for the store procedure; we can handle these exceptions in functions as well. So we can write a `try` block and followed by a `catch` block. In the `catch` block again, we can write the `select` statement to show the message that where exactly what is the severity level, what is the error message; we can even provide custom error messages, up to us. Let's move to the next topic. So I hope you are cleared with the concept of store procedures in SQL. Let's move to the next topic. The next topic is user-defined functions. So though SQL Server provides a list of many predefined functions that are built into the T-SQL language, these supplied or out-of-box functions help in extending the capabilities of SQL by providing the ability to perform like string manipulations, mathematical calculations, data type conversions by using converter cast functions, etc. But sometimes these out-of-box functions or inbuilt functions are not enough, and there are certain functionalities which are not provided by these functions. So this issue can be easily addressed if we can create some user-defined functions. So like functions in programming languages, and all programming languages, we write functions. There are some functions which do not return any values; they are functions which return a value.

And we pass parameters; we do not pass parameters while you know calling the functions. So user-defined functions in SQL are almost on this same lines of the functions in other programming languages. So user-defined functions are compact pieces of transact SQL code which can accept parameters, like how we pass the parameters in stored points; the same way functions can also accept parameters. Functions can perform complex calculations and return either a value or a table. So this return type is basically based upon what kind of functions we are creating or executing.

So let's discuss what are the various, uh, benefits of user-defined functions. So again, like stored processor functions, they also help us in achieving the concept of reusability. It will prevent us from writing the same logic multiple times. We can dump a set of SQL statements in a function, and then we can call it as many times as we need, like store processes. They also improve performance because the user-defined function reduces the compilation time of SQL queries by caching the execution plan and reusing it. Functions are also easier to maintain because functions help us to separate the complex calculations or the complex business logic from the regular SQL query, so that we can understand and debug the query quicker and better. It again reduces network traffic because of its caching plan. Functions again can be used in WHERE clauses as well; by this, we can limit the number of rows sent to the client. So we can use functions in SELECT clauses, and we can use the functions in WHERE clauses.

Now let's discuss the structure of the functions. User-defined functions are composed of two parts: one is the header and one is the function body. We'll see in awesome examples how we create functions. So the header contains the function name, input parameters (if there are any input parameters), because again the parameters are optional, but in the stored processor or whether it is a user-defined function, along with parameters we have a return parameter info, its name and type in the header section. The function body contains the logic and business logic; so it contains one or many SQL statements, depending upon what we are writing in the function body. As you can see on the screen, there are—if you need to divide the user-defined functions into some broad categories—then we can divide them into two broad categories: one is the scalar value functions, and one is the table-valued function. The table-valued function can again be divided into inline table-valued functions and multi-statement table-valued functions.

Let's move to the next slide. Let's first discuss what are the scalar functions in SQL. Scalar functions return a single data value of the type defined in the RETURN clause. If it is a nice scalar function, we even don't need a function body. We use scalar functions when multi-statements need to be provided within a BEGIN and END block.

So let's discuss the syntax. As I mentioned, the syntax contains the header and body. So the CREATE/ALTER function, which is basically the header of the functions; in the header, we can define the parameters, the return type parameter, and then in the BEGIN and END, we define the function body. What are the SQL statements or any computations or calculations which we are doing? You basically do it in the body of the function. So if we need to summarize, scalar functions are functions which return a single value; they return scalar values, single values that can be used anywhere a constant expression can be used. And every function, whether it is a scalar or whether it is like table-valued functions, every function must return a result using the RETURN statement; this is kind of mandatory.

So let's see some examples of the scalar functions. So in this example, we are creating a function with the name FN_getDepartmentNumber. So we are creating a parameter, employeeID, of the data type INT. This function basically returns an INT data type. Then there is a BEGIN keyword. After the BEGIN keyword, we are defining the body. In the body, we are writing SELECT departmentNumber FROM employee WHERE employeeID = @employeeID, where @employeeID is the parameter which we will pass when we execute this function or we'll run this function. So on the right-hand side, we are executing this function, and we are executing these functions in the WHERE clause; just pay attention. So in the WHERE clause, we are mentioning WHERE departmentNumber equals to, and then we are calling the function by providing the parameter. So when this function will execute, it will be replaced by the value which the function will return, and then that value will be used in the WHERE clause to filter the data.

So let's discuss some examples of functions for better clarity. Let me open Management Studio. Let me close these queries first. So we'll first create a function, a scalar function without any parameters. So this is the name of the function. Now parameters—we are not creating any parameters here. The RETURN type is INT, and I'm just returning—in the RETURN statement, we have just provided a SQL statement that selects some salary from employee. After executing this function, it will be created. This is a scalar function. So if you want to verify whether the function has been created successfully, then we have to refresh our database. So we have created this function in the employeeDB database. I'll refresh that, and I'll expand the Programmability. In the Programmability node, we have a sub-node called Functions. Again, in Functions, we have four nodes: Table-valued functions, Scalar-valued functions, Aggregate functions, and System functions. If I'll expand the Scalar-valued functions, we can see the name of the functions here. So in order to execute this function, we have to write a SELECT statement followed by the name of the function and try to execute it. We have provided the parentheses. So this function will return the sum of the salary from the employee table. So let me show you the data which is there in the employee table, so that we can verify our result, whether we get the right result or not. So if you calculate this, we'll get 570K. This is the sum of the salary for all the employees. Since we have salary for three employees only, this is how we'll create the functions without any parameter.

Let's see how we can create functions with parameters. So in this function, we are providing two parameters: firstName and the data type of the parameter is VARCHAR(50). The second parameter is the lastName, and the data type of the second parameter is again with the same length as of the first parameter. The RETURN type is also of the same data type, and then in the body we are executing the SQL statement. So what we are doing? We are just concatenating. So if it is a mathematical operation, if you provide the plus operator, then we'll add the two values, but if it is a string or VARCHAR, then it will connect the string. SPACE is a function, and it is an inbuilt function in SQL which basically adds a space, an empty space. So what we are doing? We are concatenating firstName and lastName, and we are adding a space between the two names to make it more readable. So as you can see, when I hover over the SPACE keyword, it is giving me a message that this is a built-in function. So let me create this function first. The function has been created. Again, this is a scalar function, but with parameters. Let me refresh the Scalar-valued function node, and I can see the function name. Let me execute this function: the name of the function, and then we have to pass the parameters. So I pass two parameters here, comma, and the name of the second parameter. Why I'm enclosing it in single quotes? Because this is a string type, and if you want to add aliases for the column name, we can mention it as fullName. So if I'll execute it again, you'll get the result "U root" here. So this is how we'll create functions with multiple parameters, and we can call the functions in the SELECT statement, or we can—sorry, when we call in the SELECT statement, right—and we can even call the functions in WHERE clauses, as we saw in the example in the PPT. Again, in the previous example, let me first increase the font size. We can even use the functions in the WHERE clause. So how we can use it? Let's assume I'm calling this query: SELECT * FROM employee, and let me first alter this function. So to alter this function, we have to use the ALTER keyword, and instead of SUM, I am just finding the average salary of the employee. Then I'm executing again. So this is how we modify the function, the existing function. The same way we can modify the stored processor also. So ALTER is the keyword which helps us to modify the existing functions as well as existing stored procedures. If I have to use the functions in the WHERE clause, so this is how we'll do. Let me show you. So I'm writing a query. So what I want to do is that I want to select the employees whose salary is greater than the average salary. So I'll write a WHERE clause: WHERE salary >, then I'll call the function. So if I execute it now, I'll get only one result because there's only one record of one employee whose salary is greater than the average salary of all the employees. So this is how we can include or we can call the function in WHERE clauses as well as in the SELECT statement as per our business requirement.

So let's move to the next topic. So we are clear with the scalar functions, I believe. So let's move to the next type of function, that is the table-valued functions. And as I mentioned earlier, we have two types of table-valued functions: one is inline, one is multi-statement. So inline table-valued functions are a subset of user-defined functions that return a table. So scalar functions return only a single value, whereas the inline table-valued functions return the entire table. So inline functions—if you remember, we have created views in a first module—so we can use inline functions if you want to achieve the functionality of parameterized views. An inline table-valued function can also be used to support parameters in search conditions specified in the WHERE clause. So these are some of the rules which are common for the inline table-valued functions. The RETURN clause contains only the keyword TABLE. The format need not be defined for the return value. There is no function body delimited by BEGIN and END. The RETURN clause contains a single SELECT statement in parentheses, and the table-valued function accepts only constants or local variable arguments. This is the syntax for the inline table-valued functions, as you can see on the slide. So the return type is TABLE here, and we generally have the SQL statement. This is an example. The last slide we saw the syntax; this is the example. So here in this example, we are creating a function, getEmployeeInfo; we are passing the parameter employeeID, and it is returning the values as a table, not as a single value. And in the RETURN statement, we are providing the SELECT statement where we are returning the values of the employee table, and we are filtering the result set by using the parameter employeeID. And this is how we'll execute it. So if you remember when we executed the scalar-valued function, please don't use SELECT * FROM; we simply mentioned SELECT and the name of the function, but if we are using a table-valued function, then we are using the SELECT * FROM because we—we are kind of—as you mentioned, we kind of use it for parameterized views. So if you need to fetch the values from views, then again we use SELECT * FROM the name of the view.

So let's see an example of an inline table-valued function. Let me open Management Studio. So this is an example of inline functions with no parameters. We can create parameters in the same way we created the parameters where we define the parameters for the scalar-valued functions. So I'm creating a function, top10Customers; we are returning a table, and in the RETURN statement, I am just writing a SELECT statement: SELECT TOP 10 FROM employee. Let me execute this to create this function. Now execute this function. So to execute this, I have to mention the SELECT clause: SELECT * FROM, and then the name of the function. So I am getting—so there are only nine rows, so it's just fetching the nine only. So if I can go ahead and modify it, instead of TOP 10, let me modify it to TOP 5. So to modify the function, we have to use the ALTER keyword. So we've got the top five results. This is how we create the inline table-valued function. So this is an example of the functions without any parameters. If required, we can go ahead and create a parameter as well. So to create the parameter, we have to define the parameter name here, and then we can—we have to provide the name of—sorry, the data type of a parameter, and then we can write a WHERE clause. Now let's say WHERE employeeID = @employeeID. Command executed successfully. And now if I run this, I'll pass a value to the function. If I'll execute it, it will get the values in the result set whose employeeID is greater than 1003. I hope this is clear, and let's move to the next topic. So we'll discuss the next category of table-valued functions, that is the multi-statement. So in the inline function, we can use a single statement, but in multi-statement table-valued functions, we can use multiple statements. So again, they also return a table data type. So the RETURN clause defines the format of the table. We cannot provide the format in the inline table-valued function, but yes, we can provide the format of the table in multi-statement table-valued functions. The Transact-SQL statements in the function body build and insert rows into the RETURN variable defined by the RETURN clause, and the rows inserted into the variable are returned as the tabular output of the function. So here we have the syntax for this. To modify, we use ALTER keywords; to create, we use CREATE keywords. The name of the function—if you wish, we can define the parameters which you can consume in the function body. The RETURN type will always be TABLE, but here we can define the format, which is not available in the inline table-valued function. Let's see an example. So this is an example here. So we are defining the format of the table in—we are defining like that—this is the table will be getEmployeeInfo, and we are providing four columns here, and we are defining the data type; we are defining the constraints on the table; we are defining or whether there is a NULL constraint or not on those columns. And in the function body, we are inserting records in the table and we'll fetch from the employee, and we are filtering the result set by using the parameter which will be passed, then we'll execute the function. So let's see one more example other than this. So you can use the same example and execute it. We'll try to write the entire thing; then it will take time, so I'm skipping the example in Management Studio, but the basic difference between these two functions, table-valued functions, is that here we can format the table, and we can use multiple statements in the function body, which is not the option in the inline functions. So we already discussed the benefits of user-defined functions: modular programming; it saves time because we can write or dump the statements in a function and use it or call it as many times as needed; it's cost-effective execution because of its caching of the execution plan and using it for subsequent calls; and it reduces the network traffic. So these are a few of the main benefits of user-defined functions. [Music]

Now let's come to our topic, that is SQL versus MySQL. So as the first topic of comparison, we have the definition. So what is the definition of SQL? SQL is the standard language for operating, managing, and accessing databases. Now let's see what is the definition of MySQL. So MySQL is a relational database management system for storing, retrieving, modifying, and administering databases.

Next point is history. So for SQL, SQL was born in 1970 as a programming language known as SQL. It was developed by Microsoft Corporation, but now it is also known as SQL. While MySQL claims to be the first open-source relational database in the early 1990s, it was developed by MySQL AB and is currently owned by Oracle Corporation.

Now looking into the complexities, to use SQL efficiently, you must first learn and then grasp the language to start working with SQL. While for MySQL, you can easily access it by downloading and installing the same.

Now coming to the usage, SQL is a programming language, so it can be used by querying and operating. While MySQL allows for data manipulation, storage, modification, and deletion in a tabular format.

Now the syntax or format. So SQL is a programming language, as we all know. Now the syntax and format are fixed; it's declarative and easy to use; it starts with a clause and ends with a semicolon. While MySQL is a software and it is not a programming language; hence, it does not have any commands or any format.

Now the updates. Since SQL is a programming language, it is fixed, and the command remains unchanged, and we can't update it. While MySQL has its latest updates and versions for enhanced performance.

For supporting language, SQL was designed for Windows, but it also works on Linux, Mac OS, in its most recent versions. While MySQL is a cross-platform compatible, running on Linux, Mac OS, and Windows as well.

Now coming to the data security, SQL servers are secured as no third party or outsiders are allowed to manipulate data. While in MySQL, it is susceptible to more security threats due to its open-source nature; it gives access to data manipulation and modification to unauthorized users as well during the runtime.

Foreignly known as, not only SQL database provides a mechanism for storage and retrieval of data and is the next-generation database. This kind of database has no specific schema and does not have tables with rows and columns storing data values, but can definitely handle a large amount of data. So if you consider the example on the screen, we have an employee database which has two collections: that is the employee and the projects collection. Now each of these collections have documents which are basically the data values. So if you just want to understand these terms, then you can just consider the collections to be your tables and the documents to be your fields in the tables.

So if you compare a SQL database and a NoSQL database, for example, let's just say we have an employee database where, you know, there's an employee table with around 10 columns, right? That is basically the 10 fields. Now in the NoSQL database, what will happen is the employee table itself will be taken as a collection, and each of these fields will be treated as documents. Now the most interesting part of NoSQL is that these kinds of databases do not have to use the same schema for the presence of multiple documents in one collection. So since NoSQL has a dynamic schema, that means that, you know, multiple documents can be present in a single collection, and also each collection can have different documents. So you can have a document in the collection which has both employeeID and employeeName, and also you can have a document in the same collection which does not have the ID and just shows the name. So that's how, guys, you can play around with collections and documents in NoSQL databases. Apart from this, let me just also tell you that, you know, there is no specific query language present in NoSQL. So basically, the language that you use to retrieve data is completely infrastructure-based; that is basically how you store your data and where you store your data. Lastly, there are no or very few relationships present in a NoSQL database, as you do not have a predefined schema, but you do have a dynamic schema in which we can put all the required information in a collection, right? When you have a dynamic schema and you have the option of putting all the required information in a single collection, and the collection can differ in the same schema itself, you actually do not need any relationships to be present, right? So that's how, guys, a NoSQL does not have or has very few relationships. So guys, if I just have to summarize NoSQL for you, then NoSQL is a type of database which does not have a predefined schema, a query language, and has no tables. It follows a method of storing data in a dynamic schema with less or no relationships and can handle a humongous amount of data. Let's now see how these databases stand against each other. So in this face-off, we'll be comparing both these databases based on the grounds such as the type of database, schema, database categories, complex queries, hierarchical data storage, scalability, language, online processing-based properties, and external support. Let's get into the detail with the first comparison factor, that is the type of database. Now when we

Compare these databases based on this factor. Let me just tell you that you know SQL is essentially called a relational database, and it organizes structured data fields into defined columns. So, a database can have n number of tables, and each table can have m number of columns with the data stored in it. Each table can be related to the other tables also, right? So, if you have around 10 tables, then those 10 tables can have around two to three columns, so you can say more than that columns in each table, and all these 10 tables can be related to each other.

Coming to NoSQL, NoSQL is a non-relational database which provides a mechanism for storage and retrieval of data. In the NoSQL database, data is modeled in the form of collections, and hence it tries to avoid relations as I just explained to you before. So guys, if you have to compare these databases based on this factor, then SQL is essentially a relational database, and NoSQL is a non-relational database or a distributed database. Next, we'll be comparing these databases based on the schema.

While comparing these databases based on this factor, let me tell you that SQL needs a predefined schema for structured data. So, before you start using SQL to extract and manipulate data, you need to make sure that you know your data is predefined in the form of tables. Coming to NoSQL, well, NoSQL databases have a dynamic schema for unstructured data. So, if you're using the NoSQL database, then there's no predefined schema present, and the complete schema of your data completely depends on how you wish to store the data; that is, which fields, that is basically which documents that you wish to store in which collections, and how you wish to store them. So guys, that was about schema. The SQL has a predefined schema, and the NoSQL has a dynamic schema. Now moving on to the next parameter, which is database categories.

Now, SQL databases are basically the table-based databases. So, as I explained in the previous factors, the SQL databases can have n number of tables related to each other, and each table can have m number of rows in columns storing data in each cell of the data. Now, similarly, if we talk about the NoSQL databases, the NoSQL databases have mainly four categories of databases: that is, document database, the key-value stores, graph stores, and the wide-column stores. Coming to the document database, now this kind of database pairs each key with a complex data structure known as a document. It can contain many different key-value pairs, or the key-error pairs, or even the nested documents. Coming to the key-value stores, these are the simplest form of NoSQL database. So, every single item in the database is stored as an attribute name or a key together with its value. Now, coming to the graph stores, the graph stores are basically used to store the information about networks such as the social connections. Now, the graph stores mainly include the Neo4j and the HypergraphDB. Coming to the last kind of database category of NoSQL, that is the wide-column stores. The wide-column stores, such as Cassandra and HBase, are optimized for queries over large datasets and stores columns of data together instead of rows. So guys, these were mainly the four categories of NoSQL database: that is, the document database, the key-value stores, the graph stores, and the wide-column stores. Now, this might have given you an idea of, you know, the SQL databases basically represent data in the form of tables which consist of n rows of data, whereas the NoSQL databases are the collection of key-value pairs, documents, graph databases, or wide-column stores which do not have a standard schema definitions which it needs to stick to. So guys, this was the main difference between SQL and NoSQL: that SQL is basically the table-based databases with a predefined schema, and the NoSQL databases mainly have different categories of databases with a dynamic schema. So, I hope I'm clear with this file. Next, let's discuss how these databases fit for complex queries.

Now, when we talk about complex queries, let me just tell you that you know SQL is a good fit for a complex query environment as the schema and the databases is structured and has proper tables. So, even if you wish to apply nested queries with many subqueries inside the outer query, you can easily do by using the proper table and column names, and you can retrieve the required data. Coming to the NoSQL databases, the NoSQL databases are not a good fit for complex queries as they don't have standard interfaces to perform complex queries, and the queries themselves in NoSQL are not as powerful as the SQL query language. So, this is basically because, you know, they're not written in a specific language, and the language in which they are written is completely based on the database infrastructure. You can see the schema. So, if you have to compare how these databases fit for complex queries, then let me tell you that SQL is a better fit for complex queries when compared to NoSQL.

Now moving on to the next factor of comparison, that is hierarchical data storage. Now, when we compare the databases based on this factor, that will tell you that the SQL databases are not best fit for hierarchical data storage. Now, this is because as the number of tables increase, the complexity of relating them to each other also keeps increasing. Now, in such a scenario, you cannot relate a humongous amount of tables with n number of columns to each other, right? But coming to NoSQL database, the NoSQL database fits better for hierarchical data storage as it follows the key-value pair way of storing data similar to the JSON data. Now, NoSQL databases are also highly preferred for last data sets when compared to the SQL database, and one such example is HBase. So, basically, HBase is used for this purpose. The next point of comparison will be scalability.

Now, SQL databases are vertically scalable. You can load balance this database by optimizing your hardware requirements, such as increasing the CPU, RAM, SSD, etc., on a single server. On the other hand, the NoSQL databases are horizontally scalable. You can do load balancing by adding more servers to your cluster so that with the help of these servers you can handle large traffic. So, on the note of scalability, SQL is vertically scalable, and NoSQL is horizontally scalable. Next, we'll be comparing these databases based on language. The SQL databases have a specific language, and it does not vary from database to database. So, basically, the SQL databases use the structured query language for defining and manipulating the data, which is very powerful. Coming to NoSQL, the NoSQL has no specific language, and it varies from database to database. In the NoSQL databases, the queries are focused on the collection of documents, and sometimes the language used in NoSQL is also called unstructured query language. So, on the note of language guys, the SQL uses a proper defined language, that is the structured query language, and NoSQL has no specific language, and the language differs from database to database.

Now moving on to the next parameter, which is online processing. Now, when we compare both these databases based on online processing, SQL databases are the best fit for heavy-duty transaction-type applications as its most stable and promises the atomicity as well as the integrity of data. While you can definitely use NoSQL for transaction purposes, yet it is still not compatible and stable enough and high load for complex transactional applications. So, you can understand by this that you know SQL is mainly used for OLTP, that is basically online transactional processing, and NoSQL is mainly used for OLAP, which is online analytical processing. So, if I have to just explain these terms OLTP and OLAP for you, then OLTP is basically characterized by a large number of short online transactions such as insert, update, and delete. The main emphasis for OLTP systems is to put on very fast query processing, maintained data integrity in multi-access environments, and an effectiveness measured by the number of transactions per second. In OLTP databases, there's proper detail and current data, and the schema used to store transaction databases is in the entity model, usually 3NF. Now coming to OLAP, that is basically online analytical processing. This is basically characterized by a relatively low volume of transactions, and queries are often very complex and involve aggregation. For OLAP systems, response time is an effectiveness measure, and OLAP applications are widely used by data mining techniques. So, in the OLAP database, there is aggregated historical data stored in multi-dimensional schemas, usually the star schema. So guys, that was about OLTP and OLAP. So, you can just understand this point that you know SQL is mainly used for heavy transactional type applications, and NoSQL is basically used for analytical processing and can definitely be used for transaction type applications, but yet it is still not stable for high-load applications. So now the next point of comparison we have is base properties.

Now, SQL databases emphasize on the ACID properties: that is, the atomicity, consistency, isolation, and durability, whereas the NoSQL database follows the CAP theorem: that is, the consistency, availability, and partition tolerance. So let's talk about both of them one by one, starting with the ACID properties. ACID properties mainly stand for atomicity, consistency, isolation, and durability. Now, atomicity basically refers to the transactions that are completely done or failed, where the transaction refers to a single logical operation of data. Now, this basically means that you know even if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged. Coming to consistency, the consistency ensures that data must meet all the validation rules. In simple words, you can just say that you know your transaction never leaves the database without completing its state. Coming to isolation, the main goal for isolation is basically the concurrency control. And finally, the durability, the durability means that you know if a transaction has been committed, it will occur whatever may come in between, such as the power loss, crash, or any sort of error. So guys, that was about the ACID properties: that is basically the atomicity, consistency, isolation, and durability. Coming to the CAP theorem, the CAP theorem or the Eric Brewer's theorem states that you know we can only achieve at most two out of three guarantees for a database: that is basically the consistency, availability, and partition tolerance. So here, the consistency means that you know all the nodes in the network say the same data at the same time, or the reader gets the most recently written data. Coming to availability, availability is the guarantee that every request receives a response about whether it is successful or failed, and the more number of users a system can cater to, the better is the availability. Coming to the partition tolerance, the partition tolerance is a guarantee that the system continues to operate despite arbitrary message loss or failure of any part of the system. In other words, even if there is a network outage in the data center and some of the computers are unreachable, still the system continues to perform. Now, out of these three guarantees: that is consistency, availability, and partition tolerance, no system can provide more than two guarantees. Now, since in the case of distributed systems, the partition of the network is a must, the trade-off is always between consistency and availability. So, you can just understand that you know NoSQL cannot provide consistency and high availability together. So guys, that was about the base properties. SQL is completely based on the ACID properties, and NoSQL is based on the CAP theorem.

Finally, the last but not the least factor of comparison is external support. Now, external support is available for all SQL databases from their vendors. There are also a lot of independent consultations who can help you with SQL databases for a very large-scale deployment. This is mainly due to since SQL has been into existence since more than 40 years, and people have been using SQL regularly. Now coming to NoSQL, for some NoSQL databases, you still have to rely on the community support, and only limited outside experts are available for you to set up and deploy a large-scale NoSQL deployments. This is mainly because NoSQL has come into existence, and many of them haven't explored it yet much. So folks, with this, we come to an end of this face-off between SQL and NoSQL. I hope all the comparison factors were clear to you guys. Now, in this session, since we have discussed so much about SQL and NoSQL, let me just show you some examples of the same. So, as you can see on my screen, these are the examples for SQL and NoSQL. So, the popular examples for SQL are the Oracle, the PostgreSQL, the MySQL, the Microsoft SQL Server, and SQLite. Now coming to the examples of NoSQL, then examples of NoSQL will have Redis, MongoDB, Apache HBase, BigTable, and Cassandra. Now, out of the lot, the most popular databases in today's market are basically the MySQL and MongoDB from the SQL and the NoSQL sections. Next, in this session, we'll be comparing MySQL and MongoDB based on various parameters.

Now, before I move on with the comparison of MySQL and MongoDB, let's first understand what is MySQL and what is MongoDB. Starting with MySQL, MySQL is an open-source relational database management system that works on many platforms. It provides multi-user access to support many storage engines and is backed by Oracle. So, you can buy a commercial license version from Oracle to get premium support services. Now, the features of MySQL, as you can see on my screen, so basically MySQL provides comprehensive application development, scalability, and flexibility, and it's open source and provides 24/7 support, provides high availability, high-performance support, secures your data, provides robust transaction support, requires low total cost of ownership, and provides ease of management. Now coming to comprehensive application development, MySQL has plug-in libraries to embed the database into any application. So, it basically supports stored procedures, triggers, functions, views, and many more application development. Coming to scalability and flexibility, with MySQL, you can run deeply embedded applications and create data warehouses holding a humongous amount of data. Next, talking about open source and 24/7 support, this relational database management system can be used on any platform and offers 24/7 support for open source and Enterprise Edition. Talking about high availability, MySQL can run high-speed master-slave replication configurations, and it offers various cluster servers. Talking about high performance, MySQL provides fast load utilities with distinct memory caches and tables index partitioning. Next, about data protection, MySQL supports powerful mechanisms to ensure that only authorized users have access to the databases. Next, talking about robust transactional support, MySQL holds the ACID properties: that is, basically the atomicity, consistency, isolation, and durability properties and allows distributed multiversion support. And talking about low total cost of ownership, MySQL makes sure it reduces the licensing costs and hardware expenditures. And talking about finally the ease of management, this software can be easily downloaded and also uses an event scheduler to schedule the task automatically. So guys, the features of MySQL are basically the comprehensive application development, the scalability and flexibility, open source and 24/7 support, high availability, high performance, secure data protection, robust transaction support, low total cost of ownership, and ease of management.

Now coming to MongoDB, MongoDB is a non-relational database which stores data as documents in a binary representation called BSON, that is basically binary JSON. This kind of database stores related information together for fast query access to the MongoDB query language. The features of MongoDB are, as you can see on my screen, that is indexing, replication, ad-hoc queries, schema-less, and sharding. Talking about indexing, MongoDB indexes are created in order to improve the search performance. Next, talking about replication, MongoDB distributes the data across different machines. Coming to ad-hoc queries, MongoDB supports ad-hoc queries by indexing the BSON documents and uses a unique query language. Coming to schema-less, it's very flexible because it's a schema-less database and is written in C++. And talking about sharding, MongoDB uses sharding to enable deployments with large datasets and high-throughput operations. So guys, these are the mainly five features of MongoDB: that is indexing, replication, ad-hoc query, schema-less, and sharding. So guys, now that you know what MySQL is and what MongoDB is, let's compare these two databases based on the grounds that you can see on the screen: that is the query language, the flexibility of schema, the relationships, security, performance, support, key features, replication, usage, and active community. So now let's get into detail with the first comparison factor: that is the query language.

Now, MySQL uses the structured query language to communicate with the database. Not only is it simple, it is also a very powerful language which consists of mainly two parts: that is the data definition language and the data manipulation language. MongoDB, on the other hand, uses an unstructured query language to build a query in JSON documents. You need to specify a document with various properties you wish the results to match. It is typically executed using a very rich set of operators that are linked with each other using JSON. Now, MongoDB treats each property as having an implicit Boolean, and it basically also supports Boolean or queries, but you must definitely use the special operator dollar or to achieve it. So, to make you understand better, I've considered the example on the screen. So, to insert the data into the employees table in the SQL query, you just have to type in insert into employees, that is basically your table name, and insert into is your SQL syntax, and then you mention the column names: that is the employee ID and employee age, and then you use the SQL syntax: that is the values and mention the values for the fields. So, to just insert data into the table, you mentioned insert into employees, employee ID, employee age, values, and then you mentioned the values. Now, similarly, in the same scenario, if you wish to insert the data into a collection which is stored in the MongoDB database, what you simply have to do is you have to mention db.employees.insert, where employees is the collection name, and then you have to mention employee ID and then mention the value, and then mention again age and the value. So basically, over here employee ID and age are basically the fields. So guys, this is how, you know, the query language between MySQL and MongoDB differs. Next, we'll be comparing these databases based on the flexibility of schema.

Now, in the perspective of flexibility of schema, let me tell you that you know before you can store anything in MySQL, you need to clearly define tables and columns, and every row in the table should have the same column. Now, this is basically because there isn't much space for flexibility in the manner of storing data. If you follow normalization, for example, if you have an employee database, you need to create a table which can hold the data of employees. Now, this table can have many attribute values such as the employee ID, employee name, and so on. Now, similarly, talking about MongoDB, one of the best things about MongoDB is that you know there are no restrictions on the schema design. So, you can directly drop a couple of documents within a collection, and it isn't necessary to have any relations between those documents. Now, the only restriction with MongoDB is that you need to frequently optimize your schema based on how the application will be accessing the data. Now, MongoDB stores the data in the JSON type manner. So, if we consider the previous example: that is the employee table, the data in MongoDB would be stored as, you know, employee ID, and then we have to mention the employee ID, that is basically the value for employee ID, then employee name, and then you have to mention the employee name, employee age, and so on. So, basically, this will be considered as a document, and now these documents can be stored in a collection as well. So, basically, MongoDB creates schema-less documents which can store any information you want, though it may cause problems with the data consistency, whereas the MySQL follows a strict schema template.

Now moving on to the next parameter, which is relationships. Now, when we talk about relationships, MySQL supports the join operations. So, to explain to you in simple terms, join makes the relational database relational. So, basically, the join allows the user to link the data from two or more tables in a single query with the help of the select command. So, for example, if you want to retrieve the data from the employee and the projects table based on the matching column, you can easily obtain the desired data by applying any type of join, such as the inner, left, right, or full, based on your need. Now coming to MongoDB, well, MongoDB does not support the join statements, but it supports the multi-dimensional data types such as arrays and even other documents. So, the placement of one document inside another document is basically known as the embedding of documents, and MongoDB supports the embedding of documents. So, talking about relationships, guys, MySQL supports the join statements, and the MongoDB does not support any join statements.

Next, let's discuss the security factor for both of them. Now, talking about MySQL first, MySQL uses a privilege-based security model. The database unit basically authenticates a user and facilitates it with the user privileges on a particular database, such as create, select, insert, update, and so on. Now coming to MongoDB, MongoDB uses a role-based access control with a flexible set of privileges. Its security features basically include the authentication, auditing, and authorization. Not only this, but it is also possible to use the transport layer security.

The secure socket layer for encryption purposes in MongoDB. So basically, this ensures that the unit is only accessible and read by the intended client; no other client can go through the documents. So guys, that's how the security is provided in MySQL and MongoDB.

Now let's move over to the next factor of comparison, that is performance. So, on comparing MySQL and MongoDB on this parameter, MySQL is quite slower in comparison to MongoDB when it comes to dealing with large databases. This is mainly because, you know, MySQL can't cope up with large and unstructured amounts of data, whereas MongoDB can. So that's the reason, guys, MongoDB is much faster than MySQL.

Now talk about MongoDB; MongoDB has the ability to handle large unstructured data. It's much faster than MySQL because it allows the users to query in a different manner that is more sensitive to workload. But yes, there is, as such, no benchmark on, you know, which database is faster because, you know, only it demands your data and your infrastructure can tell what you need and which database can provide you the output faster. So guys, that was about performance. Next, we'll be comparing these databases based on support.

Well, both of them offer excellent support 24/7 for security fixes, maintenance releases, bug fixes, patches, and updates. So there is, as such, no difference between both of them based on this parameter, as both of them offer good support. So guys, that was about support. Now moving on to the next parameter, which is key features. The key features of MySQL and MongoDB are as you can see on my screen. Let's start with MySQL first. The key features of MySQL are mainly triggers, and SSL support provides text searching and indexing; also allows query caching, provides integrated replication support, and also provides different storage engines. So guys, these were the key features of MySQL. Now talking about MongoDB, MongoDB supports auto-sharding, comprehensive secondary indexes, in-memory speed, native application, and embedded data model support. So these were few features of MySQL and MongoDB. So yes, there are various differences between both these databases, but there are few key features, you know, which help both MySQL and MongoDB to win in their own market.

Now, the next point of comparison we have is replication. Now MySQL supports the master-slave replication and the master-master replication as of MySQL 5.7.6 and later, and this kind of multi-source replication allows you to replicate from several masters in parallel. Talking about MongoDB, MongoDB supports the built-in replication, sharding, and auto-elections. So by using auto-elections, you can set up a secondary database to automatically take over if the primary database fails. So sharding allows for horizontal scaling, which is difficult to implement in MySQL, as MySQL is vertically scalable. Not only this, but MongoDB also uses replica sets to create multiple copies of data. So each member of the replica set can have the role of primary or secondary at any point in the process, and the read and writes are done on the primary replica by default and then replicated to the secondary replicas. So guys, this was about the replication; MySQL supports the master-slave replication, and the MongoDB supports built-in replication, sharding, and auto-elections.

Next, we'll be comparing these tools based on usage. Now for this factor, I'm going to tell you where you can use MySQL and MongoDB. So let's start with MySQL first. MySQL is the best fit for data with tables and rows; this works better for small data sets and allows frequent updates. MySQL is also used for strong dependency on multi-row transactions and is also used when you want to modify large volumes of records. Talking about MongoDB, MongoDB best fits for unstructured data and works better for large data sets. This is also used when you have high write loads and high availability in an unstable environment, and the data is completely location-based. So this was about MySQL and MongoDB, guys. MySQL mainly best fits for data with tables and rows, and MongoDB best fits for unstructured data.

Finally, the last but not the least factor of comparison is the active community. The MySQL database is mainly owned and maintained by the Oracle corporations, so they offer a developer's zone on the MySQL website, and the community for MySQL is, I would say, much better than that of MongoDB. So if you want support, both of them offer good support, but yes, if you talk about the active community, then MySQL has a better active community than compared to MongoDB.

So guys, now that I've told you so much about MySQL and MongoDB, let me just shift to my MySQL Workbench and MongoDB Compass so that I show you how you can create tables and databases in MySQL and how you can create databases and collections in MongoDB. So first, we'll be looking into MySQL. So for that, I'll open my MySQL Workbench. So as you can see on my screen, this is my MySQL Workbench. So I'm just going to open my connection. So guys, this is how your MySQL Workbench looks. Now to show you how you can use MySQL, I've already written the command, so I'm just going to tell you how you can use them. So to create a database, I've used a query: `CREATE DATABASE`, and I've mentioned the database name, that is `employee_info`. So this is SQL language, guys, where, you know, `CREATE` and `DATABASE` are the SQL syntax, and `employee_info` is the data parameter. I'm going to just execute this particular query. Now once the query is executed, you can clearly see that, you know, the database has been created. Now to use this database, you can just directly use the database name, that is `employee_info`. So if I just execute this query again, you'll clearly see that, you know, we'll be using this particular database. Now to create a table inside this particular database, you can use the query like, you know, `CREATE TABLE table_name`, and then you mention all the field names and the data types, right? So over here, I have different field names like the employee ID, employee first name, last name, age, email ID, phone number, and address, and their specific data types, right? So I'm going to just execute this particular query. So once I execute this particular query, you can see that, you know, a table has been created. So now if we just look into our databases, we have a database that is `employee_info`, and then we have a table inside it. Now to insert data into the table, what you can use is you can just use the query `INSERT INTO table_name`, that is `employee` over here, mention all the field names, then use the SQL syntax keyword `VALUES`, and then mention all the values, right? So here I've written a query as `INSERT INTO employee employee_ID, first_name, last_name, age, email_ID, phone_number, address VALUES`, and then I've mentioned the values, right? So I'm going to just execute this particular query. So once the query has been executed, you can clearly see that, you know, data has been inserted into the table. So I'll just go to the `employee_info` table, coder tables option, go to `employee`, and then I'm going to just look into the table. So when I just check into the option of view, you can clearly see that, you know, our first record has been inserted. So guys, that's how it's really simple to use MySQL, and with the help of MySQL Workbench, you get the GUI experience, you know, where you can easily mention your required queries, studies, and then get the outputs, right? So that was about MySQL Workbench, guys. Now shifting to MongoDB Compass.

So guys, this is how the MongoDB Compass looks. So basically, I've already created a database. Now if you just wish to go and check how a database has been created, what you can simply do is you can go over here to my cluster, and once you go to my cluster, you get an option of `Create Database`, right? So I'm just going to create a database. So let's say I mention it to be `employee_info`, and then over here, since I've told you, the database has collections, and then collections have documents, so basically a group of documents is collections, and a group of collections is a database. I'm going to mention my first collection name, let's say, you know, `employee`, and then I'm gonna just click on `Create Database`. So once I click on `Create Database`, you can clearly see that, you know, my database has been created, that is `employee_info`. So I'll click on this, and you'll see that, you know, we already have a predefined collection created. Now apart from this, you can also have a number of collections to be created, but since I'm just showing you how you can use MongoDB, I'm not going to create many more collections. This is just a single collection that I've already created. Now what you can do is you can again create documents inside this particular collection. To do that, you have to click on this collection, that is the `employee` collection, and over here you get an option for `Insert Document`, right? So you can just click on this option of `Insert Document`, mention the required values, that is basically the `_id`, `.objectID`. So basically, over here you can just mention `employee_ID`, and in this section, you can just mention the `employee_ID`. Now similarly, you can mention the employee name also, and over here I'll mention the employee name to be, let's say, Sahity, right? Now over here, if you see, we can also use the data type. So let's just say, you know, our `employee_ID` should be `int`, so I'll just mention it to be `int`, and `employee_name` to be `string`, right? So that's how you can mention the data types for your documents, and then once you've inserted all the required values, you can just click on `Insert`. So once you click on `Insert`, you can clearly see that, you know, your document has been created. Now this you can either view in the form of a table, that is basically, you know, which document ID basically has which employee ID, that is which data type, and also the employee name, or you can also view it as a list. I was previously viewing it as a list. This is how you can create a database and then create a collection and documents. Well, I'm not going to go in-depth of how you can use this MongoDB Compass and how you can explore much more features of this. So guys, it was just a short demo on, you know, how you can use MySQL Workbench and MongoDB Compass to handle structured data and unstructured data.

So folks, with this, we come to an end of the space off between MySQL and MongoDB, and I hope you understood all the points. Now, knowing so much about MySQL and MongoDB would have definitely raised a question on your mind whether to use MongoDB or MySQL for your businesses. So guys, well, there is no clear winner between both of them; the choice of database completely depends upon the schema of your database and how you wish to access it. Nevertheless, you can use MySQL when you have a fixed schema, high transaction, low maintenance, data security with a limited budget, and MongoDB while you have an unstable schema, no specific database administrator, high availability, cloud computing involved with inbuilt sharding. So guys, this is when you use MySQL and MongoDB. There's no clear winner between both of them; it completely depends on you which type of database you would want to go for for your businesses and how you think your business will be benefited by choosing which database. So there won't be any final verdict as to which among them is best, as each one of these excels based on your requirements.

So I'll start by explaining to you what is the DELETE command. Well, the DELETE command is basically used to delete a row in the table. So you can also roll back data after using the DELETE statement, and it is a data manipulation command. Coming to the TRUNCATE statement, the TRUNCATE statement is basically used to delete all the rows from a table, and you cannot roll back the data. This is a data definition language command, and it is faster than the DELETE command. So if anyone asks you the difference between the DELETE and the TRUNCATE statements, don't forget to mention that, you know, the TRUNCATE statement is definitely faster than the DELETE statement, and the TRUNCATE statement is from the data definition family, and the DELETE statement is from the data manipulation family, right?

Now moving on to our next question, that is, what are the different subsets of SQL? Well, the different subsets of SQL are mainly the data definition language, the data manipulation language, the data control language, and the transaction control language. Now coming to the data definition language, this set of language consists of the commands that can be used to define the database schema. So whenever you want to define the database schema, you can use the commands from this particular language. Coming to the data manipulation language, the manipulation language consists of all the commands that deal with the manipulation of data present in the database. So, for example, if you have n number of tables and you want to manipulate the data present in those tables, then you use data manipulation commands. Coming to the data control language, the data control language includes the commands which deal with the write permissions and other controls of the database systems. So, for example, you work for an enterprise, and the enterprise has a database. Now obviously, all the employees will not have the access to the database, right? So data control language mainly deals with how you give the user permissions to access the database. Now coming to the last type of language, that is the transaction control language; this basically includes the commands which mainly deal with the transaction of the database. Whenever you want to roll back or you want to perform any various kinds of transactions, then you use the set of commands from this language, right? So I hope I'm clear. So as I said, there are mainly four different subsets of SQL that you should mention, that is the data definition language, the data manipulation language, the data control language, and the transaction control language.

Now moving on to our next question, that is, what do you mean by database management systems, and what are the different types of it? So now if I have to define the database management system for you, then a database management system is a software application that interacts with the users, applications, and the database itself to capture and analyze the data. So the data stored in a database can be modified, retrieved, and deleted and can be of any type like strings, numbers, images, etc. So you can basically store any kind of data. Now the different kinds of database management systems are the hierarchical, the relational, the network, and the object-oriented database management systems. Now talking about the hierarchical database management systems, this type of database management system has a style of predecessor and the successive type of relationship. So it has a structure similar to a data tree, wherein the nodes represent the records and the branches of the tree represent the fields. Coming to the relational database management system, this type of database management system uses a structure that allows the user to identify and access data in relation to other pieces of data in the database. The network database management system supports many-to-many relations wherein multiple member records can be linked, and the object-oriented database management systems use small individual software called objects, and each object contains a piece of data and the instructions for the actions to be done with the data. So I hope I'm clear with this point. So now moving on to our next question, that is, what do you mean by a table and a field in SQL? So now the answer to this question is quite simple; a table basically refers to a collection of data in an organized manner in forms of rows and columns, and the field refers to the number of columns in the table. If you have to explain to anybody what table and field mean, so basically in SQL you have a database, and a database consists of n number of tables, right? So that is basically a table, and the tables have few column names, right? So the column names are basically the fields. So you can explain with an example as you can see in the screen. So over here, I have an `employee_information` table, into which the `employee_information` table is a table, and the column names in this particular table are the fields.

Now moving on to our next question, that is, what are joins in SQL? Now this is one of the most popular questions that is generally asked in your interviews. So basically, a JOIN clause is used to define to combine rows from two or more tables based on related columns between them. It is used to merge two tables or retrieve data from there, and there are mainly four types of joins in SQL, that is the INNER JOIN, the FULL JOIN, the LEFT JOIN, and the RIGHT JOIN, right?

Now moving on to our next question, that is, what is the difference between CHAR and VARCHAR2 data type in SQL? Now this is one of the most confusing questions that is generally asked in your interviews, since, you know, generally people get confused between what is CHAR and what is VARCHAR2 data type. Now both CHAR and VARCHAR2 are used for character data type, but VARCHAR2 is used for character strings of variable length, whereas CHAR is used for strings of fixed length. So whenever you have strings of fixed length, then you use the CHAR data types, and whenever you have strings of variable length, then you can use the VARCHAR2 data type. Now, for example, CHAR(10) can only store 10 characters and will not be able to store a string of any other length, whereas the VARCHAR2(10) can store any length, that is either 6 to 8; it completely depends on the variable, right?

Now moving on to our next question, that is, what is the primary key? Now when you're working in a database field, obviously a company, you can have n number of databases having n number of tables inside this. Now each and every table in a database has to be connected with the other table, right? Now for that, we need to uniquely identify a table, or you know, you can say you need to uniquely identify a column. So basically, a primary key is a set of attributes that can be used to uniquely identify every tuple. So if there are around three to four candidate keys present in a relationship, then out of those, one can be chosen as the primary key. Now as you can see on the screen, we have an `employee_information` table which has columns like, you know, `employee_number`, `employee_name`, `employee_country`, and the `employee_age`. Now obviously, you can uniquely identify each and every employee with the `employee_ID`, right? So basically, that will be a primary key. So over here, `employee_number` will be a primary key.

Now let's move on to our next question, that is, what are constraints? So constraints are basically used to specify the limit of the data type of the table, right? So whenever you're creating a table, then you can use the constraints to set a limit of the data type of the table. It can be either specified while either creating the table or, you know, while you're altering the table statement. So it can be basically specified in both the ways. Now there are mainly five constraints that you need to understand about, that is the NOT NULL constraint, the UNIQUE constraint, the CHECK constraint, the DEFAULT constraint, and the INDEX constraint. Now the NOT NULL constraint basically ensures that a null value cannot be stored in a column. So whenever you mention this particular constraint into a column of your table, then this particular constraint will make sure that, you know, no null value can be stored for that particular column in the table. Moving on to the next constraint, that is the UNIQUE constraint; this constraint makes sure that, you know, all the values in the column are basically different. So if you need to make sure that, you know, in a column you have unique values for each and every row, then you can use this particular constraint. Now moving on to the next constraint, that is the CHECK constraint; the CHECK constraint basically ensures that all the values in the column satisfy a specific condition. So if you have a condition, you need to make sure that, you know, only the values which satisfy the condition are stored in the column, then you can use this particular constraint. Now talking about the DEFAULT constraint, the DEFAULT constraint consists of a set of default values for a column when no values are specified. So, for example, in a table of 10 rows, you know, you have a column in which you do not specify all the values for all the 10 rows, then you can make sure that, you know, you will set the default value, and the default value will be automatically stored whenever you don't mention a value in that column. Now moving on to the last type of constraint, that is the INDEX constraint; the INDEX constraint is used to create and retrieve data from the databases very quickly. So I hope I'm clear with the different types of constraints that you need to answer about when you're asked this question about what are the constraints that you know. Now let's move on to the next question, that is...

What is the difference between SQL and MySQL? Now, this is one of the most popular questions, generally asked, you know, because since people generally get confused between what is SQL and what is MySQL. So let me just explain the simple difference between both of them. SQL is basically a standard language which stands for Structured Query Language, based on the English language, whereas MySQL is a database management system. SQL is basically the core of relational databases, which is used for accessing and managing the database, whereas MySQL is a relational database management system which works on many platforms. So basically, this provides multi-user access, to support many storage engines, and is backed by Oracle. So that's the basic difference between SQL and MySQL, guys. SQL is basically the core of relational databases, which is used for accessing and managing your database, and MySQL is an open-source relational database management system.

Now let's move forward to our next question: what is a unique key? Now, a unique key basically identifies a single row in a table. This basically allows multiple null values per table, and also null values are allowed. So you'll have to make sure that you know, whenever you're using the unique key, you need to have an idea that it identifies a single row in the table; multiple values are allowed for the table, and also null values are allowed, but yes, duplicate values are not allowed. All right.

Now moving forward to a next question: what is a foreign key? A foreign key basically maintains referential integrity by enforcing a link between the data in two tables. The foreign key in the child table references the primary key in the parent table, and the foreign key constraint prevents actions that would destroy the links between the child and the parent table. So if you have a database, and you know, if you have around 10 tables in that particular database, and then if you want to maintain relations between all these tables in the database, then you need to use the primary key foreign key concept so that you identify the relation between both these tables with the help of a foreign key.

Now moving forward to a next question: what do you mean by data integrity? Now, data integrity basically defines the accuracy of the data as well as the consistency of data stored in the database. It also defines the integrity constraints to enforce business rules on the data when it is entered into an application or a database. So if you have to answer this question, then you can answer by saying that data integrity basically defines the accuracy and the consistency of data.

Now let's move forward to a next question: what is the difference between the clustered and the non-clustered index in SQL? The clustered index is basically used for the easy retrieval of data from the database and is faster than the non-clustered index. The clustered index alters the way records are stored in the database as it sorts out the rows by the column which is set to be the clustered index, and only one table can have a clustered index. Coming to the non-clustered index, the non-clustered index is also used for the retrieval of data from the database, but yes, it is slower than the clustered index. The non-clustered index does not alter the way it is stored, but yet it creates a separate object within a table which points back to the original table rows after searching, and also one table can have many non-clustered indexes. The main difference between both of them is that both are used for easy retrieval of data, but yes, the clustered index is faster than the non-clustered index, and only one table can have only one clustered index, but yes, a single table can have many non-clustered indexes. Apart from that, the third difference between both of them is that the clustered index alters the way records are stored in the table, and the non-clustered index does not do that.

Now let's move forward to our next question: write a SQL query to display the current date. Now, when you attend interviews for a database administrator, let me just tell you that not only theoretical questions are asked, but yes, you are sometimes asked to write queries also. So they can give you some scenario-based questions; they can just ask you a few simple queries that you need to make sure that you know. So that's the reason this question could be asked: write a SQL query to display the current date. Now, in SQL, to display the current date, we have a function known as GETDATE. So basically, with the help of this function, you can return the current date and timestamp. The syntax of the function is really simple: it's just GETDATE, and it applies to SQL Server 2017, 16, 14, 12, 2008 R2, 2008, and 2005. Now, if you just have to give an example to the interviewer about how to write a query to display the current date, you can just mention the query like: SELECT GETDATE. So when you execute this particular query, you would see an output that the current date and time would be displayed as output. So that's how you can write a query to display the current date.

Now moving forward to the next question: what are the different types of joins? So, as I mentioned before, there are mainly four types of joins that you need to talk about: that is the inner join, the full join, the left join, and the right join. So talking about the inner join, this join basically returns those records which have matching values in both tables. Now consider two tables, Table A and Table B. Now, when you apply the inner join on both of these tables, you'll observe that the output would be all those records which have matching values in both tables, that is Table A and Table B. Let's talk about the full join. The full join basically returns all those records which either have a matching value in the left or the right table. So whenever you apply a full join on both of these tables, you'll see that you'll get an output of all those records which either have a match in the left or the right table. Now talking about the left join, the left join returns the records from the left table and also those records which satisfy the condition from the right table. So if you have Table A and Table B and you apply a left join to both of these tables, then the output would be all those records from the left table and the records from the right table which satisfy the specified condition. Similarly, the right join is just the vice versa. The right join basically returns records from the right table and also those records would satisfy the condition from the left table. So whenever you apply the right join to Table A and Table B, and consider that Table B is the right table, you'll get all those records from Table B and also matching records from Table A which satisfy the condition. So these are the various types of joins that you need to talk about, guys.

Now moving forward to the next question: what do you mean by denormalization? Now, denormalization basically refers to a technique which is used to access data from higher to lower forms of databases. It increases the performance of the entire infrastructure as it introduces redundancy into the table, and it also adds redundant data into a table by incorporating database queries that combine data from various tables in a single table. So if you have to just explain denormalization, you can just say that it is a technique which is used to access data from higher to lower forms of databases, and it basically adds redundant data into the table by incorporating database queries that combine data from various tables. So I hope I am clear with this.

Now moving forward to the next question: what are entities and relationships? Let me just explain what entities are first. So entities can be anything like a person, place, or a thing in the real world about which data can be stored in a database. Tables store data that represent one type of entity. So, for example, a banking database has a customer table to store customer information. The customer table stores this information as a set of attributes, that is basically the columns within the table for each and every customer. So if you consider a customer table has around five parameters like customer ID, customer name, customer phone number, customer email ID, and so on, then all these customer ID, customer name, customer phone number are basically the column names, that is the attributes for the entities, and customer information will be the entity. Now talking about relationships, relational links between entities that have something to do with each other are basically relationships. For example, the customer name is related to the customer account number and the contact information. Now this might be in the same table or it could be in any other table also. So if you have two tables, out of which one table has the customer name and the other table has all the other information like the customer ID, customer name, and so on, now these two tables will be related to each other with a relationship so that the customer details could be retrieved. Now that particular information is basically relationships.

Now moving forward to a next question: what is an index? In previous questions, I talked about the non-clustered index and the clustered indexes, right? But what exactly is an index? Now, an index basically refers to a performance tuning method of allowing faster retrieval of records from the table. As I mentioned before in the clustered and non-clustered indexes question, both of the indexes are basically used for easy retrieval of data. So that's what an index does. This is basically a performance tuning method to allow faster retrieval of data from the table, and also an index creates an entry for each value. So to allow the faster retrieval of records from the table, it basically creates an entry for each and every value. Now let's move forward to the different types of indexes. Well, I've already explained to you about two types of indexes, that is the clustered and the non-clustered index, but yes, let's understand again about both of them and also an additional index, that is the unique index. Mainly, there are three types of indexes that are used: that is the unique index, the clustered index, and the non-clustered index. The unique index basically does not allow the field to have duplicate values if the column is uniquely indexed. If a primary key is defined, a unique index can be applied automatically. A unique index is mainly used when you do not want any duplicate values to be present in the column. Now moving to the clustered index, the clustered index basically reorders the physical order of the table and searches based on the basis of key values. So each table can have only one clustered index. Coming to the third type of index, that is the non-clustered index, the non-clustered index does not alter the physical order of the table and maintains a logical order of the data. So each table can have many non-clustered indexes. So basically, guys, there are three types of indexes that you need to explain: that is the unique, the clustered, and the non-clustered index.

Now moving forward to a next question: what is normalization and what are its advantages? So normalization is basically the process of organizing data to avoid duplication and redundancy. It's basically the opposite of denormalization that we just talked about in one of the previous questions. So if you just have to define normalization, then you can say that it is a process of organizing data to avoid duplication and redundancy. Now the advantages of normalization are, as you can see on the screen: it offers better database organization, more tables with smaller rows, efficient data access, greater flexibility for queries, quickly finds the information, easy to implement security, allows easy modification, reduction of redundant data and duplicate data, more compact database, and ensures consistent data after modification. So guys, these are a few advantages of normalization.

Now let's move forward to our next question: what is the difference between the DROP and the TRUNCATE commands? The DROP command basically removes the table and it cannot be rolled back from the database. Whenever you use the DROP command, just remember that you completely drop the complete table and it cannot be rolled back from the database. The TRUNCATE command removes all the rows from the table and also cannot be rolled back into the database. The DROP command and the TRUNCATE command differ by this. Whenever you use the DROP command, you drop the complete table, and whenever you use the TRUNCATE command, you will remove all the rows from the table. The syntax of both the commands is almost the same. The syntax of the DROP command is basically DROP OBJECT and object name, that is basically the table and table name, and the syntax for the TRUNCATE command is TRUNCATE TABLE and table name. So guys, that was about the DROP and the TRUNCATE command.

Now let's move forward to the next question: what are the different types of normalization? So there are mainly four types of normalizations: that is 1NF, 2NF, 3NF, and BCNF. Now let me explain the different types of normalization with an example. So guys, this is the table that we're going to consider for the example. Now you basically have to apply normalization to this particular table. Now to apply normalization to this particular table, you'll clearly observe that there is Alice Johnson who has a particular address and has rented a few movies from a specific category, and the category action is mentioned twice over here. Similarly, David Allen's address has been divided into two different records, and the movie is rented in the categories have also been divided into two different records. Now to apply normalization to this particular table, you first have to apply the 1NF, that is the first normalized form. For a table to be in 1NF, you need to make sure that each table cell should have a single value. So basically, all the records must be unique. As I saw in this particular table, we have redundant values in the same record. So we're going to have each cell with a unique record. So we'll have records such as Miss Alice Johnson, First Street, house number three, Mission Impossible, and the second record as Miss Alice Johnson, First Street, house number three, Clash of Titans. Similarly, we'll have Mr. David Allen, Third Street 45, with Interstellar; Mr. David Allen, Third Street 45, with Edge of Tomorrow; and similarly, Mr. David Allen, Seventh Avenue, Mission Impossible Fallout. So that's how basically you get your table into 1NF; you have records with unique values in the complete table. Now as you can see on the screen, this is a table for 1NF. Now you have to divide this table to 2NF. When I say 2NF, that is the second normalized form, you can divide this table into two different tables. To have a table in 2NF, you need to make sure that the database should be in 1NF and should also have a single column primary key. Since a table is in 1NF that we considered, that's applicable to our situation. Now let's move forward to the 2NF. Now in the 2NF, you'll clearly see that we have salutation, full name, address, and movies rented. Now to divide this table into two different tables, you can clearly see that I've added an ID to both the tables. So I've added ID, salutation, full name, and address, and ID, movie rented. Miss Alice Johnson staying in First Street, house number three, must have rented Mission Impossible. Similarly, she must have rented Clash of Titans. Mrs. David Allen staying in Third Street 45 has rented Interstellar and Edge of Tomorrow, and Mr. David Allen staying in Seventh Avenue has rented Mission Impossible Fallout. So that's how I've divided the table into 2NF. Now moving forward to 3NF. Now a database to be in 3NF, you need to make sure that your database is first in 2NF and must not have any transitive functional dependencies. For that, what you're going to do is you're going to further divide the two tables into three tables, as you can see in the screen. So we're going to have an ID, full name, address, and salutation ID, and also another table with ID, movies rented column attributes, and the third table with salutation ID and salutation. So basically, we're going to identify Mr. with one, Miss with two, Misses with three, and Doctor with four. So that's how we're going to get our tables to 3NF. Well guys, with this, we come to an end of this particular example, that our table has been completely normalized, and the highest normal form available for this particular table is 3NF.

Now moving forward to that final type of normalization, that is BCNF. Now if your database is in third normal form, there would be some scenarios where anomalies would be present, and if you have more than one candidate key, then BCNF comes into role when you further divide your table so that there would be only one candidate key present. So guys, these are the various types of normalization: 1NF, 2NF, 3NF, and BCNF. In 1NF, there are no repeating groups within the rows; in 2NF, every non-key column is dependent on the whole primary key; in 3NF, it is completely dependent on the primary key; no other non-key column values; and in BCNF, you have to make sure that there is only one candidate key present in the table. So guys, these were the different types of normalizations that you need to understand.

Now let's move forward to our next question: what is the ACID property in a database? The ACID property mainly stands for Atomicity, Consistency, Isolation, and Durability. It is basically used to ensure that the data transactions are processed reliably in a database system. So if you have to define the ACID property in a database, then you have to define all these terms individually. A stands for Atomicity. Atomicity refers to transactions that are completely done or failed, where a transaction refers to a single logic operation of data. It means if one part of any transaction fails, then the entire transaction fails, and the database state is left unchanged. Coming to Consistency, consistency ensures that the data must meet all the validation rules. In simple words, you can say that your transaction never leaves the database without completing its state. The third part, that is Isolation, the main goal of isolation is concurrency control. The last part, that is Durability, durability means that if a transaction has been committed, it will occur whatever may come in between, such as power loss, crash, or any sort of error.

Now let's move forward to our next question: what do you mean by a trigger in SQL? So triggers in SQL are a special type of stored procedures that are defined to execute automatically in place of or after data modifications. It allows you to execute a batch of code when an INSERT, UPDATE, or any other query is executed against a specific table. So guys, there are mainly six types of triggers that you need to understand: that is the BEFORE INSERT, AFTER INSERT, BEFORE UPDATE, AFTER UPDATE, BEFORE DELETE, and AFTER DELETE. So basically, the two main key terms that you need to understand are BEFORE and AFTER. These are completely applied on the INSERT, UPDATE, and DELETE commands. BEFORE INSERT is basically activated before the data is inserted into the table. AFTER INSERT is activated after the data is inserted into a table. BEFORE UPDATE is activated before the data in the table is updated, and AFTER UPDATE is activated after the data in the table is updated. BEFORE DELETE is activated before data is removed from the table, and AFTER DELETE is activated after the data is removed from the table. So guys, this is what a trigger in SQL is. It is basically a type of stored procedure that is defined to execute automatically in place of or after data modifications.

Now let's move forward to our next question: what are the different types of operators available in SQL? So there are mainly five types of operators available in SQL: that is the Arithmetic, Bitwise, Comparison, Compound, and Logical operators. So guys, these are the main five types of operators available in SQL.

Now let's move forward to our next question: is a NULL value the same as 0 or a blank space? A NULL value is not at all the same as 0 or a blank space. A NULL value mainly represents a value which is unavailable, unknown, unassigned, or not applicable, whereas 0 is a number and a blank space is a character. So if anybody asks you if NULL values are the same as 0 or a blank space, please say no, because NULL values are basically anything which is unavailable, unknown, unassigned, or not applicable, whereas

Zero is a number, and a blank space is a character. Now let's move forward to a next question; that is, what is the difference between a cross join and a natural join? The cross join produces the cross product or Cartesian product of two tables, whereas the natural join is based on all the columns having the same name and data types in both the tables. The main difference between both of them is that you know the cross join basically produces the cross product of both the tables, and the natural join is completely based on all the columns having the same name and data types in both the tables.

Now let's move forward to our next question; that is, what is a subquery in SQL? A subquery is basically a query inside under the query where a query is defined to retrieve data or information back from the database. So subqueries are always executed first, and the result of the subquery is passed on to the main query. So as you can see on my screen, I have an outer query inside which I have a subquery or an inner query. So basically, this query is assigned to retrieve data from the database, and then this query will be executed first. So if there are any errors in this query, then the complete query would not be executed; only when the subquery is completely executed then the outer query will be executed.

Now let's move forward to a next question; that is, what are the different types of subqueries? Now there are mainly two types of subqueries: that is, the correlated and the non-correlated subquery. The correlated subqueries are basically those queries which select the data from a table referenced in the outer query. It is not considered as an independent query as it refers to another table and refers to a column in a table. The non-correlated subquery is an independent query where the output of the subquery is substituted in the main query. So you'll have to understand the difference between both of them. If you do not understand by definition, you can definitely go and execute the commands, write the two different types of queries in your SQL, and you'll get to know what I'm talking about. Basically, in a non-correlated type of subquery, the output of the subquery will be substituted into the main query, and in a correlated type of subquery, the queries select the data from a reference table in the outer query.

Now let's move forward to our next question; that is, can you list the ways to get the count of records in a table? Now to count the number of records in a table, you can use various kinds of queries. So there are mainly three queries that I've mentioned over here: that is, `Select * from table one`. `*` means basically select all. When you want to select all the rows, all the records from the table, you can use `*`. Next, when I say `select count(*) from table one`, that is basically you select all the records from the table one and then you count them. Coming to the third query, that is, `Select rows from system indexes where ID = object ID of table 1 and ID < 2`, that means it basically counts the number of records in a table with system indexes. These are the various ways to count the number of records in a table.

Now let's move forward to our next question; that is, write a SQL query to find the names of employees that begin with the alphabet 'a'. Now to display the name of employees that begin with 'a', you can type in the command like, you know, `select * from table name where employee name like 'a%'` in codes. So when I say `a%`, all those names starting with 'a' and having any letters or any characters after that would be selected. So guys, that's how you can write a query to find the name of employees that begin with 'a'. Now suppose if you want to write a query to find the names of employees that end with 'a', what you can simply do is you can again write the similar query like, you know, `select * from table name where employee name like '%a'`, right? So where the `%` comes forward, that means, you know, all the names that start with any alphabet but end with 'a' will be considered.

Now let's move forward to our next question; that is, write a SQL query to get the third highest salary of an employee from an employee table. Now to get the third highest salary of an employee from an employee table, you can write a query as you can see on the screen. You can just mention `select top 1 salary from` and then write a subquery which says `select top 3 salary from employee table order by salary in a descending order as amp` and then again `order by salary in ascending order` for the outer query. So you can write a query like this, guys.

Now let's move forward to a next question; that is, what is the need of group functions in SQL? Now group functions work on a set of rows and return one result per group. So basically, some of the most commonly used group functions are the average, count, max, min, sum, and variance. So when you say what is the need of group functions in SQL, the need is basically because the group functions work on a set of rows and return one result per group.

Now let's move forward to a next question; that is, what is a relationship, and what are the different types of relationships? Relations or links between entities that have something to do with each other can be basically termed as relationships. So relationships can be also defined as the connection between the tables in a database, right? Now the different types of relationships are the one-to-one relationship, the one-to-many relationship, many-to-one relationship, and the self-referencing relationship. When you have a relationship between two tables, Table A and Table B, so when I say one-to-one relationship between both the tables, Table A and Table B, a single record in Table A will be related to a single record in Table B. Coming to a one-to-many relationship, a single record in Table A can be related to many records in Table B. Next, coming to the many-to-one relationship, many records in Table A can be related to one record in Table B. Coming to a self-referencing relationship, the self-referencing relationship basically means that you can have a single table out of which two columns are related to each other with a relationship.

Now let's move forward to a next question; that is, how can you insert null values in a column while inserting data? Now to insert null values in a column while inserting the data, you mainly have two ways: that is, either implicitly by omitting columns from a column list or explicitly by specifying the null keyword in the values clause. So as these are the two ways through which, you know, you can insert null values in a column while inserting the data.

Now let's move forward to the next question; that is, what is the difference between the `between` and `in` condition operators? The `between` operator is basically used to display rows based on a range of values in a row, whereas the `in` condition operator is used to check for values contained in a specific set of values. So if you have to explain with an example for `between` and the `in` condition operators, then you can use the example on the screen. You can just write a query like `select Staff from students where roll number between 10 and 50`. So all those records from the students table would be selected whose roll number stands between 10 and 50. Coming to the `in` condition operators, you can use a query like this, like you know, `select Staff from students where roll number in (8, 15, 25)`. So all those records from a student table would be selected where the roll number would be either 8, 15, or 25. So guys, that is the main difference between the `between` and the `in` condition operators.

Now let's move forward to our next question; that is, why are the SQL functions used? The SQL functions are used to perform some calculations on the data, to modify individual data items, to manipulate the output, to format dates and numbers, and also to convert the data types. So if you want to perform these activities or you know if you want to perform these actions, then you need to use the SQL functions.

Now let's move forward to our next question; that is, what is the need of a merge statement? This statement is basically used to allow conditional update or insertion of data into a table. So it performs an update if a row exists or an insert if the row doesn't exist. So basically, the need of a merge statement is that you know it allows conditional update or insertion of data into a table.

Now let's move forward to our next question; that is, what do you mean by a recursive stored procedure? A recursive stored procedure refers to a stored procedure which calls itself until it reaches some boundary condition. This recursive function or a procedure helps the programmers to use the same set of code n number of times. So basically, you'll first mention the boundary condition, and then you'll use the recursive stored procedure to check, you know, if it calls itself till it reaches the specified boundary condition.

Now let's move forward to a next question; that is, what is a clause in SQL? Now SQL clauses basically help you to limit the result set by providing a condition to the query. A clause helps to filter the rows from the entire set of records. So for a better understanding, the example is basically `where` and `having` clauses. So when you write a query, you're having these two particular clauses; you basically mention a condition into these particular clauses, right? Like `where student number = 2` or `having roll number > 5`, and so on, right? So that's how you can use a clause in SQL.

Now let's move forward to a next question; that is, what is the difference between the `having` clause and the `where` clause? Now the main difference between the `having` clause and the `where` clause is basically that you know the `having` clause can be only used with the `select` statement. It is usually used by the `group by` clause, and whenever `group by` is not used, `having` basically behaves like a `where` clause. Coming to the `where` clause, the `where` clause is applied to each row before they are part of the `group by` function in a query. So the `having` clause is basically used with the `select` statement, and it is usually used in the `group by` clause. When the `having` clause is not used with the `group by` clause, the `having` clause behaves like a `where` clause. So guys, that was about the difference between the `having` clause and the `where` clause.

Now let's move forward to our next question; that is, list the ways in which Dynamic SQL can be executed. The ways in which Dynamic SQL can be executed are by writing a query with parameters, using `exec`, and by using `sp_executesql`. So there are basically three ways in which Dynamic SQL can be executed: that is, by writing a query with parameters, using `exec`, and using `sp_executesql`.

Now moving forward to the next question; that is, what are the various levels of constraints? The constraints, as I mentioned before, are basically the representation of a column to enforce data entity and consistency. So mainly, there are two levels of constraints: that is, the column-level constraint and the table-level constraint.

Now let's move forward to our next question; that is, how can you fetch common records from two tables? Well, you can fetch common records from two tables by using the `intersect` statement. So the syntax of the `intersect` statement is as you can see on the screen; it's basically `select column one, column two, and so many columns from the table name where condition`. Basically, you mention a condition over here when you mention the keyword `intersect` and then again mention another table name, right? So that is again you mentioned select the columns from a specific table where the condition matches. So that's how you use the `intersect` command. So for your better understanding, you can see the example on the screen. You can see, you know, that I have used `select student ID`, that is basically a single column from `student`, then use the `intersect` command, and then again I have mentioned `select student ID from a different table`, that is `exam`. So that's how you can fetch common records from two tables.

Now let's move forward to a next question; that is, list some case manipulation functions in SQL. So there are mainly three case manipulation functions in SQL: that is, the `lower`, `upper`, and the `initcap`. Now talking about the `lower` function, this function basically returns the string in lowercase. It takes a string as an argument and returns it by converting it into a lowercase. The syntax of this particular function is basically `lower` and in brackets you mentioned strings and quotes. Now moving forward to the next function, that is, the `upper` function. This function returns the string in uppercase. It takes a string as an argument and returns it by converting it into an uppercase, right? So the syntax for this particular function is `upper`, and in brackets, you mentioned the string within the codes. Moving forward to the third function, that is, the `initcap`. This function returns the string with the first letter in uppercase and the rest of the letters in lowercase. So the syntax for this function is basically `initcap`, and in brackets, you mentioned the string with quotes. So guys, these were the three case manipulation functions in SQL.

Now let's move forward to a next question; that is, what are the different set operators available in SQL? So the different set operators available in SQL are `union`, `intersect`, and the `minus` operators. So let's talk about `union` first. So when you consider two queries, that is the left query and the right query, and you apply the `union` operation, you will see that, you know, it will combine rows from both those queries. You'll get an output of, you know, all those records from the left table, that is basically the left query, and also from the right query, that is the right table. Moving forward to the next operation, it is the `intersect` operation. So when you apply the `intersect` operation to the left query and the right query, you'll see that, you know, you'll get only those rows which are common in both the queries, right? So for example, you have 10 rows in the first table and 10 rows in the second table, but the common rows in both these tables are just two rows, so you'll get only those two rows as an output to this particular operation. Moving forward to the third type of operation, that is the `minus` operation. So when you apply `left query - right query`, you'll see that, you know, you'll get only those rows from the left query which are not included in the right query as an output. And when you apply the operation of `right query - left query`, you'll see that, you know, you'll get only those rows as an output from the right query which are not included in the left query. So guys, these were the different set operators available in SQL: that is, the `union` operator, the `intersect` operator, and the `minus` operator.

Now let's move forward to a next question; that is, what is an alias command? Now an alias name can be given to any table or any column. So this alias name can be referred to in the `where` clause to identify a particular table or a column. So that's basically an alias command. So for example, if you see on the screen, you see a query, right? Like `select m.employeeID, department.result from employee as m, Department as dept where m.employeeID = department.employeeID`. So what I've given over here is that I've given an alias name to the employee table as `m`, and for the Department table, I've given an alias name as `dept`. So that's how you can use the alias command, guys. Let's move forward to the next question now; that is, what are aggregate and scalar functions? The aggregate functions are used to evaluate mathematical calculations and return a single value. These calculations are done from columns in the table. So for example, if you need to consider the aggregate functions, then you can consider the `max` function and the `count` function as an aggregate function. Now coming to the scalar functions, the scalar functions basically return a single value based on the input value. So if you need an example for scalar functions, then you can consider the `ucase` and `now` as scalar functions as calculated with respect to the string. So guys, this is what aggregate functions and scalar functions mean.

Let's move forward to the next question; that is, how can you fetch alternate records from a table? When you answer this question of how you can fetch alternate records from a table, please make sure that you mention a point that you can fetch alternate records; that is, both the odd and the even row numbers. Now to display the even row numbers, you can use the command like, you know, `select studentID from (select row_number() over (order by studentID) as rn, studentID from student) a where mod(rn, 2) = 0`. So we're using this function of `where mod(row number, 2) = 0`, right? So when you divide the row number with 2 and if you get the remainder as 0, then that particular row number would be an even number, and similarly, if you get a remainder as 1, then that particular row number would be an odd number. That's how you can segregate the alternate records; that is, the even number records and the odd number records. You just have to mention the condition `mod(row number, 2) = 0` for even and `mod(row number, 2) = 1` for odd.

Now let's move forward to the next question; that is, name the operator which is used in a query for pattern matching. The operator which is used in the query for pattern matching is basically the `like` operator. So in the `like` operator, you can use either the percentage sign or the underscore sign. The percentage sign basically matches to zero or more characters. If you use the percentage sign in the query like, you know, `select * from students where student name like 'a%'`, so all those student names whose name starts with 'a' and ends with any character will be taken into account, and all the information related to all those records will be retrieved. And coming to when you use the underscore sign, the underscore sign basically matches exactly one character. So when you use the underscore sign in the query like, you know, `select * from student where student name like 'ABC_'`, so all those records, you know, whose student name has characters which match the pattern 'ABC' and any character present after that will be taken into account. So guys, that's how you can use the `like` operator for pattern matching. You can either use the percentage sign with it or an underscore sign with it.

Now let's move forward to the next question; that is, how can you select unique records from a table? Well, you can select unique records from a table by using the `distinct` keyword. So for your better understanding, you can write a query like, you know, `select distinct studentID from student`. So with the help of this query, all the unique records from the student table will be selected.

Let's move forward with the next question; that is, how can you fetch the first five characters of a string? Now there are obviously a lot of ways to fetch the characters from a string. So for your understanding, I've mentioned two examples over here: that is, either you can use the `substring` command or the `left` command. So when you use the `substring` statement, you can use the statement like, you know, `select substring(student name, 1, 5) as student name from student`. The first five characters of `student name` will be retrieved from the student table. Now similarly, when you use the `left` statement, you can use the statements like, you know, `select left(student name, 5) as student name from student`. So with this query again, all the first five characters of each and every student name from the student table would be retrieved. So that's how, guys, you can fetch the first five characters of a string: that is, either by using the `substring` statement or the `left` statement.

Now let's move forward with the next question; that is, what is the main difference between SQL and PL/SQL? Now SQL, as I mentioned before, is a query language that allows you to issue a single query or execute a single insert, update, delete, whereas PL/SQL, that is basically Oracle's procedural language SQL, allows you to write a full program of loops, variables, etc., to accomplish multiple operations such as select, inserts, updates, and deletes. So guys, that is the main difference between SQL and procedural language SQL. In SQL, you just have to write a single query to execute insert, update, or delete, and in procedural language SQL, you have to write a full program with loops and variables to perform multiple operations like insert, update, delete, and selects.

Let's move forward to a next question; that is, what is a view? A view is basically a virtual table which consists of a subset of data contained in a table. Since views are not present, it takes less space to store, and Views can have data of one or more tables combined based on the relationship. So, as you can see on the screen, I have two tables of, you know, n number of rows and columns. Now, once I execute a query to form a view, you can clearly see that, you know, it has combined the columns and the rows from both the tables and has created a view of both of these tables into a single table. That's what a view is.

Now let's move forward to the next question; that is, what are views used for? Views, as I just explained, basically refer to a logical snapshot based on a table or on any other view. It is used for restricting the access to data, making complex queries simple, ensuring data independence, and also providing the different views of the same data. So that's what views are used for.

Now let's move forward with the next question; that is, what is a stored procedure? A stored procedure is basically a function which consists of many SQL state statements to access the database system. Several SQL statements are consolidated into a stored procedure and are executed whenever and wherever required, which obviously saves time, and we can avoid writing code again and again. So, with the help of a stored procedure, you can make sure that, you know, several SQL statements are executed again and again, and you don't have to write the query for it again because, you know, you, if you just have a stored procedure for it, it will automatically execute the queries for you.

Now let's move forward with the next question; that is, list some advantages and disadvantages of a stored procedure. Let's talk about the advantages first. Stored procedures can be used as a modular programming, which means create one store and call for several times whenever it is required. They support faster execution and it also reduces network traffic, which provides better security to the data. Coming to the disadvantages of a stored procedure, the only disadvantage of a stored procedure is that it can be executed only in the database and utilizes more memory in the database. So guys, that was about the advantages and disadvantages of stored procedures.

Now let's move forward with the next question; that is, list all types of the user-defined functions. So there are mainly three types of user-defined functions: that is, the scalar function, the inline table-valued functions, and the multi-statement valued functions. So you mainly have to mention these three functions when you're asked about the different types of user-defined functions.

Next, let's move forward and understand what do you mean by collation. Collation is defined as a set of rules that determine how data can be sorted as well as compared. Character data is sorted using the rules that define the correct character sequence along with the options for specifying case sensitivity, character width, and etc. So that's what a collation is, guys. It is basically a set of rules that determine how data can be sorted as well as compared.

Now let's move forward with the next question; that is, what are the different types of collation sensitivity? The different types of collation sensitivity are the case sensitivity, the Kana sensitivity, the width sensitivity, and the accent sensitivity. So, guys, these are the mainly four types of sensitivities of collation. So I hope that you've understood till now.

Next in this session, let's understand what are the local and the global variables. Now, talking about local variables first, these variables can be only used or exist only inside the function. These variables are not used or can't be referred by any other function, right? So whenever you want to use local variables, then you need to understand the fact that, you know, they can be only used or exist inside a single function and they can't be referred by any other function. Coming to global variables, these variables are the variables which can be accessed throughout the program. So global variables cannot be created whenever the function is called, but yes, they can be accessed throughout the program. So guys, that was about the local and the global variables.

Next, let's move forward and understand what is auto-increment in SQL. The auto-increment keyword allows the users to create a unique number to get generated whenever a new record is inserted into the table. So this keyword is usually required when our primary key is used, and the auto-increment keyword can be only used in Oracle whereas the identity keyword can be used in the SQL Server. So that was about auto-increment in SQL, guys.

Next, let's understand what is a data warehouse. A data warehouse refers to a central repository of data where the data is assembled from multiple sources of information. Those data are consolidated, transformed, and made available for mining as well as to online processing. Warehouse data also has a subset of data called the data mart. A data warehouse can be understood as a central repository of data where the data is assembled from multiple sources of information. So guys, that was about data warehousing.

Now let's move forward and understand what are the different authentication modes in SQL Server and how it can be changed. The different authentication modes in SQL Server are basically the Windows mode and the mixed mode. So these two modes are basically used in SQL Windows. To change the authentication modes in SQL Server, what you can simply do is you have to follow the steps that are mentioned on the screen; that is, you have to first click on Start, then go to Programs, and go to the Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group. Now, to change the authentication modes in the SQL Server, you can follow the steps that I've mentioned on the screen; that is, you have to click on Start, go to Programs, go to Microsoft SQL Server, and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group. Then select the server from the Tools menu and select SQL Server configuration properties and choose the security page, right? So that's how you can change the authentication mode in the SQL Server, guys.

Now let's move over with the final question in the session; that is, what are STUFF and REPLACE functions? Talking about the STUFF function first, this function is basically used to overwrite existing characters or insert a string into another string. The syntax for this function is basically STUFF(string_expression, start, length, replacement_characters), where the string_expression is basically the string that will have characters substituted; start represents the starting position; length refers to the number of characters in the string which are substituted; and the replacement string are the new characters which are injected in the string. Coming to the REPLACE function, this function is basically used to replace the existing characters of all the occurrences. The syntax for this particular function is that REPLACE(string_expression, search_string, replacement_string), where every search string in the string expression will be replaced with the replacement string. I hope I am clear with the STUFF function and the REPLACE function. So, guys, these were the questions that could be asked in your interviews. [Music]

Now, what exactly is data science? Now, data science, in simple terms, is the process of deriving useful insights from data in order to solve your ball problems or in order to grow a business. Now, data science was introduced because we are generating an immeasurable amount of data. For example, there's a fact that we're generating more than 2.5 quintillion bytes of data every day, and at this pace, it's only going to grow because, right now, everything runs on data. So the idea behind data science is to take up all this data and, you know, derive useful insights or derive knowledgeable insights from this data so that you can grow your business or you can solve a problem. That's what data science is all about. The data is the key in data science, and since we are producing so much data, it is the perfect time for you to learn data science. Data science basically covers artificial intelligence, machine learning, natural language processing; or these processes are covered under data science. So that is one of the reasons why data science has become so popular, because of the amount of data we're generating; we need methods and technologies that can handle so much data and they can, you know, derive something useful from the data. So that's a small introduction to data science, and if you guys want to learn more about data science, I'll leave a couple of links in the description box.

Now let's move ahead to our topic of discussion. First, we'll understand why we need SQL for data science. So like I said, data science is basically all about deriving useful insights from data. Data science involves extracting, processing, and analyzing tons and tons of data. At present, what we need are tools that can be used to store and manage this vast amount of data. Now this is where SQL comes in. SQL can be used to store; it can be used to access and extract massive amounts of data in order to carry out the whole data science process more smoothly. So SQL, as a querying language, it can be used to perform a lot of querying operations, a lot of search operations, extractions, and editing and modifying your data. So we need a huge management system, and along with that, we need a language that can perform all the operations that we want to do on our data; that's why SQL comes in. So like I said, we'll be using MySQL today, and let's understand why I've chosen MySQL.

Now, first of all, MySQL is very easy to use. You have to get only the basic knowledge of SQL, right? You can build and interact with MySQL with just a few simple SQL statements, right? SQL statements are quite easy; like they're a lot like your English language. I feel like it's the most basic and the most understandable querying language there is. Apart from this, it is also very secure. Actually, MySQL consists of, you can say, a solid data security layer which will protect all of your sensitive data or your confidential data from any intruders. Passwords are encrypted in MySQL, so that's a good advantage of using MySQL. Apart from that, of course, it's open source, so it's free to download and to use. You can just go to the official website and download it in a matter of minutes. Then, of course, it is scalable as well, right? It can handle almost any amount of data, right? It supports large databases up to as much as 50 million rows or more, right? That's the amount of data that you can store in MySQL, and the default size limit is about 4 GB if I'm not wrong, and you can also increase this number to a theoretical limit of around 8 DB of data. I think you'll have to pay a little bit of money for that, but I feel like 4 GB is a lot, first of all, to have a data set of that size. Then another important point is that MySQL follows a client-server architecture. So this is where you basically have your database server, which is your MySQL, and you have many applications and programs as your clients, right? And these communicate with the server. This is where they query data; they save changes; they update the data; and all of that. Not only this, MySQL is compatible on many operating systems. It is easy to run on a lot of operating systems such as Windows, Linux, Unix, and so on. Now MySQL actually provides a functionality that the clients can run on the same computer as a server or they can even run on another computer, so basically communication via a local network or the internet. Another important point is that there are quite a number of APIs and libraries for the development of MySQL applications. So basically it has support for multiple programming interfaces, right? So client programming, you can use languages like C, C++, Java, Perl, PHP, Python, and so on, and all these languages are easily compatible; they provide APIs so that you can integrate and you can perform or you can build the applications using these languages. And since Python is one of the best languages for data science, MySQL is perfect for data analysis, storing data, and querying data. You can easily work with MySQL and Python to build applications and query data and all of that, right? Apart from that, it is also customizable, like I said, and it's also platform-independent, right? It's not only your client applications that can run under a variety of operating systems, but MySQL itself can be executed under a number of operating systems. The most important ones are your Mac operating systems, Linux, Microsoft Windows, and so on. Apart from that, we also have speed, right? MySQL is considered a very fast database program, and this speed is actually being backed up by a large number of benchmark tests. And apart from that, it's highly productive because it uses triggers; it uses stored procedures and Views, and this basically allows the developer to give a higher productivity. So these are a few reasons why you should go with MySQL, right? I feel it's one of the most easiest to use, and it's one of the most compatible databases that are there.

Now let's move on and discuss a couple of basics about MySQL. So we'll discuss the data types which come under MySQL. We have numeric, we have character string, we have bit string, Boolean, date and time, and timestamp, and interval, right? Under numeric, it includes integers of various sizes; there is a floating point of various precisions and formatted numbers. Under character strings, these data types either have a fixed or they have a varying number of characters. Now this data type also has a variable-length string which is called character large object, which is used to specify columns that have large text values. So it supports large text values as well. Apart from that, there is bit string. Now these data types are either of a fixed length or varying length of bits. Now there is also a variable-length bit string data type which is called binary large object. Now this is available to specify columns that have very large binary values, such as, you know, maybe images and so on. Then we have the Boolean data type. Now this data type, as the name suggests itself, it has true or false values, and since SQL has null values, a three-valued logic is used, which is unknown; that's the third value. Then we have date and time. So the date and time is like any other date variable; the date data type has your month and day and the normal date form, and similarly the time data type has components like hour, minute, and second. Now obviously these formats can be changed based on your requirement. Next we have the timestamp and interval data type. So the timestamp data type includes a minimum of six positions for decimal fractions of seconds and an optional with time zone qualifier in addition to your date and time fields, okay? So the interval data type will basically mention a relative value that can later be used to increment or, you know, decrement an absolute value of time or date or any of that sort, or basically a timestamp, right? So you can increment or decrement any absolute value using the interval data type. So guys, this was a little bit of information about the different data types that are there.

Now let's discuss a little bit of basics of SQL. Like I said, I'm just going to brush up a couple of topics because I'm hoping that you all have a good understanding of the querying language. So let's just brush up a little bit. So first of all, we have the first command, which is CREATE DATABASE. Now this is a very general-purpose command, right? It basically creates a new database for you. So the syntax is just CREATE DATABASE and the name of your database. Then once you create it, in order to initialize and use it, you just use the command USE and the name of the database that you created. And remember that at the end of each command you have a terminator, which is a semicolon, and also your commands are usually written in capital letters so that you can differentiate your commands from your table columns or table names and all of that. So it's a good practice if you write all your commands in capital letters. Next we have CREATE TABLE. Now tables are the most important part of a database, right? So CREATE TABLE is a simple command that will create a new table for you, and it can contain a lot of data variables of different data types, right? So the syntax is simple; the command is CREATE TABLE, the name of the table you want to create, and then within the table whatever variables you want, you can mention the name of the variables with their respective data types. Like for example, if your variable is age, then your data type will be an integer or something like that. Similarly, you can add another variable like name, and you can have the data type as a character. So it's as simple as that; it's very understandable language. And then let's talk about INSERT INTO. Now this command is used to insert new data into your table. Now usually what happens is when people insert values into the table, they forget the data type that they've defined under that particular variable. So remember that the values that are inserted, it must align with the defined data types. So for example, if your variable is age and instead of putting your numerical 3, you've put your character 3, basically you've typed out t h r e e, and that's not going to work because you already defined your age variable as integer, so you'll get an error there. So make sure that the values that you are inserting into your variable are of the same data type as you've defined your variable as, okay? So make sure that happens. Now these are very simple things, guys. I'm sure you guys are aware of this. Now let's look at our next command, which is SELECT. So this is one of the most important commands when it comes to SQL for data science, and because mainly it's all about extracting useful insights and extracting particular type of data from your database, right? We'll see how often we'll use this command when we perform our demo today. This is one of the most simplest and in fact it's one of the most important commands in SQL, okay? So basically SELECT will select a specified table or a column and it will extract the values from it, okay? SELECT * FROM and table name is your syntax. Now we'll be using this in the demo, so don't worry if you do not know exactly what this does; just remember that your SELECT command is for extracting data from your table. Next we have the UPDATE command. So UPDATE will basically allow you to modify any values that are stored in your table, and the WHERE clause here will select the variable or value that you want to change. So it's basically it'll highlight the variable or the value or I'll try to identify the value that you want to change. Next we have the DELETE command. Now DELETE will basically delete data from your data set or from your table, as the name itself suggests. So DELETE FROM the name of your table and WHERE with the condition; it's as simple as that. Next we have DROP TABLE. So this command is basically used to delete a table and all the rows in the table. So your table will get deleted from your database; that's what happens with DROP TABLE. These were a couple of commands that I thought you should brush up on. I'm sure you guys are already aware of these commands, but in case there are a few, few who don't know much about SQL, I'll leave a couple of links in the description box; you can go through those videos and then maybe come back to this if you're specifically looking for SQL for data science.

Now let's get started with our demo, which is quite interesting. So guys, with this demo, I'll be using the MySQL workbench. So it's quite easy to install; it'll just take like 15 to 20 minutes. I'll leave a link in the description box; we have a short video where it may showing you how to install the whole workbench. So once you've installed MySQL, we'll start by creating a database and we'll import a data set into our workbench. So I'm going to import an existing data set, right? I'm doing this because we are doing a more advanced tutorial; this is not about creating tables and, you know, extracting values from tables; instead, this is about deriving useful insights from your data. So usually for data science, you don't have to sit down and create tables and, you know, do those basic commands; instead, you have to explore the data variables. So usually there's a humongous data set that needs to be explored and analyzed in order to derive something useful from it, right? So that's what we're going to do today. So I've already imported a CSV file; let me show you what the file looks like. So this is our CSV file, and this basically contains details about employees; so basically the name of the employee, title is the job title of the employee.

Department is the department that the employee is working in. Then we have the annual salary; we have the hiring date; we have the start date in the present position; we have the salary; and we have the employment category—whether you're a full-time employee or whether you're a part-time employee. So our data set has around 32,000 observations. Right, so this is a very huge data set, and I basically downloaded it from the internet. You can find a lot of data sets on the internet, and you can perform all of the data analysis in no time.

So if you don't know how to import a data set in your MySQL workbench, I'll quickly show you how it's done. So I've already created a database here. Now creating a database is as simple as this, right? You just have to do `create database` and the name of the database—let's say `tutorial`—and then if you want to use it, you just use the command `use tutorial`. Right, so basically the `tutorial` database gets activated. Now all you have to do to run is you have to use this, right: `use tutorial`. So we've basically activated our database. Now, for this tutorial, I've already created a database, so I'm going to use that database itself. The name of my database is `students`, all right. So let's activate this database. Right now, in this, I have a couple of tables, and we are going to be focusing on this table, `employee details`. So this is the table that I imported.

So guys, for those of you who don't know how to import a CSV file into your MySQL workbench, all you have to do is go to tables, right-click on any table, and go to `table data import wizard`. Right-click on this and browse for your CSV file. Okay, just to take an example, I'll consider this CSV file. I'm not going to import the CSV file that we're going to be using right now because that is a very, very huge CSV file, and it'll take a lot of time for me to import that CSV file into the workbench. To save up on some time, I'll import a small CSV file and I'll show you. All right, so I'm selecting this file, `students marks`. Let's open it, right, and go to next. After that, create a new table. Now, basically what you're doing here is you're going to create a new table that corresponds to all the columns that are there in your CSV file. Either you can create a table on your own and click on `use existing table`, or you can allow MySQL workbench itself to create a new table for you. That's what I'm going to do because obviously it's simpler. Then click on next. So this is basically all the fields that are there in my CSV file. It will collect all the fields in my CSV file and it will create a table out of it, right? This is my CSV file; basically it has name, gender, date of birth, math, physics, chemistry, and all of that. These are just records of students and their marks. Then if I click on next and next again, yeah, data gets imported; next five records are imported; click on finish and refresh here. You see `student marks`. So this was the CSV file that I just imported into my SQL workbench. So guys, that's how you import a CSV file as a table into your MySQL workbench.

So if you want to see this table, right, the CSV file that we imported as a table, all you have to do is `Select * from` and the name of the table; it is `student_marks`. So let's just run this. So here you can basically see the entire CSV file that we imported into a table. So guys, that's how simple it is to import a CSV file into your MySQL workbench in order to perform data analysis. So now let's clear this up. So for this demo, like I said, we'll be using the `employee details` data set. This is a very huge data set, and let's just get started. I've already imported the data set here as a table, right? If you take a look at this `employee details`, so these are the columns in my table: we have the name of the employee; title is the job title of the employee; department is the department he works in; salary, annual salary; then we have hiring date, start date, salary Basics, and we have employment category, all right. So let's start by performing some sort of data analysis.

So first what we'll do is let's just view the entire table that we have. For that, all you have to do is `Select * from` the name of the table; `employee details` is the name of the table in my case, so I'll just run this command, right. So this is the entire table that just got loaded, all right. So this will just extract your entire table for you since I did `select * from` and the name of the table, so my entire table is extracted here, right? If you take a look at this, the whole table is being extracted here, right? Now let's do something a little more complex. Now let's write a query to find the salaries of all the employees. For that, what you have to do is `select` again. Now the name of the column that has the salary; okay, in our case it is `salary annual`, right? So let's write that down: `salary annual`, right, `from` the name of your table, `employee details`. Okay, so let's run this. So this query basically just gave me the `salary` column in my table, right, `salary annual`. This is the salary of all the employees that are there, right? It's as simple as that.

Now let's write a query to display the unique designations for the employees. Basically, you need job roles we'll display. So for that, again we have `select` because we're extracting; then we have a keyword called `distinct`, since we are trying to display the unique designations; it'll just take the designations that are unique; it won't take your repetitive designations. For example, there might be 10 employees who are working as data analysts, so we'll just consider that as one. So we're just extracting the unique designations for the employees; that's why we have the word `distinct` here. Next, a job title is in the variable `title`, so that's why I've written `title` here, and then we have `from` and the name of your table, right? Let's run this command. So here you can see that there are different job titles in our data set. We have Sergeant, we have police officer, we have Chief contractor expeditor, we have civil engineer, concrete laborer, we have traffic controller, pool motor; this is police officer, and this is police officer assigned as detective. Wow, that's interesting, right? So basically this query gave us the unique job roles that are there in our data set.

Now let's try something else. Let's write a query to display the unique departments with their jobs. So let's extract that: `select` again, since we are trying the unique, we are going to use a `distinct` keyword, and we are going to extract the unique departments and the job titles, and `from` the name of the table. So let's run this code. Now, under Police Department, we have different job titles; that's why this is repeated here, and we have police officer. Then there is Fleet and facility management, under which we have a chief contractor as expeditor. Under Water Management Department, we have a civil engineer, and so on, right? So guys, this query was pretty simple; it just gave us the distinct departments according to their job titles.

Now let's perform another query. We'll write a query to list the employees who are working in a particular Department. Let's say the fire department. Again, since we're extracting, we'll use the keyword `select`. After that, `select * from` and the name of your table, `where`. So this is where the `where` clause comes, right? We're trying to identify a particular department, so we'll put `where department` in the name of the department that we're looking for. Let's say fire department; that sounds interesting. So let's run this. All right, so here you can see that we've just got employee details of all the employees that are there in the fire department. These are their salaries; these are the dates that they were hired on; and apart from that, this is the employment category—full-time, part-time; salary basis is whether you're getting paid hourly or whether you're getting paid on a daily basis. So these are the details of all the employees that are working in the fire department. If you see that here, it's entirely Fire Department. So that was also quite simple. So this is how SQL is—the language is very, very simple because it's pretty understandable; like you can read the statement and you can understand what exactly I'm trying to extract or what exactly I'm trying to do.

Next, let's try to do something interesting. Let's say that we want to write a query to list the employees who do not belong to a particular Department. Let's say that we're trying to list out the employee details of employees which are not in the police department. So for that, it's quite similar to our previous query. So you write `select * from` the name of your table again, `where Department not in`; that's the only difference, okay, `not in` and the name of the department that you want to exclude. So this time, let's say police department. So we want only details of employees that are not there in the police department. So let's run this. So all the Departments here will have everything apart from your Police Department, okay? So we have fire, we have water management, we have law, we have streets and sand, we have finance department, we have Fleet and facility management, and all of that. So basically we excluded our police department and printed out the details of all the employees which are in every other department apart from the police. All right.

So now let's write a query to list the employees who joined before a particular date. So for that, again we'll start from `select * from` the name of your table, right, and we'll add the `where` clause, and here we'll mention our original hiring date, since that's the name of the variable that has the higher dates in it. Let's keep it less than a particular date, okay? Let's choose the first of January 2000. Let's run this code, and so when you run this code, you'll find all the employees that were hired before 2000. So if you see original higher date, all of this is before 2000. Some of them were in 1994, 1996, 1984, and 1987. So the only four employees who were hired before the year 2000, basically before the 1st of January 2000.

Now let's try another query. Let's write a query that will display the average salaries of all the employees who work at a particular Department. Okay, let's choose the surgeon department. So basically we're going to display the average salaries of all the employees who are working as surgeons. So for that, again it starts from `select`. Since we have to calculate the average salaries, we'll use a function called `average`, which is a predefined function in SQL, and `average` of which column? It is a salary column, `salary annual`, and let's mention the name of the table, `from employee detail`. Let's write down the whole statement and then we'll see what the error is. This, and we are going to select the job title as a surgeon; basically the average salary of a sergeant. Let's run this first and we'll find out what the error is. Okay, there is no error; I have no idea why I'm getting this. So the average salary is around 1 lakh 6000 and change, right, for a surgeon.

So now let's try another query. What we can do is we'll write a query to display the details of a particular employee; some name we'll select at random, okay? `Select * from` the name of your table, `employee details`, `where name is equal to`. Let's look for a particular name, Ahmad Syed, okay? So this is the name of the employee; let's paste that name over here, right? Hopefully this should give us an output. Let's run this. So now we have the details of this particular employee whose name is Ahmad Syed; his title, job title, his Department, his salary, all the details about him. So we just printed all the details about a particular employee.

Now let's try something else. Let's write a query to list the employees whose salary is, let's say, more than 3,000 after giving a 25% increment to their salary. Now let's do a little bit of math. So we list down employees whose salary is more than 3,000 after giving them a 25% increment. So let's write down a query for that. So again, start off with `select * from` the name of your table, `where`. Here we specify the condition, basically after giving them a 25% increment—1.25 into the salary, so `salary annual`—and after giving them a 25% increment, their salary should be at least three thousand, all right? So this is exactly what we're doing here. Let's run this code and let's see if we're getting anything. So here are the employees whose salary is more than three thousand dollars after giving them a 25% raise. So basically these guys are promoted; this is a list of all the employees. So that's quite simple, guys; it's basic math implemented in one line of code. That's how simple SQL is, and a lot of data scientists require this kind of tool because querying even your complicated math and even complicated things from your database becomes very easy when you make use of SQL languages. It becomes extremely easy to even do the complex things. Now I just did this in one line.

So now let's try something else. Let's write a query to list the employees whose salary is less than a particular number, okay? Let's say less than 3,500 dollars. So let's write a query basically for employees whose salary is less than three thousand or three thousand five hundred, `where salary annual is less than`, let's say, 3500. So let's run this line of code. All right, so we have a couple of people whose salary is less than three thousand; so we have 2756; like maximum of these people have 2756, okay? So basically this is a list of employees whose annual salary is less than three thousand dollars. That's also quite simple to do; it's just one line of code.

Now let's try something else. We'll write a query to list the names and a particular set of details about an employee who's joined before a particular date. Let me write it down for you, and then we'll understand what exactly I'm doing. So `select`, okay, now we'll define a variable so that we can basically extract a number of columns, okay? So let me write this down, and then I'll tell you what exactly I did here: `name`, and let's also get their salary, right, `original hiring date`; then we'll also get the salary `from` the name of the table `where` the hiring date, let's say, was lesser than—I'll give a random number—01/02/2008. Now what exactly I'm doing here is I'm basically listing out the name of the employee, the hiring date, and the salary of all the employees that have joined before a particular date, okay? Basically before this date; that's what I've done here. Let's run this line of code and let's see if it works, right? So here we have the name, the hiring date, and the salary of individuals that have joined before a particular date in 2008. So it's as simple as that.

Now let's write a query in SQL to list all the employees who joined on a particular date. Okay, let's say we want the details of all the employees who joined on October of 2013 or something like that. For that, again it starts off with `select * from` the name of the table, we'll add the `where` clause along with the hiring date, `original higher date`, a particular date; let's say 08/20/13. Let's run this line of code. So basically we list down employees that were hired on this particular date, okay? These are details of all the employees that were hired on the same day. So we have around six employees that were hired on the 8th of 2013, some date, right? So guys, that's what you see; SQL is a very easy language; you just have to understand what you're trying to extract; that's all. You just have to know like five to ten basic commands, and these basic commands can do wonders; they can extract and manipulate data in such a way that you know you can perform proper data analysis, data processing, and so on.

Now let's try one last query. Let's write a query to list the employees whose annual salary is within a particular range. For this, again we have `select * from` the name of the table, `employee details`, and let's add the `where` clause, and here we will say `salary annual is between`—another keyword—so `between` two numbers, okay? Let's say between uh 24,000 dollars and let's say 50,000, right? Let's run this line of code. All right, so here you can see that all of these employees have a salary range between 25,000 and 50,000. So 43,201, we have forty-two thousand; yeah, forty-four thousand; we have forty-five thousand; forty-eight thousand is the maximum salary, all right? So this is basically how you perform querying using SQL. [Music]

What is PostgreSQL? Now PostgreSQL is an open-source object-relational database system with 30-plus years of active development in the industry. So basically, if you have to understand PostgreSQL, guys, PostgreSQL is basically a programming language, or maybe you can understand that, you know, a language to which you can handle open-source relational database systems and then handle databases. PostgreSQL is the world's most advanced open-source relational database. So guys, this is a really great topic to start learning about databases. So if I have to just define PostgreSQL for you, then you have to understand these two points over here: that it is open source and it is used for handling databases in the form of an object-relational database system. So the data is present in the form of a relational database, but yes, it is object-oriented; that's where PostgreSQL comes into picture.

Now, since PostgreSQL is so popular in the industry, next let's look into the features of PostgreSQL. So the features of PostgreSQL are, as you can see on my screen, that is basically the data types, so data integrity, performance, reliability, security, and extensibility. So talking about data types, when I say data types, what I mean by that is PostgreSQL provides various kinds of data types to store data in any format, such as, you know, integer, numeric data type, JSON, XML file, maybe in the form also of point, line, circle, polygon, and also you can have custom data types. So there are various kinds of data types, like, you know, the primitive ones, the structure, the document, geometry, and customizations. So we'll not get into the depth of, you know, the different data types related to PostgreSQL; you can go to their official document and check what are the different data types that, you know, PostgreSQL provides. Well, I would leave that to you.

Moving on to the next feature, data integrity. So when I say data integrity, what I mean by that is, you know, your data is secured. So basically, whatever data that you have, it's made sure that, you know, there's no redundancy, and then it's stored in the proper format with the help of, you know, various constraints and keys used in databases, like primary key, foreign keys, exclusion constraints, unique constraints, explicit locks, and so on, right? So that's how basically your data integrity is met.

Coming to the next feature, that is performance. Now performance is something that's very important to all of us, right? Because all of us want good performance for any action that we do on an industry basis, right? Now, since PostgreSQL meets with good performance standards, that clearly implies that, you know, it has been used for more than 30-plus years of active development. Now, to enable performance in PostgreSQL, we have various features like, you know, indexing, or maybe a sophisticated query planner, multi-version concurrency control, table partitioning, just-in-time compilation of expressions, and so on.

Now moving on to the next feature, that is reliability. Now PostgreSQL also proves itself in the factor of reliability, that is because, you know, it has various functionalities like write-ahead logging, replication, point-in-time recovery, active standbys, and table spaces.

Finally, coming to extensibility. Now, obviously, any database that you wish to use, you would obviously want to extend it to maybe any application that you might be using in the industry or maybe in your company, or also on an individual basis. Well, PostgreSQL provides all those functionalities with the help of stored functions and procedural language, foreign data wrappers, and many extensions that you'll see further in the session. So guys, these were the main six features of PostgreSQL: that is data types, data integrity, performance, reliability, security, and extensibility. So now that you know what is PostgreSQL, let's next look into how you can install PostgreSQL. So what I'm going to do is I'm going to install PostgreSQL on Windows. Apart from that, if you want to install PostgreSQL on any other operating system, well, the steps are really simple, and the steps are almost the same. So let's get started by installing PostgreSQL. So what I'm going to do is let me open my Google Chrome, and then let's say I just type in PostgreSQL.

SQL download right. So once I type in in, you have to first go to the official website of this, that is postgresql.org. Download. So this is where basically you'll have to go to first start installing PostgreSQL. So what I'm going to do is basically I have to install on Windows, right? So over here you have to start choosing your operating system. So if you wish you install a Linux, let's say you know Ubuntu, then you would choose this option, but since I'm going to install on Windows, I'm going to simply choose this particular option.

So if I click on Windows over here, you'll be next redirected to this particular page. Now this is the page basically you have to install the installer, right? So basically every operating system that you choose, the official website of PostgreSQL will redirect you to a particular page which will have this particular installer. So over here you can see that I have the Windows installer, and then I have to install, and then you can see the platform support, right? So what I'm going to do is I'm gonna just click on this option, download the installer.

Now once I click on download the installer, this is where basically you have to choose your configuration, right? So either it is Linux or Windows or Mac OS, that's completely your choice on what operating system that you wish to choose. Since I've been installing on Windows, I'll choose Windows 64-bit, right? So I'm going to choose this particular option of download, and please remember the fact that you know, try to install the most latest version so that you can get the maximum features that you want. So I'm going to install the 11.4 version for Windows 64-bit, right? So I'm going to just click on download over here, and then you see that you know you'll be redirected to this particular page that you know, thank you for downloading PostgreSQL, and also on the left-hand side you'll see that you know PostgreSQL is getting downloaded, right? So let's wait for it to download. All right. So as you can see on my screen it has got downloaded, so I'll just double click it so that we can open.

Now once you double click on the setup, you'll see that you know this particular dialog box opens which says welcome to PostgreSQL setup wizard, right? So now you just have to click on next, and then you have to choose the installation directory. I'm gonna let it be as it is. So by default - C program files PostgreSQL and level, so that will be basically my installation directory, and then I'll click on next. Once I click on next, you'll get an option basically on the various components that you wish to install. Well, I wish to install all of them, so basically I'm installing the server, the PGAdmin, the Stack Builder, and the command line tools. So now over here let me tell you that you know the PGAdmin is the official GUI for PostgreSQL, so we'll be working on the GUI for this particular session. So I'm going to just let it be as it is since all of them are checked in, and then I'll click on next.

Once I click on next, I have to next choose the directory under which I'll basically store my data, right? So this is basically my data directory that is C program files PostgreSQL 11 data. So I'm going to let it be as it is, and then I'll click on next. Once I click on next, I have to mention my password for the database super user. So just mention the password, any password that you wish to, and please remember the fact that you know you have to remember this password to configure your server, right? So do not forget this password, and please make sure that you remember this password. After that, just click on next again, and then you have to select the port number. So I'm going to let it be as it is. So basically my server will run on the port 5432, and then I'll click on next.

Once I click on next, you'll see that you know I can choose the default locale to be used by the new database cluster. So I'm going to let it be as it is, and then I'm going to click on next. Once I click on next, you'll see that you know basically the following setting will be used for installation, that is basically whatever you have selected till now will be shown over there, that is the installation directory, the server installation directory, the data directory, the database port, the database super user, and so on, right? And then I'll click on next over here again, and now you'll see a confirmation that you know the setup is now ready to begin installing PostgreSQL on your computer. If you're fine with it, you can just click on next, else you can just go back, make the changes, and then again come back to this particular dialog box, right? So I'm fine with it, so I'll just click on next over here, and then you'll see that you know PostgreSQL is getting installed on my system. So let's wait for it to install. All right. Now once the installation is done, you get a confirmation wizard that you know the setup is finished installing PostgreSQL on your computer, right? So you can just click on finish, and then if you want to launch the Stack Builder at your exit, you can just check in this box, but I'll just uncheck this particular box, and then I'll click on finish.

Once I click on finish, basically guys, your installation is done. Now if you search for PostgreSQL on your system, you'll clearly see options of the various stuff that we have installed, right? So as you can see on my screen, we have PGAdmin, we have the SQL shell, we have the documentation, the PGAdmin documentation, the release notes, and so on, right? So what I'm going to do is I'm going to open the SQL shell and also the PGAdmin, so let me just open. All right. Now once you open the PGAdmin, you basically are asked for the master password. So if you remember while installing I asked you to enter a password, right? So that's basically the password that you have to mention over here. So I'll just mention my password.

Right now once the password is entered, you'll clearly see that you know we have a server, and then automatically the server gets connected to databases and the super user database that is postgres, right? Under this particular database what we're going to do is we're going to basically use the different commands, that is these different SQL command categories, and then we're going to create a schema table, and then we're going to choose how we can play around with databases, right? So on the SQL shell what you can do is you can again similarly connect to the server. So you just basically have to click on enter because you're connecting your server on the localhost. So I'll just click on enter, that the database, basically the super user database is postgres, so click on enter again. The port has to be the same that is 5432. I'll click on enter again. The username will be postgres, so I'll just click on enter again, and password is basically what password you mentioned while installing, right? So you'll mention the same password, and then you'll see that you know once you hit on enter you'll clearly see that you have been redirected to postgres. So basically that's how guys you can configure server either on the PGAdmin and also on the SQL shell.

So guys, that was about installation of PostgreSQL on Windows. I hope you've understood all the steps. So now that you've installed PostgreSQL on your system, next let's look into the SQL command categories. So as I said, there are mainly four command categories, that is the data definition language commands, the data manipulation language commands, the data control language commands, and the transaction control language commands, right? So basically guys, these are the main four command categories of SQL, that is the DDL commands, the DML commands, the DCL commands, and the TCL commands. The DDL commands basically consists of the commands which can be used to define your schema, right? So you can create a table, you can create a schema, you can create a view, and so on, right? So basically all those commands which define the database of the schema, basically how your data has to be represented and what would be the very stable, so maybe let's say which table will be related to other table and so on, will be all under this particular section, that is the data definition language commands.

Coming to data manipulation language commands, the DML commands basically consists of those commands which deal with the manipulation of data present in the database. So all the manipulation that you'll do in your databases will be with the help of the data manipulation language commands. Coming to the data control language commands, the data control language commands basically includes those commands which deal with the rights permissions and other controls of the database system. You're like, you know which database has to be granted to any specific user or maybe that particular database will be open to public and so on. And finally coming to transaction control language commands, so the transaction control language commands basically include those commands which mainly deal with the transaction of the database. So guys, these are mainly the four different command categories, that is the DDL, DML, DCL, and TCL. So without wasting any further time, let's look into the DDL commands. Now what I'm going to do is I'm going to show you how you can write commands on the SQL shell and then I'm going to use the PGAdmin, right? So it's really simple. PGAdmin is the GUI for PostgreSQL. In today's market in industries, people are mostly using PGAdmin because you know they can connect this particular database to various other external tools also so that you know they can manipulate the data and maybe they can generate reports and so on, right? So I'm going to initially show you on SQL shell for few commands and then I'll completely shift over to the GUI.

So now let's say you know you want to create a schema. How do you think you can create a schema? Well, the command is really simple. For that you'll have to use create, right? So what you'll do is basically you'll type in create schema, and let's say we mentioned the schema name to be information, right? Right. So I'm going to use caps so that you understand that you know that's a particular syntax, and the small case lets us to understand that's the name that I'm giving and that's completely your choice on how you wish to do, and then I'll end with a semicolon and click on enter. Once I click on enter, you'll see an output that you know creates schema, that means you know a schema has been created. Now if I go back to my PGAdmin and then let's say you know I just refresh over here, so automatically you'll see a schema that is information, right? So basically whatever I've created in SQL shell is automatically seen in PGAdmin, right? So that's the reason I told you it's easy to visualize and use GUI over here. Now similarly if you wish to create a new scheme over here, what you can do is you have this schema option, right? You right click over here, choose create, and choose create schema. Automatically you just have to mention the name. Let's say I mentioned sample, and then I'll leave the other details to be the same, that the security default privileges and SQL, right? So in SQL you'll basically see that you know the syntax that I just mentioned in this SQL shell, that is create the schema and then schema name and authorization postgres, that's basically our database super user. Well, that's by default in SQL shell because you know we are already under postgres, so that's the reason we didn't have to give it over there. So I'll just click on Save, and then once I click on Save you'll automatically see that a schema has been created, that is basically sample. So now I have the information schema, the public schema, and the sample schema, and the public schema is created by default, and the information was the one that I created in SQL shell, and the sample is the one I created in GUI. So you see, right, how simple it is. Now if you're getting confused how you can write queries in GUI, well don't worry, we have a query tool also. So if I right click over here and then if I choose query tool, you'll see that you know automatically you'll get a workspace where you can basically put all your queries. I'm not going to do that now.

Next what I'll do is let's say you know we want to use this particular schema. So what I'll do is I'll just type in the query set search path to, and then I'll mention the schema name, right? So I'll mention information over here. So automatically you'll see an output that you know it is set to information, right? So whatever actions that I wish to perform like you know creating tables or maybe views and all, all of them will be basically under this particular schema. Now once the path is set, let's say you know we want to create a table, right? So for that you'll type in create table, and then you'll mention the table name. So let's say I mentioned students, and now each student will basically have various attributes, right? For example, let's say I am a student. Now I'll have a name, I have an age, I have a date of birth, and so on. So basically all those values will be a column. So I'll just put it in brackets, and let's say I mentioned student ID and int to be data type, and let's say further I again mentioned student name, and then let the data type be varchar 255 characters, right? And then what I'll do is I'll put a semicolon at the end. Once I click over here, once I click on enter, you'll clearly see an output that you know create table. Now let's go back over here and then let's just basically refresh the schemas, right? So I'll just refresh the schemas, and under the information table you'll clearly see an output that you know we have a table students, and then it has columns student ID and student name. So basically that's how you can create a table basically on the SQL shell, guys.

Now if similarly if you wish to create a table in the PGAdmin, what you do is you right click on the table over here, go to create, choose table, and then basically you have to mention the name, right? So for example, let's say we mentioned the table name to be teachers, and then the owner to be postgres, the schema to be information. So you'll have to basically choose the schema under which you wish to create table, and then you click on save. So if you click on Save without choosing the columns, then remember that you know this particular table will have no columns. So if you wish to add columns, you can just add column over here. For example, let's say I wish to add column, right? So I'll go to plus button over here, choose the name, let's say you know teacher ID, let's say data type to be int, right? And then you know not null primary key and all, I'll come later on this session, right? So I'll click on Save over here. So once I click on Save, you'll see that you know automatically a teachers table will be created with a single column that is teacher ID, right? So guys, that's how basically you can create tables in the SQL shell and PGAdmin.

Now before I move forward and show you the various other commands related to DDL, let me cover a concept known as entity relationship diagram. Now this particular concept is important over here because you know you have to understand how to create tables and how you have to relate those tables to the other tables, and basically what will be the column values for this particular table. So as you can see on my screen, guys, this is the example for entity relationship diagram that I'm going to consider for this particular session. Now based on this particular diagram only I'm going to basically take forward my session to show you the different commands also. Now entity relationship diagram basically is a simple diagram through which you can understand the various relationships between two different tables or two or more tables, right? For example, let's say you know we have this particular entity relationship diagram, right? Now over here we have employee, department, project, and dependent over here. Now all the rectangular boxes on this particular screen will represent entities. Now what I mean by entities is basically that you know, for example, let's say I'm a person, right? Now I have a name. Now my name, my age, my phone number, my date of birth, my address, all these are basically my attributes, right? And I as a person can be uniquely identified with the help of these particular attributes, right? So whatever can be uniquely identified with the help of attributes is basically entity, right? So I am an entity. So for example, I am Sahity, right? So my name, my age, my date of birth, all of this will be attributes through which anybody can identify me as Sahity, right? So over here any employee can be uniquely identified with the help of an SSN, that is basically a social security number, or you can simply understand as his ID name. Now name further can have the first name, the last name, and the middle name. Now address, salary, and sex, right? So basically all these attributes can uniquely identify an employee, right? So employee over here is an entity, and all these particular attributes are basically the factors to which you can identify. So when you build relational database management system, what happens is that employee will become the table name, and all these particular values, that is basically the attribute values, will be the column names, right? So you'll have a column name with SSN, birth date, first name, middle name, last name, address, salary, and sex, right? So all this basically will be your column names, and then employee will be your table name. Now similar is the case with the other factors also. For example, if you take department, now a department can be uniquely identified with number and name, right? So these two will be attributes, and the locations is basically a multi-valued attribute. Now when I say multi-valued attribute, what I mean by that is an attribute can have various factors, right? For example, let's say location. What will be your address? You can have so much of streets. Let's say you know fifth street, fourth crossroad, and let's say Queens Road, right? So this could be basically your location, right? Now this has various attributes like you know maybe you can have fifth streets, like the streets can be put into one value, and maybe the Queens Road, basically the main locality can be another value, right? So basically it's a multi-valued attribute, that's what basically double ellipses mean. Apart from that also, please remember that even this particular attribute will be included into the columns part, so you'll have a department table with the department number and department name as columns. Now apart from that, next let's look into project. The project is again another entity, right? So every project can be again uniquely be identified with project number and the project name and the location, right? Now over here the project number and the project name will be unique for each and every project, so that is the reason for every entity, for this particular entity, these two attributes are very important over here because every project can be uniquely identified with a project number and the project name. And finally coming to dependent. Now you must be wondering over here why does the dependent entity have two rectangles, right? That is because you know it is a weak entity. What I mean by weak entity is basically that you know the dependent entity is basically dependent on the employee entity, right? For example, let's say you know I as an employee, right? So I am an employee, and then maybe I'm going for an insurance, right? And then I have a health insurance, who in my next nominee let's say is my sister. So what happens over here is basically that you know this particular entity is dependent on the employee entity. My details will be basically taken from the employee entity, right? So for example, let's say I am an employee, then all my details will be taken from the employee entity, right? So that is the reason basically the dependent entity is completely dependent on the employed entity. So so that's what you have to understand over here. When I say weak entity, you have to understand that entity is dependent on any other particular entity, right? Now over here I hope you understood what is entities and what is attributes. Next, if you look into the diagram, we have various other factors like you know these diamonds and then we have double lines, we have single lines and so on, right? So let's look into what they are. So coming to diamonds over here, when I say diamond, what I mean by that is that is basically the relationship set. So what is relationship set? So if you have to understand

This then you can understand that you know employees are related to every Department. Right? So if you take your company, any number of employees—like you know, more than one instance of the entity—is basically associated with one instance of the department. Right? So in simple terms, if you just have to understand it like, let's say you know 10 employees are working in one particular Department, let's say IT Department, so that's how basically you can understand this.

Now coming to the next relationship that is manages. Now there's a relationship between employees and Department also, right? So there is a department, and then there is a manager for each and every Department. Right? So now not all employees are managers for the Departments. Right? So it could happen that you know only one instance of the employee entity is basically associated with one instance of the department entity. Right? So let's say you know we have the IT department. Now the IT Department can basically have only one manager; the HR department can have only one manager, and so on. Right? So basically all of them are also employees. Right? So that is the reason there is a relationship between employees and Department over here.

Now coming to the next relationship that is works on. Now it is obvious that the fact that you know all the employees must be working on some of the other projects. Right? For example, let's say you know we can have 10 employees working on two projects, or maybe you know the same number of employees working on some other projects also. Right? It's never that, in Industry, that a single employee is working only on a single project and not more than one project. Right? So in this particular relationship, that is the reason we have M to N. Basically, by that what I mean is that you know more than one instance of the entity employee is basically associated with more than one instance of the other entity, that is the Projects entity. Right? So that is because any number of employees can work on any number of projects.

Similarly, let's look into the next relationship that is dependents. Of what I see in the relationship of dependents of is basically one is to N, that is because you know one employee can have any number of insurance. Right? So you can have a life insurance and so on. So that is the reason basically you have a one-is-to-N relationship, and then you have the relationship of dependents of, because your dependents entity is completely dependent on the employee entity.

Finally, coming to self-referencing relationship over here. What I mean by self-referencing relationship is basically that you know, for example, let's say you have a boss. Right? Now your boss can handle 10 people. Right? So basically he's your supervisor, and then he supervises 10 people. Right? And he himself is also an employee, and all the 10 people are also employees. Right? So that is where this particular relationship comes into picture, that is one is to N. Right? So one instance of the employee where employee is basically a supervisor can supervise more than one instance of the other employees. Right? So basically that's how it happens. You basically have different relationships like this, guys.

If I have to just summarize the different relationships, then you have one is to one, one is to N, N is to one, M is to N. Right? And then you also have self-referencing relationships. So if you have to talk in technical terms, then you have one-to-one relationship, one-to-many relationship, many-to-one relationship, and many-to-many relationship. Apart from that, we also have the self-referencing relationship that I just spoke about.

Now if you observe the complete entity relationship diagram over here, so I hope you've understood how entities, attributes, and relationships work in the databases. Right? Now let's look into the double lines over here. What do you think the double lines mean? What I mean by total participation is basically that you know each entity in the entity set must at least have one relationship in the relationship set. So basically each entity in the employee must work in some or the other department. Right? So that is the reason we basically have total participation over here.

Moving on to the next relationship, you can see that you know it's not necessary that every employee manages some or the other person. Right? So that is the reason we don't have total participation on this particular side, but yes, every department has a boss. Right? So every department has a manager, so that's the reason we have total participation on this particular side, that is from managers to Department.

Moving on to the next relationship that is basically employees to project. If you see, every employee has to work on some of the other project. Right? So that is the reason we have total participation on both the sides, that you know every employee basically will be working on something or the other thing, and every project will have a set of employees working on it. Right? So that is the reason we have total participation over here.

Coming to the next relationship, you can clearly see that you know that the dependents are basically completely dependent on employees, so it's total participation towards from the dependent side and not from the employee side, because you know it can happen that you know maybe an employee doesn't have some insurance, or maybe an employee doesn't have any insurance. Right? So in that scenario, what basically happens is that you don't have total participation over here, but you have total participation on this particular side.

And now finally coming to this particular relationship. If you observe over here, we do not have any total participation, that's because you know it's not necessary that every person in the employee table—basically every person in the company—should be a supervisor of somebody. Right? It's not necessary like that; maybe a fresher is just not a supervisor. So in that scenario, basically total participation will not hold true.

So that is basically, guys, how you can build up an entity relationship diagram for that scenario that you have. I took a company database where you know you have various entities like employees, Department, dependent, projects, and then they are related to each other in some way or the other, and each of these entities have various attributes. So remember the fact that you know when you build a relational database, you have entities which will basically become your tables, then you have attributes, so your attributes will basically become your column names, and then you have relationships.

So guys, this was all about entity relationship diagrams. You basically have entities, attributes, and the relationships. Right? So I hope you've understood how my ER diagram looks like. Now as I was talking about different kinds of attributes, let me next take you through what are the different kinds of attributes that you see. So you must have observed, right? We had multi-value attributes, we had derived attributes, and then we have complex attributes and composite attributes. So we basically there are various attributes like you know Composites, simple, single, multi-valued, stored, derived, and complex attributes. So let's look into each one of them one by one.

So talking about composite and simple attributes, guys, if you remember the entity relationship diagram I showed you, I told you that the name can have first name, last name, and middle name. The first name, last name, middle name will basically be my simple attributes, and the name all together will be my complex attribute. So basically, if I have to define in single terms, then a composite attribute can be divided into smaller subparts, and these subparts can represent individual basic attributes with their own meaning. For example, let's say we have address. Right? Now address can have street address, city, state, ZIP, and street address can be further divided into number, Street, and house number. Now city, state, ZIP, number, Street, and house number will basically be your simple attributes. So this was about composite and simple, guys.

Now let's move forward with the next type of attributes, that is single and multi-valued. Now attributes having a single value for a particular entity are known as single-valued attributes, and a multi-valued attribute may have lower and upward bounds to constrain the number of values allowed for each individual entity. So you can have a single attribute and a multi-attribute in an entity, and I forgot to tell you one thing over here: every entity is uniquely identified. Right? So as I told you, employee had SSN, that is the social security number. Now that is basically uniquely identified. Right? So that is the SSN. So over here, that will be basically a unique attribute through which the complete table will be identified.

Next, let's move forward with the next type of attribute, that is stored versus derived. So the attributes which are derived from the real entities are known as derived attributes, and the stored attributes are the attributes which are already stored in the database and from which the value of another attribute is derived. So basically, if you consider age, from age you can derive birth date. Right? And from birthday you can derive age. Right? So I'm not saying in the matter of exact birthday, you can like, let's say you're 23 years, so you can derive the fact you know the birthday could be either in 95, 96, and if you know the year born is 95, 96, then automatically you can derive an age that you know the age could be 23 years. Right? So that's how basically you can understand stored and derived attribute.

And finally coming to complex attributes, the attributes that can be represented by grouping composite attributes between you know brackets by separating the components with commas and by displaying multi-valued attributes with square brackets are known as complex attributes. Right? So basically an address can have phone number, and then the phone can have again like area code and phone numbers, and then moving forward we can have again address and maybe add the skin again can have street address, number, Street, flat number, state, ZIP code, and so on. So basically this is how you can define complex attributes, guys.

So guys, that was about entity relationship diagram. So I hope you have understood how entities work, how attributes work, how a table name can be found, and how columns are formed, and how each table can be related to the other table, because this concept is really important to understand so that you understand the further concepts like you know the keys in databases and the constraints used.

Now before I wrap up this entity relationship diagram, let me just shift back to my PG admin and show you the simple commands of DDL, like you know the create, truncate, alter, and so on. So for example, let's say you know you want to truncate the table. Right? So when I say truncate, what I mean by that is you basically delete all the data present in the table, but you do not delete the table itself. Now since we haven't added any data into the table, I'll just show you the syntax so that you can understand. So let's say you know you want to truncate table students. Right? So for that what you'll do is you'll type in `TRUNCATE TABLE` and then you'll mention `students`. Right? And then you'll execute. Right? Once you execute, you'll see the output that you know `TRUNCATE TABLE` the query has been written successfully. Now since we have no data is present, you cannot see any particular output, but if you had any data present in the table, you would see that you know all the data would be removed from the table.

Because let's say you know you want to rename the table, let's say you want to rename the table students to let's say `info_students`. Right? So to rename the students, you basically have to use two DDL statements, that is `ALTER TABLE` and `RENAME`. Right? So for that what you'll do is you'll type in `ALTER TABLE` and then you'll mention the original name that `students`, and then you wish to rename. Right? So you type in `RENAME TO` and then you'll mention the new name that is `info_students`. Right? And then you'll execute. Once you execute, you'll see that you know all the tables, the query has been returned successfully. So what I'll do is I'll just refresh this particular schema, and then you'll automatically see that you know we see an output of `info_students`. Right? So that means our table has been renamed.

Now, for example, let's say you know we want to add a new column. So for that again you'll use the `ALTER` statement. So I'll just type in `ALTER TABLE` and then I'll mention the table name that is `info_students`, and then what you'll do is you'll mention `ADD` and then you'll mention the column name that is, let's say you know `date_of_birth`, and then the data type of it, let's say `DATE`. Right? And then you'll end with semicolon, and then you'll execute. Once you execute, you'll see that you know the query has been returned successfully. So if I just refresh this part again and you'll see automatically that you know a new column has been added onto the table that is `date_of_birth`. So this was just for a single column, guys. Now you can add multiple columns also. So for example, let's say I want to add two more columns. Right? So what I'll do is I'll just remove this. Let's see. Now I want to add gender, so I'll just mention `sex CHARACTER` and again comma and add let's say `class`. Okay, `class` is a keyword, so I'll mention `standard` and then `INTEGER`. Right? And then I'll again execute. Once I execute, I'll again refresh, and when I refresh you'll see that you know automatically my `sex` and `standards`. So basically the `gender`, `date_of_birth`, and `standard` have been added as new columns. Right? So that's how basically you can add a single column or you can add multiple columns.

Now you can also alter the data type of the particular column. For example, I want the data type of the `standard` column to be changed to let's say `CHARACTER`. So for that what you'll do is you'll basically mention `ALTER TABLE info_students`, that is basically the table name, and then what you'll do is you'll mention `ALTER COLUMN` and then you'll mention the column name that is basically `standard`, and then you'll mention the keyword `TYPE` and let's say we mention `CHARACTER`, and then I'll execute, and now once I execute and then if I show you the properties of this particular column, you'll automatically see that you know the data type is `CHARACTER`. Right? So basically, guys, that's how you can also alter a particular table or maybe column, maybe if you want to rename it on.

Now let's say you know you want to drop this particular column. So for that what you do is you type in `ALTER TABLE`, mention the table name again, and then what you do is you mention the keyword `DROP COLUMN`, and then you mention the column name. Right? And then you just execute. Now once you execute and let's say if I refresh this, you'll clearly see an output that you know your `standard` column is gone. Right? So that's how basically you can drop a column. Now similarly, if you want to rename a column, it's really simple. You have to write a query like you know `ALTER TABLE`, the table name, and then you have to mention `RENAME COLUMN`, and then you mention the column name to the new column name. Right? For example, let's say I want to change the column name of `sex`. So what I'll mention is `ALTER TABLE info_students RENAME COLUMN sex TO gender`. So that's how you can basically rename a column also. Now simply, let's say you know if you want to drop a table. Now if you want to drop a table, I'll mention `DROP TABLE` and then I'll mention the table name. Right? So I'll just click on execute, and then you'll see that you know automatically your table will be dropped. So if I just refresh this, you see that you know we just have one particular table that is `teachers`, and the `students` table is gone.

So guys, this is how basically you can work on PG admin for basically the DDL commands. Right? What I'm going to do is for this particular session, I'm going to consider the ER diagram as I mentioned before. Right? So I'm going to create tables and manipulate data over those particular tables only. So before I move forward with this session, what I'll do is I'll explain you the different keys and constraints used in the database so that it's more clear to you how you can create the database in a more structured manner, and then we'll move forward with the various manipulation commands. Until then, what I'll do is I'll just delete this particular table, so I'll right-click here, go to delete, and click on OK, and then let's say you know we will delete this particular schema also, so there's no confusion at all, and then what I'll do is I'll close this shell also.

So guys, remember that you know I am using PG admin; well you can use the same queries that I mentioned there on SQL shell also, and you'll see the same output. So I hope that's clear. So I'm going to close the SQL shell, and then I'll continue with this session. So now moving forward with this session, let's start with the next topic that is keys in database. So there are mainly five types of keys in database, that is the candidate key, the super key, the primary key, the alternate key, and the foreign key.

So talking about the candidate key, the candidate key is basically the minimal set of attributes which can uniquely identify a tuple. So any minimal set of attributes which can uniquely identify a tuple is known as a candidate key. So the value of the candidate key will be unique and non-null for every tuple. So if you have to identify a specific tuple, let's say Sahity is 24, let's say date of birth 30 October and so on so on so on, then you need a particular candidate key to uniquely identify my tuple. Right? So that particular can be my employee ID and so on. Now let me tell you one thing over here: there can be more than one candidate key in a relation also. So our candidate key can also be either a simple key or a composite key.

Now coming to super key. Now super key is basically again the set of attributes which can uniquely identify a tuple. So any set of attributes which can uniquely identify a tuple is known as a super key, but it's not the minimal set of attributes; the minimum set of attributes is the candidate key, but as any set of attributes which can uniquely identify is known as a super key. So when you add zero or more attributes to a candidate key, it becomes a super key, but the vice versa is not true. So a candidate key is definitely a super key, guys, but the super key is not a candidate key. So that's what you have to understand.

Now moving on to primary key. The primary key is also a set of attributes which can be used to uniquely identify every tuple. Now if you remember the entity relationship diagram that I was explaining you, I said the employee table has a special social security number through which every tuple will be identified. Right? So that particular social security number will be the primary key to which every tuple will be identified. And now apart from that, there can be more than one candidate key in a relation. Right? So out of all the candidate keys present in the relation, you can choose any one key as the primary key. So if you have around five candidate keys, out of them one can be definitely your primary key for that particular relation.

Moving on to the next type of key that is the alternate key. So the candidate keys other than primary keys are basically the alternate keys. So as I was giving you an example of five candidate keys, so if there are five candidate keys in a relation, then out of which if let's say you know the first key is chosen as the primary key, then the other four keys will be the alternate keys.

And finally moving on to the foreign key. So the foreign key is basically the key if an attribute can only take the values which are present as values of some other attribute. So basically whenever an attribute can only take the values which are present as values of some of the attributes, then it will basically be the foreign key to the attribute to which it refers. So basically the relation which is referenced is called reference relation, and the relation which refers to the reference relation is called the referencing relation. So the referenced attribute of the referencing attribute should be a primary key. Right? For example, let's say you know you have employee, department. Right? Now you want to reference department to employee. So what will happen is you'll basically use a foreign key to validate this relationship, and then you'll add a foreign key from department to employee. I hope that's clear.

So guys, these were the various keys that you need to understand about, that is the candidate key, super key, primary key, alternate key, and the foreign key. So now that you know the different keys in database and you know the DDL commands also, let me take you to the constraints in database so that we can quickly create the tables that we discussed in entity relationship diagram. Right? So the constraints in the database are as you can see on my screen, that is

Not null, unique, check, default, and index. So the not null constraint basically ensures that you know a null value cannot be stored in a column. For example, let's say you know you have a student's table. Now in the students table, you have a column known as student ID, and then when you're creating the table, you mentioned the not null constraint for this particular column. Then whenever you're inserting the data, you have to remember that you know there cannot be a null value in this particular column, that is the student ID.

Coming to unique, the unique constraint makes sure that you know all the values in the column are different. So in whichever columns that you want to store unique values, you have to use this constraint, unique.

Coming to check, this constraint ensures that all the values in a column satisfy a specific condition. So you have to check, let's say you know we want to store the age of employees. Now let's say age has to be greater than 25. So only the age values whose value will be greater than 25 will be stored in the age column if you mention this particular constraint.

Now moving on to the next constraint, that is the default constraint. This particular constraint consists of a set of default values for a column when no value is specified. So whenever, let's say you know you have not inserted any value specifically, then automatically a default value will be stored in that particular cell if you use this particular constraint.

And finally, coming to the index constraint, this constraint is used to create and retrieve data for the database very quickly. So if you want to create and retrieve data from the database very quickly, then you have to use this particular constraint, that is index. So guys, I hope the keys and constraints concept is clear to you guys.

So now that we have understood the entity relationship diagram, the constraints, and the keys, let me shift back to my PGAdmin. And now let's say I'll start creating tables. So I'll just show you for one table, and then I've already a set of commands that I've already executed. You know, I'm just going to copy-paste the command over here. So what I'm going to do is we have the employee table, right? So for that, what I'm going to do is I'm going to mention create schema first, so that you create a schema. So I'm just going to mention create schema. Let's say we mentioned the schema name to be company. After that, what I'm going to do is I'm going to use this particular schema, right? So I'll just mention set search path to company. Now automatically, if I just refresh over here, you'll see that you know there are two schemas, that is company and public.

Now what I'm going to do is I'm going to create tables inside this particular schema. So for that, what I'll do is I'll mention create table. Let's say we mention employee, and in brackets what I'll do is I'll mention all the column names. So we had first name, let's say we mentioned text not null. So I'm using a constraint known as not null, right? So this particular constraint is used, that means that you know it cannot be a null value in this particular column. Similarly, let's do for middle name. Let's say char null, right? So there can be null values over here. Now last name, let's say text not null, right? Now I have basically a social security number, right? So I'll put SSN, let's say character of let's say nine characters, let's be specific over here, and I'll put not null, so this cannot be null, and I also want it to be the primary key. So basically, through this particular number, the complete table will be uniquely identified. After that, I'll mention birth date, and then I'll mention the data type to be date. Right? Let's mention address, and let's say I mentioned the data type to be text not null. This also cannot be null, right? Similarly, I'll mention sex, let's say character null. Now similarly, I'll mention salary, let's say decimal, and then 10, 2, and this can be null. So we don't know, it can happen that you know we don't know the salaries, right? Then I'll mention superSSN. So this is basically to identify the self-referencing relationship, if you remember, right? And then I'll mention character of nine characters, and this can be null. And then let's say we mentioned department number. Let it be int and let's say not null because we don't want it to be null, right? Now what I'll do is I'll just execute this particular query. Now once I execute this particular query, you'll see that you know automatically we get an output that create table. So our table is successfully created. So if I refresh this particular schema and then if I open tables, you clearly see that you know we have the employee table.

Now similarly, what I'm going to do is for all these particular entities, I'm going to create tables, right? So I already have a doc present, so I'm just going to copy-paste from that. So let me just open that doc, right? So let me just copy-paste from here. So I'm going to copy for Department, Department_locations, Projects, Works_on, and Dependent. Now I'll go back to my PGAdmin, and then what I'll do is I'll just paste over here. So what I'm doing is, let me just explain to you. So I'm creating a table Department with the column names as Department_name, Department_number, Mgr_ssn. That's because for the relationship of manager, right? So if you remember, if I just open a diagram, you'll clearly see that you know employee manages Department, right? So you see for this particular relation, and then Mgr_start_date, that is because you know we have to consider the column present on the relationship also, that is manages. Similarly, I'm creating Department_locations, that is with Department_number, Department_location, and primary key as Department_number and location together. Then I'm creating a table known as Project. So the Project table will have Project_name, Project_number, Location, and then I've used the primary key to be Project_number, and then the Project_name has to be unique, right? So I've used the constraint over there. Similarly, I'm creating a table known as Works_on. So for the Works_on table, I have employeeSSN, the Project_number, the hrs_worked, and the primary key to be the employee number and the project number together. The Dependent table will again have the employeeSSN, the dependent_name, sex, birthday, relationship, and the primary key to be employeeSSN and dependent_name, right? So I'll just execute all these particular queries. So you can see that you know automatically my query has got successfully executed. So I'll just refresh this particular table again. So once I refresh this particular schema, you'll see that you know I have six tables, that is the Department, Dependent, Department_locations, Employee, Project, Works_on, right? So guys, that's how basically you can create tables, and that's how you can use keys and constraints while creating tables.

So guys, that was all about the data definition language commands. I hope you understood how you can use them and create databases. Now before I move on to the next topic, that is the data manipulation commands, let me take you through an interesting topic, that is normalization. So what is normalization? So normalization is a technique that organizes tables in such a way that you know the redundancy and the dependency of data is reduced. So obviously, when you're storing a humongous amount of data on an industry level, there could be scenarios where you have redundancy. So normalization is basically that technique through which you know you can remove the redundancy and dependency of the data. So as you can see on my screen, the normalization is basically at four levels, that is 1NF, 2NF, 3NF, and BCNF. So let's discuss the same now.

Now before I move forward with 1NF, let me tell you that you know I'm going to consider this particular example. So the example that you can see on my screen is basically of three people you know living in specific addresses, and they have rented a few movies of a specific category. Now you definitely see redundancy in this particular table, right? That's because you know you see Alice Johnson has rented two movies, that is Mission Impossible and Clash of Titans. Similarly, for David Allen, the address has been divided, and also the movies rented have also been divided into different categories, right? Like the Sci-Fi movies are put into one category, and the action movies are put into the next category, and both of them are in two different tuples. This is definitely redundant data, right? Now how do you think you can normalize the data? Well, we'll start with 1NF. Now the rule of 1NF is really simple, guys. What the rule says is that you know each table cell should have a single value. So basically, any table that you have, and then you wish to normalize the data from that particular table, you have to make sure that you know each table cell has a single value. So for example, we had Alice Johnson and David Allen, right? So if you remember from the previous slide, we had movies entered together, right? So for Alice Johnson, we had Mission Impossible and Clash of Titans in the same tuple, and for David Allen, we have the address divided, but also the movies are also divided. So what I've done over here is to get the data into 1NF. What I've done is I've divided all the movies rented into different tuples. So Alice Johnson staying in First Street, house number three, has basically, you know, specific movies rented, that is Mission Impossible and Clash of Titans. So what I've done is I've divided both these movies into two different tuples. The same goes for David Allen. If you remember from the previous slide, what happened is that you know in Third Street, 45, address 1, David Allen had Interstellar and Edge of Tomorrow together, right? So what I've done is I've divided those two into two different tuples again, and then added Seventh Avenue into the next tuple. So this is basically how I've got my table into 1NF. Each table cell basically has only one single value.

If you observe over here, there's still a problem, right? That's because you know our address is written for Alice Johnson and for David Allen. Our address is redundant, and yes, it is divided also, it's not all together. So for that, what we'll do is we'll convert this table into 2NF. So basically, to normalize such a database into 2NF, remember the fact that you know the database should be in 1NF and should also have a single column primary key. What I mean by that is you know what I'm going to do is I'm going to divide the table into two different tables such that you know for each specific user, I'm going to identify the specific movie rented. For example, let's say you know I give Alice Johnson staying in First Street, house number three, ID number one. Now I know she rented Mission Impossible and Clash of Titans, right? So what I did was I gave the movies Mission Impossible and Clash of Titans, which are rented by Alice Johnson, the ID 1. Similarly, what I did is for David Allen staying in Third Street 45, basically for that particular tuple, I've given the ID to be two. We know that you know he must have rented Interstellar and Edge of Tomorrow, right? So for those particular movies, I've given the ID to be two, and finally for Mission Impossible Fallout, that is basically rented by David Allen staying in Seventh Avenue, what I've given is I've given ID number three. So that's how basically I have divided the 1NF table into 2NF.

Now if you see over here, this is still a problem, right? Now that's because you know we still have redundant data with respect to Alice Johnson and David Allen, right? Because David Allen's name comes twice, as Johnson, who rents two movies, comes once, but yes, the address is also divided for David Allen. So to normalize this factor, what we'll do is we'll normalize again. So now we'll normalize the database which is in the form of 2NF to 3NF. Now if you want to normalize a database from 2NF to 3NF, the database should be in 2NF and must not have any transitive functional dependencies. So for that, what I'll do is I'll basically add a salutation ID. So basically, I'm going to identify Mr from one, Miss from two, Misses from three, and Doctor from four. So in that way, what will happen is that you know David Allen's name won't come twice because he'll be uniquely identified with mister. So we'll type in Mr. David Allen, so that will only come once, and then all the movies will come together. So that's how guys basically you can normalize your database. So we've normalized from 1NF to 2NF, 2NF to 3NF, and finally comes BCNF. Now since my example ends there, so I'm not going to normalize it further, but yes, if your database is not yet normalized, you can then go forward and normalize again, that is BCNF. So to perform the normalization for the fourth time, what you can do is you have to normalize, right? The condition to normalize it again is basically that you know your database must be in 3NF, and maybe you know even after being in 3NF, there would be some anomalies, and it may have more than one candidate. Now in such scenarios, what will happen is BCNF will come into the picture, and then it will divide the tables further so that there would be only one candidate key present. So whenever after 3NF you observe that you know there's more than one candidate key, and then you'll have to normalize it again, that's where BCNF comes into the picture to divide the table further. So guys, this was about normalization. I hope you have understood how you can normalize your databases.

Now let's move forward with the next topic for today's session, that is data manipulation commands. Now the data manipulation commands, as I said before, are basically the commands which are basically used to manipulate your databases. So what I'm going to do is I'm going to manipulate data present in the database that I've created over here, that is in the six tables that I've entered. So to initially manipulate data, you need data present in your table. So now to do that, what you have to do is you have to insert data. So to insert data, what you'll type in is insert into, and then let me show you for the employee table, employee, and then you'll mention values, and then you'll have to mention the values that you wish to enter, right? So let's say I wish to enter John as first name, and let's say I'll enter middle name, let it be a character. Now similarly, I'll enter the next name, let's say Smith, that is basically my last name, sorry, the comma has to go at the end. Now I'll enter SSN. Right after that, what I'll do is I'll enter birth date. So let's say I mentioned 1965-01-09. Then let's say I mentioned address. So let's say I mentioned 731 Houston TX, and let's say further I mentioned the gender to be male, and then let's say we mentioned salary to be 30000, and then we mentioned superSSN, let's say 33344445, and let's say we mentioned the department number to be five. Now once this is done, you can just execute this particular query. So what you can do is you can just hit on execute, and you'll see that you know automatically the query has been written successfully, that means the data is filled. So if you want to see the data output, what you can do is you can use the other manipulation command, that is basically select * from employee. So that will basically show you all the values present in the employee table. So let me just mention that, and then I'll hit on execute, and you'll see that you know automatically you see the data present in the table, that is whatever we have mentioned over here.

Now since guys, filling data would be a waste of time for me to explain for each and every value, I've already put it in my doc, so I'll just copy-paste from there so that we can move faster in the session, right? So let me just copy-paste these commands. So if you observe over here, what I'm doing is I am entering data into the Department table, the Dependent table, the Department_locations table, Project table, Works_on table, and so on. So I'm not entering just one, I'm entering quite an amount of details. So what I'll do is I'll just select all of them together, and then I'll hit on execute. Once I hit on execute, you'll see that you know the query has been written successfully, that means that you know automatically our data has been entered into our tables, right? So if you just want to check how if the data has been entered or not, you can similarly use the same command that I just showed you, that is select * from, and then you mention the table name.

Now let's move forward with the session. Now as you remember from the Entity relationship diagram, I said there were relations between two entities, right? So those relations are basically mapped into pictures with the help of foreign keys that I mentioned before, right? So to add foreign keys, what you'll do is you'll have to alter the table since the tables are already created. So what you can do is either you alter the table or the other way completely round is basically whenever you're creating the table, you can add foreign keys. So I'm just going to alter the table since you know my tables are already created. So for that, what I'll do is I'll put an alter table, and let's say you know I add a foreign key for the manager's relationship. So what will happen is I want to add a foreign key for the manager's relationship where you know I'll say the department is managed by an employee, right? So what will happen is Department will be our first table where we'll add a foreign key, basically Mgr_ssn, which references to the employee table because every employee manages a department. So that's what I'm going to do. So I'll mention alter table, and then let's say we mentioned Department, then I'll mention add foreign key, and then I'll mention the column attribute which has to match, right? So that is Mgr_ssn that I have created in the Department table, and then I'll mention references, oh, I'm sorry, there's a spelling mistake over here, right? And then I'll mention the table number two, that is employee (SSN). So basically, you have to add a foreign key to each of the columns, right? So you are basically trying to connect the Mgr_ssn column of a Department table to the SSN column of the Employee table. You'll just execute this, and then once you execute this, you'll see that you know the query written successfully, that means there is a foreign key, right? So for example, let's say if I just refresh this, and then we go to the employee table, and then if we see the properties, and let's say you know we go to constraints over here, and in the primary key, we see that you know it's SSN, and in the foreign key, so there's nothing over here. So I had to go to the Department table. So let's go to properties because you know we are adding the foreign key from there, right? So I go to foreign key, you see that you know Mgr_ssn foreign key, basically Mgr_ssn is connected to SSN. So you clearly see that you know that's how you can add a foreign key. Now what I'm going to do is I'm going to add foreign keys for other tables also so that you know we can move forward. Again, let me just directly add it from here, right? So as you can see on my screen, I've mentioned a foreign key between employeeSSN and employee superSSN. So that was basically for our self-referencing relationship. Then I mentioned a foreign key between department number and the department, basically who works on which department, right? So for that particular relationship, after that, I've mentioned a foreign key for Department_locations and the department, so basically which department is present in which location. After that, I've mentioned the foreign key between Project and Department, basically which department is looking into which project, and then I've mentioned a foreign key between the Works_on table and the Employee table to understand which employee is working on which project or which department, and finally on the Dependent and the Employee table to make sure the dependency relationship is taken into account, right? So what I'll do is I'll just execute all these particular foreign keys. So I'll hit on execute. You'll see that you know automatically the query has been executed, right? So guys, that's how basically you can add foreign keys to all your tables. You know, if you just refresh over here, and then if you check all the tables, you'll see that you know there are some other foreign keys present for each and every table, that is for each and every relation.

Now let's move forward. Now for example, let's say you know I want to see all the details from the Works_on table, right? Now let's say you know I

Want to delete records with the project number, let's say 30. Let's try deleting. Right, so if I try deleting, let me just write it over here: DELETE FROM. You have to delete from the project table, and then I'm saying the project number I've considered 30, right? So I'll just type in 30, and let's see what happens when we execute this. Okay, I'm sorry. Yes. Now, when you execute this particular statement, what do you say? You see an error that you know, UPDATE or DELETE on table project while it's foreign key constraint. Because we have a foreign key with respect to WORKS_ON, sound right? So because we've just mentioned over here that you know we'll have a foreign key with WORKS_ON and project number, so now that's the reason we get this error.

Now, to resolve this error, basically I'm talking about the concept where you want to delete the records where foreign keys are present, right? So what you'll do is you'll initially delete the record from the WORKS_ON table, and then you'll go forward and delete the records from the project table. So you directly won't come over here; what you'll do is you'll initially DELETE FROM WORKS_ON table. So let's say P_NUMBER is 30, right? So I'll delete the record from the WORKS_ON table over here. You'll automatically see that you know query returns successfully. And now if we try deleting data from the Project table, what you'll clearly see is that you know query is written successfully; that means there was no violating error, right? So what happens is whenever you have a foreign key from a table to B table, remember that you know if you want to delete anything from the B table, you have to first delete it from the A table, and then you can go forward and delete it from the B table, right?

So guys, that was about the INSERT statement, the ALTER statement, and about foreign keys. Now, in this session, what I'm going to do is I'm not going to talk about any theory part like what's gonna happen and then how you can use. What I'm going to do is I'm going to directly jump on the query so that you can understand how you can write queries and how you can manipulate data. So let's get started. So now let's say you know we want to update the salary of employees. For example, let's say I'll just see which employee salary has to be updated. So I'll just type on SELECT * FROM employee so that I can see the details. So I'll just execute this. So when I execute this, you'll see that you know I have all the details. Right now, let's say you know I want to update the salary of a person, let's say employee whose SSN is, let's say 39847. Now let's say the salary is around 25,000. Right now, I want to update it to 27,000. What can I do is basically I have to use the UPDATE statement. So to use the UPDATE statement, what I can simply do is let me just press on ENTER so that the screen is clear for you guys. I could just type in UPDATE, and then you have to mention the table name, so that will be employee, and then you'll mention SET column name, and then what you'll do is you'll mention the new value that you want, that is, let's say 27,000, and then let's say WHERE SSN, that is basically through which you can uniquely identify every tuple, right? So WHERE SSN is equal to what was the SSN? It was 39847, right? So I'll just type in 39847, and then what I'll do is I'll just end with a semicolon. Once I execute this, you see an output that you know query returns successfully, right? So now let me just go back over here and choose SELECT * FROM employee, and now if we go back to this particular table, you can clearly see that you know the employee who had an SSN of 39847 has now a salary of 27,000. So guys, that's how you can update the values.

So guys, that was about the UPDATE statement. Now let's say you want to delete a tuple's data, you know, let's say more than one condition. So what you can do is you can just use the DELETE statement. Okay, DELETE FROM, and then let's say we want to delete it from the WORKS_ON table, right? So I'll just type in WORKS_ON, and then let's say WHERE employee_SSN, because our WORKS_ON table has employee_SSNs column, right? So over here if you can see, we have ESSN, and let's say you know we use the same employees, and let's say 39847, and we also have project number details, right? So here I'll choose project number, let's say, right? So that is basically the data I had mentioned. So I'll just execute this particular query, and you see that it automatically is executed, right? So now if I just change this from employee to WORKS_ON, and then if I execute this particular query, you can clearly see that you know we have no employee with employee ID of 39847 and working on Project number 10's data present in the WORKS_ON table.

So guys, that was about how you can DELETE, UPDATE, INSERT, and ALTER. Now let's move forward with one of the most important queries, that is the SELECT query. Now the SELECT query is basically considered as one of the most important queries because you know this is the query through which you can retrieve the data. So as you can see over here, I was using the SELECT query again and again because you know I wanted to retrieve the data that I have in my database. So that's where basically the SELECT query comes into picture. Now when I had SELECT * FROM WORKS_ON, that means all the data was shown. For example, let's say I just want the first name, last name, and the address from the employee table, and let's say you know we are specific to department number 5. So what I can do is I can just type in SELECT first_name, last_name, address, and I'll mention FROM employee, and let's say we mention department_number is equal to 5. So I'll execute this particular query. So when I execute this particular query, you can see that you know John, Franklin, Ramation, Joyce, so basically the first name, last name, and address have come into picture, right? So uh, that's how guys you can use a SELECT query. Now this was quite a simple one, right? Now let's look into something more complicated. For example, let's say you know you want to retrieve data for every project located in Bellary, and then you want the project number, the controlling department number, and the department manager's last name, address, and birthday. So over here if you observe what all I have taken into account: the project number, the department number, the department manager's last name, address, and birth date. So if you observe over here, basically what's happening is there are three tables coming into picture, right? That's basically the project table, the department table, and the employee table. So let's look into how we can write the query for this. So what all did I mention? I mentioned the project number, the department number, last name, address, and birth date. So what I'll do is I'll mention SELECT, and then I'll mention all these factors, that is pno, the dnum, right, and then I'll mention lname, that is basically my last name, and then I'll mention address, say we mentioned birthdate, right? And then I mentioned FROM, uh, what are the tables that I had considered? That is the project, department, and the employee, right? So I'll mention project, department, employee WHERE dnum is equal to dno. So basically the department number from the project table has to match the department number from the Department table also. So that's basically you use an operator known as AND, and then you mention mgr_ssn, that is basically who manages the project has to match with the employee code, that is, right, SSN. Apart from that, we also have to mention that you know our project location is, so we'll mention AND p_location is equal to, in quotes we'll mention Bellary, right? So if I just execute this particular query, you'll see an output that you know there are no tuples which satisfy this particular condition, right? So what I'm going to do is let's say we change Bellary to let's say Houston, right? Now let's execute again. Now if I execute on Houston, you can see that you know we've got the project number, the dnum, the last name, the address, and the birth date of basically all those employees who work on the project basically located in Houston. So that's how guys you can basically integrate two to three tables together and use the SELECT statement to further play around with it.

Now if you remember, I was talking about the self-referencing relationship where you know we have employee related to himself, right? That was basically how a supervisor can have a supervisor. For example, let's say you know for each employee we want to retrieve the first name and the last name, and also the first name and the last name of the supervisor. Then what we can do is we can use the SELECT statement again, right? And then I'll mention e.fname and e.lname. So this is basically to identify every employee, right? So that is basically the supervisee. Now if you want to identify the supervisor, what I'm going to do is I'll mention s.fname and s.lname, and then I'll mention FROM, and then I'll mention employee, sorry, let me put it in small so that it's clear to you, FROM employee AS e, right? So for every employee, that is basically for every supervisee, I'm identifying employee AS e, and similarly for supervisor I'm going to identify AS s, right? So I'll mention employee AS s WHERE e.super_ssn is equal to s.ssn. Now if I just execute this particular query, you see an output that you know we have the first name and the last names of the supervisees and the supervisors. So that's how basically you can play around with the names of the columns and the tables also, guys. So I hope you've understood this particular query.

Now moving forward, you might have heard about the term DISTINCT. So when I say DISTINCT, what I mean is I want to find out all the unique values, right? So to find out unique values, you have to use the term DISTINCT. Let's say we want to find out the distinct salary values for all the employees, right? So now what I can do is I can just mention SELECT DISTINCT, and then I choose the column salary FROM the employee table, and then I click on execute. So you'll automatically see that you know we see all the distinctive salary values present. So whenever you want to find out any unique values, or let's say distinct values, this is basically the keyword that you have to use, that is DISTINCT. So guys, that was about the DISTINCT query. Now let's move forward and understand the cross product. Now cross product is something like you know when you have A x B, right? So basically you have A, and then you want to find out all the combinations of A with B. That's when you use cross product. For example, let's say you know you want to find out all the SSNs, basically of all the employees, and then you want to find out all the combinations of employee SSNs with the Department name. So let's do that. So what we can simply do is to perform cross product, you can mention SELECT SSN, dname FROM, when mentioned employee, department. So if I just execute this particular query, you'll see that you know we get all the combinations of SSNs with Department name. So let me just drag a little bit, right? So as you can see, we have for each SSN we have various departments, like you can see we have the Research Department, the Admin Department, the Headquarters Department, and so on. So that's how basically you can perform cross product. Now let's say you know if you want to take this query further. So let's say you know we want to find out all the employees who work in the department, let's say Administration. So what we can simply do is we'll type in SELECT *, and then I'll mention FROM employee, department, and then I'll mention WHERE condition which says dname is equal to 'Administration' AND dept_no is equal to dno FROM the Department table. So if you have any queries with how am I mentioning the column names, you can always refer to the tables that you have, and then you can go back to the tables and check for the column names. For example, let's say I go to the department, then you can see that you know I have the department number over here. So I'll just execute this particular query now, and once I execute this particular query, you see that you know we get all the details of all the employees who work in the department Administration, right? So if I just extend this, you clearly see the output, right? So guys, that's how basically you can play around with the SELECT statements.

Now before I move forward with the further Data Manipulation Language commands, let's look into the next topic, that is operators. Now there are various kinds of operators present in the SQL commands: that is arithmetic operators, the bitwise operators, the comparison operators, and the compound operators. So the arithmetic operators are basically used to perform the arithmetic operations, as you can see on my screen: +, -, *, /, and MOD. Bitwise has bitwise AND, OR. Comparison has >, <, >=, <=, =, and !=, and so on. And the compound operators have you know increment, like you know a = a + 1 can be written as a += 1. So that's how basically you can use operators, guys. Well, I'm not going to explore more about operators because that's a really simple topic that you can explore about, right? So I've just given you a basic understanding of the top operators. Well, don't worry, we'll be looking forward into these particular operators later on in the session. So let's get started with our next topic for today's session, that is nested queries. So nested queries are SQL queries which have an outer query and an inner query. So the subquery is a query nested within another query, such as SELECT, INSERT, UPDATE, or DELETE. For example, if you see the screen, that is basically the outer query and the inner query. So I have an outer query which says SELECT last_name, first_name FROM employees, let's say you know WHERE address IN, and then we choose you know we mentioned an inner query which says SELECT address_code FROM Office WHERE country = 'India', right? So based, so if the condition matches, then automatically this query will be executed, and then we'll get the output. So this was about nested queries, guys. So now what I'll do is I'll now explain you a little bit more concepts, and then I shift back to my PGAdmin to show you how you can write nested queries and implement various other queries. So on that note, next let's look into what are set operations. Now all of you might be knowing what are set operations, right? It's basically UNION, INTERSECT, and MINUS. For example, let's say you know you have set A and set B. Now if you perform the UNION operation between set A and set B, what you'll get is you'll basically get all the data present in both set A and set B. Coming to the INTERSECT option, basically if you have set A and set B, and then if you perform the INTERSECT operation between both these sets, what you'll get is only those rows which are common in both the queries. And finally coming to MINUS, that is you can basically mention MINUS or EXCEPT, right? For example, let's say you have set A and set B, and then you mention set A MINUS set B, you basically keep all the rows from the left query which are not included in the right query. Now the vice versa is also true. For example, if you do set B MINUS set A, then you keep all the queries from the right query which are not included in the left query. So that's how basically you can perform set operations, guys. So in the matter of Database Management Systems, if you have to understand, then you can understand set A and set B as left query and right query. So as you can see from the pictorial representation over here, if you do UNION, then you get all the rows from both the queries. If you do INTERSECT, then you get only those rows which are common in both the queries. And then if you perform the MINUS operation or the EXCEPT operation, you get only the rows from the left query which are not included in the right query, or maybe only those rows which are included in the right query but maybe not included in the left query, right? So guys, that was about set operations. So now let's move forward and let's look into special operators. So when I say special operators, there's nothing much big deal about it; they're just few operators which are special, like you know BETWEEN, IS NULL, IN, EXISTS, ALL, ANY. So these are various operators. This is not something that you need to learn in depth, but as you write queries you should have an idea about all these operators. So when you say BETWEEN operator, what I mean by BETWEEN operator is basically that we want to mention a condition between A and B. So whatever values which satisfy the condition between A and B, all those values, rows will be printed. Similarly, IS NULL, so the IS NULL operator is basically used to test for the NULL values. Now since you know it is not possible to test the NULL values with comparison operators like greater than or less than, we can simply use IS NULL and IS NOT NULL operators instead. So what you can simply do is you can just find out where if address IS NULL or maybe if the date of birth IS NULL and so on. Coming to LIKE operator, the LIKE operator is basically used to get the data of all those values which either start with a character, specific character that you mentioned, or maybe end with a specific character that you mentioned, or it could also happen that you know you have few spaces and then you mention a specific character, you also want all those rows. Coming to IN operator, this is basically a shorthand operator for multiple OR conditions which allows you to specify multiple values in WHERE Clause. So this is basically used when you want to use nested queries, right? Coming to EXISTS operator, EXISTS operator is basically used to test if a record exists or not. If it exists, it's fine; if it doesn't exist, then it returns an output that you know the query not found. And finally coming to the ALL operator, the ALL operator is used with a WHERE or a HAVING clause, and it returns TRUE if all the subquery values meet the condition. So this was about ALL operator. Coming to ANY operator, the ANY operator is also used with the WHERE and the HAVING clauses, and returns TRUE if any of the subquery values meet the condition. Apart from that, over here I also want to tell you about the ORDER BY, GROUP BY, and HAVING clauses. So the ORDER BY is basically to order the data that you want in a specific format, let's say you know ascending order, descending order, and so on. The GROUP BY is basically you want to group the data according to some specific column and so on, right? And HAVING is basically where you're checking, let's say you know HAVING salary > 25000. So only those tuples will be written whose salary is greater than 25,000. So guys, that was about GROUP BY, ORDER BY, and HAVING clauses also. Now let's move forward with the next one, that is aggregate functions. So aggregate functions is also one of the most simple topics. So aggregate functions is mainly used with the nested queries, that is basically the MIN, MAX, COUNT, AVG, and SUM. So the MIN function is basically used to return the smallest value of the selected column in a table. The MAX function is basically used to return the largest value of the selected column in a table. The COUNT function is basically used to count the number of rows that match a specified criteria. The AVG function returns the average value of a numeric column that you choose, and the SUM function returns the total sum of a numeric column that you choose. Now that was about aggregate functions, guys. So don't worry, I'm just brushing you with the topics, basically the concepts. I'm going to show you how you can use all these concepts based on the queries that I'll execute on the PGAdmin in a while now, but before that let me just take you through the LIMIT, OFFSET, and FETCH values. The LIMIT is basically used to

Limit the number of data that you want to get. Now we want only the data of the first five rows. So what we'll do is we'll basically mention, "Select Staff from employee limit five." What will happen is automatically we'll see the first five rows.

Coming to offset, offset is used to basically select a specific number of rows after the limit. Right? For example, let's say after the fifth row we want three rows. Right? So what we'll do is we'll use the offset statement to basically mention that, you know, after the fifth row we want three rows. Right? So basically, only after the fifth tuple is read, automatically six, seven, eight will be printed out as an output.

Coming to fetch, fetch is also one of the ways to limiting the query results. Right? So whenever you want to fetch, let's say first five rows only, or maybe let's say 10 rows only, then you can use the fetch statement. So I'm going to show you how that's done. Let me just shift back to my PG admin. And now what I'll do is I'll start with the first topic that I had discussed over here, that is nested queries. So let's write some interesting nested queries so that you get a hands-on experience and how you can integrate into a complex queries. Right?

For example, let's say, you know, we want to make a list of all the project numbers for projects that involve an employee whose last name is Smith, either as a worker or as a manager of the department that controls the project. So our main question is basically to list the project numbers for projects that involve the employee Smith. Now that particular employee can either be the manager or can also be the worker of that particular department and controls the project. So to do that, what I'll do is I'll have to write a nested query. The reason for nested query is simple, that is because, you know, we have to first find out all the projects where, you know, Smith is working as an employee. Later on we'll find out the projects where Smith is working as a manager. Right?

So let's start with Smith working as a manager. So for that what we'll do is we'll type in select distinct, because we want unique records, and let's say p number, that is basically the project number from project, and then we also want the department because we're going to use a department table, and then we mention employee because we're going to use the last name where we'll mention the dnum is equal to the dnum and MGRSSN is equal to SSN, also my last name should be Smith. Right? So I'll mention Lname is equal to. Right? So let me just remove this, put in a where, and let me put a bracket. Now let me tell you one thing over here: this is not the end to the query because we also want to find out all the project numbers where employee Smith is working as a worker. Right? So for that what we'll do is we'll use the set operation Union. Right? Because this makes sense. Right? We want all the values from set A and then we also want all the values from set B. So that is the reason we'll use the union operation. And then we'll mention select distinct pnum from Project, works on, employee where pnum is equal to pnum, that is basically the project number from the project table and the works on table, and employsSN from the works on table to SSN from the employee table. Apart from that we also have to mention that last name should be Smith. Right? So we'll mention and Lname is equal to Smith. Right? So I'll end it with a semicolon, and let me just remove this type over here, and then let's execute this particular query. All right, it says Department—oh yes, there's a spelling mistake over here. Right? And now let's execute again. So once I execute, you see that, you know, I get the project number one, two. That means that, you know, the person with the last name Smith works as a manager or maybe works as a worker in these two projects, that is Project number one and two. So guys, this was a nested query with the Union operation.

Now let's say, you know, you don't want to use any set operations, and let's say you just want to write a simple query. Let's take an example for that. Now let's say, you know, we want to retrieve the name of employees who have no dependents. Right? So we had a relationship that says employees have dependents. Right? So let's say, you know, we want the name of employees who have no dependents. So for that what you can do is you can just type in the query select firstname, let's say we take firstname and let's say we take lastname from employee where—we'll mention not—I'm sorry, I have to correct the spelling of where—we are—we'll mention not exists, and then I'll again mention a subquery which says select * from dependent where we have to match the SSN. Right? So SSN is equal to essn. Right? So I'll just execute this particular query, and then once we execute this particular query, you'll see an output of all those employees who have no dependents. So that's how, guys, basically you can use this operator of not exists. What I've done is I've basically taken the operator of exists. So if it exists, what will happen is that initially the subquery will be executed with say select * from dependent where SSN is equal to essn. So this query will generate all those results which have the dependents. Right? So basically all those employees who have dependents, that particular result will be generated over here. Then I put a not condition before that. So when I put a not condition, the output gets reversed, and automatically I got that output printed. So if you just mention exists over here, and then if you remove not, and then again if you just execute this particular statement, you'll see a different output. So this is basically the output of all the employees who have dependents.

So now let's take this query further, and let's say we want to find out the names of those managers who have at least one dependent. So what I'll mention over here is I'll mention select firstname, lastname from employee where exists, and then I'll change this condition, select * from dependent where SSN is equal to essn, and also I have to take this condition further which says and exists, and then I again have a nested subquery which says select * from Department because we are considering manager. Right? Where SSN is equal to MGRSSN. So I'll just close this bracket over here, and then I'll remove one bracket at the end, and let me put an enter so that's clear to you. So what I'm basically doing is I'm basically listing the name of managers who have at least one dependent. So for that what I've done is I've used an outer query which has a subquery, and underneath that I again have another subquery. So for that what I'm using is select firstname, lastname from employee where exists, and then again I have a subquery which says select * from dependent where, you know, SSN is equal to essn. This will basically give the output of all the employees who have dependents. Now after that we also have to match from select * from department where SSN is equal to MGRSSN, which is basically the name of managers that we want. After that we're taking dependents into account, and then we are returning the firstname and the lastname. So if you see the output, we get Franklin and Jennifer. Right? So Franklin and Jennifer are those managers who at least have one dependent. So guys, that was about exists and not exists, how you can use and all. Let's move a little bit further, and as I was talking about operators like the special operators, let's look into few queries related to that. So let me just press one enter over here so that I can make the screen clear for you.

Now let's say over here we want to retrieve all the employees whose addresses are in Houston, Texas. It's really simple. What I can do is I can just generate select SSN and firstname from employee where address like, and then in quotes I'll mention %Houston%, and then what I'll do is I'll end with a semicolon over here. So basically I'm generating the SSN and the firstname of all the employees whose address is in Houston, Texas. Right? So let me just execute that. So once I execute, you see an error that, you know, where address—okay, so that is basically because our spelling is incorrect over here. So let me just execute again. So once I execute, you see SSN and firstname of all those employees whose address is in Houston, Texas. Right? So if you want to check this information, you can go back to our employee table, and then you can check the information for sure. So that's basically how you can use the like operator.

Now let's say, you know, we want to find out all those employees whose firstname has, let's say, five characters. So if you want to mention five characters, how will you do that? Any five characters, not necessarily that, you know, it has to start with f or s or a or any other character; it can be any character that you wish to. Right? So in that scenario, let's just generate select firstname and let's say I again generate SSN from employee where firstname like—okay, there's a typo over here—and then I'll mention _ _ _ _ _, five characters. Right? And then I'll end with a semicolon. So let's just execute this particular query, and you'll see that, you know, it's just Joyce, Ahmed, and James who have firstname with five characters. So all the other employees who have firstname with any other number of characters are not taken into account. So that's how basically you can use the like operator, guys.

Now let's say, you know, you want to use the between operator. For example, let's say that we want to find out all those employees whose salary lies between, let's say, 30,000 to 45,000. So for that I'll type in the statement select * from employee where, and then you mention the nested query salary between, and then you mentioned 30,000, right, and 40,000, right. And so let me just execute this particular query. All right, once I execute this particular query, you get the information of all those employees whose salary lies between 30,000 to 40,000. So guys, that's how you can use the between operator.

Now as I'm talking about operators, let me just show you a simple functionality of the arithmetic operator also. Let's say, you know, we want to show the resulting salaries of each and every employee working on the product Y project, and let's say, you know, it's given a 20% raise. So to do that what you can do is you can write a query, let's say select e.fname, so if you remember I used a similar query previously also, and then I choose e.lname, and then I mention 1.2 * that is basically my arithmetic operator that I'm using, and I'm choosing e.salary as increased salary from—I am choosing employee table because salary is an employee table, and then since I'm using e.fname, I'll mention employee as e, and then works on w, and project as p, and further what I'll do is I'll mention where employee.ssn is equal to—is equal to—the workson.ssn. Right? So whatever employee is working on product Y. Right? So that's what we want to find out over here. So he has to first satisfy the condition of the ssns have to match. Apart from that we'll consider and—all right, this has to be essn. Right? And then I'll mention work.pnum is equal to p.pnum and p.pname is equal to 'product Y'. So let me just end this particular query over here, and now execute it. Once I execute, you see that, you know, we get the firstname and the lastname and the increased salaries of all those employees who have worked on product Y, and their salary is increased by 20%. So that's how, guys, basically you can use the as operator and also arithmetic operators together.

Now as I was talking about one more operator, that is is null, so if I have to talk about is null, let's say, you know, we want to find out all those employees who do not have any supervisor, so then directly you will use is null operator. So in that scenario what you'll basically do is you'll write a query like, you know, select let's say * from employee where superssn is null. I am basically using this is null operator to find out all those employees who do not have any supervisors. So I'll just execute this, and then once I execute this, you get the details of that particular employee who doesn't have a supervisor. So guys, that was about operators and all. I won't go into each and every operator now. I'm leaving the rest to you so that you practice.

Next let's look into how you can use aggregate functions in SQL. So to use aggregate functions, what you can simply do is you basically have to use the functions as sum, maximum, average, and count. Right? For example, let's say, you know, we want to find out the sum, the max, the min, and the average salary from employee, let's say. So let's say, you know, I want to find out the sum, min, max of salary from employee. Right? So I'll just mention select sum(salary), min(salary), max(salary) from employee. Right? When I mention that, you'll see that, you know, the sum is so much, the minimum is so much, the maximum is so much. Right? That was about sum, min, max. Now let's say, you know, I want to count the salary. So what I'll do is I'll basically change this particular function to count. Right? And then I'll say count(distinct salary) because I'm going to count the unique ones. Right? And then I'll mention from employee. Right? So I'll just remove this particular section. Right? And then if I just execute this, you'll see an output of 7. Right? So basically we have seven distinct salaries. So that was about aggregate functions, guys.

Now next let's look into order by, group by, and having clauses. So as I mentioned before, the order by is basically used to get the output either in the ascending format or the descending format. The group by is basically used to group the data that you want by a specific column, and having is basically used to check a condition. Let's say we want to write a query to retrieve a list of employees and the projects they're working on, ordered by the department, and within each department they have to be ordered alphabetically by the last name and then the first name. So initially they have to be ordered by department, and then under each department also they have to be further ordered by the last name and the first name. So to do that what you can do is you can just mention select, and then you mention d.dname. Right? And then you mention e.lname. We also want the firstname. Right? So we'll mention e.fname and then p.pname from Department—this is a typo—and then we also want employee, we also want workson. Right? Now over here we have to mention as w over here, as e over here, as d over here, and then I forgot to mention the project, so project as p, and then you have to mention the condition which says where d.dnum is equal to e.dnum and employee.ssn is equal to workson.ssn and workson.pnum is equal to p.pnum, and then it is order by d.dname, and then I mentioned e.lname, e.fname. Right? And then if I just end this particular query, let's execute this particular query. You see an error that, you know, w.ssn not found because this has to be essn. Right? So I'll have to mention essn over here, and then let's execute this query again. It's a typo again, which is p.pnum. Right? Now let's execute again, and you see an output of dname, lname, fname, and project name. So initially if you see the dname is ordered by alphabetically, that is in the ascending order from A to R, and then under Administration, Wallace and Jennifer have come. Similarly, headquarters have Borg and James. Research has a lot of values, but underneath that also we have ordered them according to ascending order by, which I mean that, you know, it is ordered alphabetically by last name and then the first name. So that's how, basically, guys, you can use the order by. Now this was a little bit complicated one. If I just have to explain you with simple one, what you can do is you can consider the query of, let's say, you know, we want to find out the salary of all the employees in a descending order. So what we do is we just type in select * from employee order by, and then we mentioned salary descending. Right? Now if I just execute this particular query, you'll see that, you know, we get all the details of all the employees in the salaries of the descending order. In the case of descending, if you mention ascending, then you'll get an output of all the details of all the employees in an ascending order based on the salaries. So guys, that was about the order by clause.

Now let's move forward with the group by clause. Now let's say, you know, we want to find out for each department, we want to retrieve the department number and the number of employees in the department. Right? So now to retrieve the number of employees, you know, the aggregate function we have to use the count function, and then we want to group it by the department number. Right? Because we have to do it for each department. Right? The question says for each department we want to retrieve the department number and the number of employees. So to do that what I'll simply do is I'll mention a select query, department number, and then count(*) of all the employees, and then I'll mention from employee. Right? So let me just press on enter so that the keyboard doesn't move, and then I mentioned group by dnum. Right? Because we want to find it for each department, we're using this. So for each department we have a count, like, you know, in the department number five, the number of employees working are four; in department number four, the number of employees working are three; and in the department one, the number of employees working are one. All right? So that was about the group by clause, guys. I hope that was simple to understand.

Now let's look into the having clause. So having, as I mentioned before, is basically used to specify a specific condition. So let's say, you know, having count less than two, greater than two, having salary greater than 25,000 or maybe less than 30,000, and so on. Now let's say, you know, we have a scenario where we want to retrieve the data for each project on which, let's say, more than three employees work. We want to retrieve the project number and the number of employees who work on the project. Our main condition is that, you know, for each project where the employee count is more than three. Right? So for that what I'm going to do is I'm going to mention the condition select pnum, that is because of the project number, and then let's say I want to count the employees. Right? So I'll mention count(*) from Project, workson where pnum is equal to pnum, and then I group by for each project. Right? When you group by, you basically have to group by project number, and then I mentioned the condition having count(*) greater than—I forgot to mention the asterisk condition over here—three. So basically I'm mentioning the condition that, you know, we want to retrieve the project number and the count of employees who are working on the project where the project number from the project table matches the project number from the workson table, and then it is grouped by project number where the count is more than three. Now if I execute this particular query, you see that, you know, there's no data returned. Right? So that may be because, you know, the condition is not satisfied by any of the data that we have. So let's say, you know, we want to do it for two. So I'm just mentioning the condition to be 2, and I click on enter, and then you see that, you know, we get the project number two where you see the count is three, and then the project number 20 where you see the count is three. So initially when I mentioned the condition having count greater than three, the output did not come because there was no such data present. So that's the reason there was no output.

Nothing returned. But when we change the condition, you see that, you know, we get an output of two project numbers. So guys, that's how basically you can use the group by Clause, the order by clause, and the having Clause.

Next, as I was talking about the limit, offset, and fetch, let me just quickly cover that particular part so that we can go back and learn about SQL joins. Now, talking about a limit, as I told you, if you want to limit the data that you want to fetch, right, so basically, let's say, you know, we want to just fetch five rows, right? What you can simply do is you can just type in select star from, let's say works on, and then we limit five, right? And now if I execute this particular query, you'll see an output that, you know, only five rows of data will be printed out. So that's because, you know, we're limiting the data that has to be written.

Now, let's say, you know, we want to select three rows from, let's say works on table after the fifth row. So we want the next three rows to be printed after the fifth row. So for that, you have to use the offset statement. So what you'll do is you'll mention select star from works on, and then what you'll do is instead of limit over here, you'll mention offset 5, and then over here you'll mention limit 3. So after the fifth row, you want three rows to be printed, so that is the reason you'll mention offset 5 and limit 3. So let me just execute this particular query. So if I execute this particular query, you'll see that, you know, I've got the output of 6th, 7th, and 8th row. So basically, guys, that's how you can use the offset statement.

Now, let's say, you know, if you want to use the fetch statement. So as I mentioned before, the fetch statement is also used to fetch the records. So let's say, you know, I want to fetch the first eight rows. So what I'll do is I'll mention select star from works on and then mention offset 5, and then I'll mention first eight rows only. So after the fifth row, what I'll mention is I'll mention select star from works on, and then I'll mention fetch first eight rows only, right? So if I just execute this particular statement, you'll see the first eight rows. So over here, you can clearly see the output that, you know, when we used limit 5, you saw the first five rows, and then when we used offset 5 and then limit 3, we saw the next three rows. And now if you're using the fetch command where we say fetch first eight rows only, you'll see that, you know, we fetch all the eight rows, right? So that's how guys, basically you can use the limit, offset, and the fetch commands. So that was about till now. Now let's go back to our pgAdmin.

Next, let's look into joins in SQL. So all of you might be knowing what are joins, right? The joins in SQL are commands which are basically used to combine rows from two or more tables based on a related column between those two tables. So they are predominantly used when a user is trying to extract data from the tables which have one-to-many relationships or many-to-many relationships between them. So if you just have to understand joins in a simple language, then joins in SQL are basic commands which are used to combine rows from two or more tables based on a relative column between those two tables. So basically, there are four types of joins present: that is the inner join, the left join, the right join, and the full join. So as you can see on my screen, the inner join is the join which is used to return the records which have matching values in both the tables. So whenever you have matching values in both the tables, you use inner join. Coming to the left join, the left join returns records from the left table and also those records would satisfy the condition from the right table. The right join returns records from the right table and also those records will satisfy the condition from the left table. And finally, coming to full join, the full join returns all those records which either have a matching value in the left table or on the right table. So guys, these were the mainly four types of joins: that is the inner join, the full, the left, and the right join. Now let me just quickly take you back to pgAdmin, and then let's apply a few joins on the tables that we have. For example, let's say, you know, we want to apply left join. Right, as I've told you before, the left join is basically going to return all those records from the left table and also all those records matching the condition from the right table. What I'll do is and mention select, let's say SSN, I am going to mention first name, and then I mentioned dependent.dependent_name, and then I'll mention dependent.relationship, which is a column of the dependent table, and then I'll mention from employee left join, and then I'll mention the table one that is basically dependent on employee.SSN is equal to dependent.essn. So when I execute this particular query, you see an error that, you know, the table is not found because we have an error with the column name. So let's just check the column name. Okay, it's underscore, so I'll mention underscore over here. So when you see the output, you can clearly see that, you know, we've got all the records from the left table, that is the dependent table, and then all the records which also match with the condition from the right table. So that's how guys, you can apply left join. Now similarly, you can apply right join also. So for the same condition, let's apply the right join and let's see the difference in the outputs, right? So what I'll do is I'll just scroll again, and then I'll just change it to right join, and now I'll execute again. So let me just execute this particular query, and once I execute this particular query, you'll see a difference, right? So that's basically how you can play around with joins, guys. This was about left and right. Now before I conclude the Joins Part, let me also talk about the inner join and the full join. So the inner join is basically where you have matching values in both tables, right? So let's say, you know, we select SSN and first name, and let's say, you know, we remove this particular section, and then we mentioned from employee, I'll mention inner join dependent on employed.SSN is equal to dependence. So we'll get all those records which have matching values in both the tables, right? I'll execute this particular query, and you'll see the output, right? So these are basically all those values which have a matching values in both the table A and table B. And finally, let's say, you know, if I want to specify the full join, which basically will give me the output of all those records which either have a matching value in the left table or on the right table, what I can do is I can simply mention full join over here, and then I execute this, and then you'll see an output like this, right? So basically, you'll see that, you know, these are all the tuples which have either a matching value in the left table or on the right table. So guys, that was about joins.

Next in this session, let's move forward and take a look at the views. So views are really simple, guys, as the name suggests. Views in SQL is a single table which is derived basically from the other tables. So for instance, if you consider the example on my screen, I have two tables, right? Now, for example, let's say I want to create a new view which will basically have few columns who rows from a specific table and few columns or rows from the other table, right? So that is basically my view. So now views are used in industries to basically collaborate with the data of many tables so that the company can understand how to go about the next action step they should take while taking any specific decision. So without wasting very any further time, let's take a look at how we can create a view. So to create a view, it's really simple. Either you can use the query tool, or what you can do is you can just go to the view option, right-click over here, choose create, and choose View. Since I'm writing queries for all of them, I'll show you by writing queries itself, else you can use this option also. So talk about views. So to create a view, it's really simple. As you create a table, you can similarly create a view like, you know, create view, and then you mentioned view name. Let's say we're going to create a view for the works on table, so I'll mention works_on_one, and then what I'll do is I'll mention the condition. So if you stop over here, this will simply create a view, and this will not store any particular data that you want, but if you start mentioning the condition, then it will have all the data according to the condition that you have mentioned, right? So over here what I'm doing is I'm going to mention the details of an employee who work on a specific project. So for that, I'm going to do is I'm going to just create a view over here. So as I'm creating, so I'll type in create view works_on_one, and then I'll mention the condition as select first_name, last_name, and project_name from employee, project, and works_on where SSN is equal to essn and project_number is equal to project_number, right? So that is basically the project number matching from the project table to the works on table and the SSN matching from the employee table to the works on table, right? And then I'll just execute this particular query, right? Once you execute this particular query, you see an output that, you know, query returns successfully. Now if I just refresh this particular views, you'll see a view named as works_on_one with the columns that you've mentioned: that is first_name, last_name, and the project_name. Now if you want to see the data present in this particular view, what you can do is you can just mention select star from, and then you mentioned the view name, that is works_on_one, right? And then if I execute this, you'll see the output, right? So that is basically the data that is automatically present in our view, and the view is created by deriving data from other tables like the employee table, the project table, and the works on table. So that's how guys, basically you can create a view. Now let's say, you know, you want to drop a view. Dropping a view is also really simple, guys. You have to type in drop view, and then the view name, right? So if I mentioned works_on_one, and then if I end with a semicolon, you'll see that, you know, the drop view is successful. So if I just refresh this particular section, you'll see that, you know, there's no view available. So guys, that's how basically you can drop view also. So guys, that was all about views. I'm not going to go into depth of how you can create more complicated views and all because I've given you a basic understanding of how views are created and how you can drop the views also. Rest I leave with you to practice. Please remember the fact that, you know, I'm just giving you all the basic concepts so that you get started with PostgreSQL, but if you have to get a good understanding of all the databases, then make sure you have good practice. On that note, let's get started with the next topic for today's session: that is procedures. So procedures are basically a section of code. So basically, you can understand procedures as a section of code or functions which you can save, you know, and then you can reuse it, right? So whenever you want to save a section of code or maybe a function, and then you want to keep reusing it, that's where stored procedures come into the picture. So for example, let's say, you know, you want to create procedures, right? So what I'm going to do is I'm going to create a new table. Let's stop with the example of employees and works_ons and so on. Let's move on with a new example. Let's say, you know, I create two tables. So I'll mention create table, and then I'll mention let's say the table name, table first table to be tbl1, and then I'll mention the column to be tbl1_ID, and then let it be int. Now similarly, I'll create another table also. So let me just change it to table2 also, and then now what I'll do is I'll just execute this particular two statements, right? So if I just refresh this section over here, right? So now you will see that, you know, instead of six tables, now there are eight tables. So let me just minimize the others so that you have no confusion, right? So we have two tables: that is tbl1 and tbl2. Now let's say, you know, you want to create a procedure such that, you know, you want to insert values. So basically, I don't want to write insert into statements 110 times. What I'm going to do is I'm going to just create a simple function through which you can insert values. So to insert values, what you can simply do is I'll mention create procedure, and then let's say mention the procedure name to be insert_values, and now let's say, you know, we mentioned what values have to be inserted. Let's say, you know, value X has to be inserted in table 1 and value Y has to be inserted in table 2. So I mentioned X integer and Y integer, and then what I'll do is I'll mention language plpgsql because it is a form of SQL as $$ and then I'll mention insert into tbl1 that is basically my first table values X, right? And then I'll mention insert into tbl2 values Y. After that, I'll just end this section with $$, and semicolon, and then what I'll do is I'll basically call this particular function. So this is basically how you create a procedure, but yes, if you want to reuse a procedure, then you have to call that particular procedure, right? So for that, I'll use the function call insert_values, and then I'll mention let's say 1, 2, right? So these are basically the two values that I want to mention in table one and table two. So the table one should be inserted with value one, and then table two should have the value 2. And now what I'll do is I'll execute this particular section completely. Once I execute this particular section completely, you'll see an output that, you know, call query has been returned successfully, right? Now let's just use the select statement to see whether, you know, the value has been inserted or not. So let's say I'll mention select star from table one, and then similarly, I'll mention select star from table two. So if I just print select star from table one, you see the value to be one, right? I hope that you can see now. Similarly, if I mentioned select star from table two, you'll see the value to be 2. So that means our values have got inserted. So guys, this is a really simple example. I've just taken two tables with a single column. Now you can have any number of columns, and then you can mention any number of columns to be present over here, and then you mention the specific values into the insert statements, and then what you just have to do is you just have to keep changing the values over here. So for example, let's say if I do 3, 4 over here again, and then I execute the statement call insert_values, and then let's say, you know, I execute the statement select star from the tbl1, so you'll see that, you know, apart from one, we also have the value 3. Now similarly, if I do select star from tbl2, you'll see the output that 2, apart from two, we also have four. So that's how basically, guys, you can create stored procedures. Well, I think it was really simple to understand how you can create procedures and so on, right?

Now in this session, let's move forward with the next topic: that is triggers. Now triggers are a set of SQL statements which are stored in the database catalog. Now these statements are executed whenever an event associated with the table occurs. So a trigger is basically invoked either before or after the data is changed by either the insert statement, the update statement, or the delete statement, and it only invokes whenever there's an event associated with the table. So now let's look into how you can implement triggers in PostgreSQL. So to implement triggers, uh what I'm going to do is I'm going to create a table first. So let's say I create a table audit, and then let's say, you know, I'm going to consider employee_ID, right, to be of char type and nine characters since our SSN is of 9 characters, and then it should not be null, and then apart from that, I am also going to consider, let's say, you know, we have entry_date, right? Let's say joining date or maybe entry_date, and then we have text, it's of text data type, right? And there should not be any space because that is also a data type, and then I'll mention not null. Now what I'm going to do is I'm going to create a function, and then I'm going to create a function which returns a trigger as a specific trigger, and then I'll use that particular trigger on the employee table. So let's do the same now. Once I create this table audit, what I'm going to do is I'm going to create a function audit_log_func, which will basically return the trigger as example_table, which will begin whenever you wish to insert something into the audit table. Now the trigger example_table will be created then. So let's just do the same. So now since I've created the table audit, let me create the function, right? So to create a function, you have to type in create or replace function audit_log_func, that is basically, you know, the function name that I'm giving, and then I mentioned returns trigger as, and then I'll mention the trigger name, let it be example_table, right? And then I'll mention begin, right? So it will begin then, and then I'll mention insert into audit where emp_ID and entry_date will be mentioned, and values will be new.SSN, a new SSN will be generated, and then automatically the current timestamp will be taken as the entry_date, right? So that's how basically you can also use timestamps also, guys. So basically, what I'm doing is whatever is the current time, I'm using that particular current timestamp. So I'll mention current_timestamp, and then what I'll do is I'll mention return new, and then end. So this is basically the function that I'm creating. So the function basically says that, you know, it will return a trigger as example_table whenever you want to insert something into the audit table. Now as I was talking about the trigger example_table, we have to create that also, right? Now before that, I forgot to mention something over here: that is, you know, you have to mention example_table, that is basically in language plpgsql, right? So you'll have to mention that particular fact over here. Now after that, if you wish to create a trigger, you'll mention create trigger example_trigger after insert on basically whenever you're inserting employee for each row, I am going to execute the procedure or the function that I just created. So that is basically my audit_log_func. So I'll just copy from here, paste it over here, and then finally, I'll mention the insert statement. So what I'm going to do is the insert, since we are doing on the employee table itself, I'll just copy this particular fact over here, and then what I'll do is I'll paste it over here, and let's say I mentioned it's l, and then I mentioned and, let's say I randomly put in details, right? And then let's say I changed the salary also so that there's no redundancy anywhere, right? So what have I done over here? I've basically created a table audit. So this audit table is basically like, you know, whenever I want to insert into the employee table, a trigger will be created. So basically, a trigger will be invoked which says after insert on, you have to mention the procedure, right? So basically, the procedure is basically the function that we created that's basically it returns to a trigger example_table where, you know, it inserts into the audit table automatically, that is basically the employee_ID that I've mentioned over here, and automatically the current timestamp as the entry_date. So let's see what happens. So what I'll do is I'll execute from here to here, and let's just check if everything is selected. Yes, and then I execute. All right, it says syntax error at employee_ID value current. Oh, it's because the current_timestamp spelling is wrong over there. So let's just correct that. Now I'll again execute this particular...

Section again. It still says that you know there's an error over here. Yes, that's because you know I've missed com over here, and then I'll put the bracket. So I've removed the brackets, and then I have to put the comma, and then again let's try executing this particular section. It says that you know the key super SSN is not present in the table employee. Right, so that's because we cannot randomly do and we have foreign keys present. So let's just randomly choose any super son, let's say triple three double four four times five, right? And now I'll go back, and now let's execute again. Once I execute again, you can clearly see an output that in a query returned successfully. Right? So let me just refresh tables and let me just refresh triggers. So once I refresh tables, you'll see that you know there's an employee table, and then we also see there is an audit table, and the order table has the columns employee ID and entry date. Right? And then we have a trigger function which says audit log function is basically the trigger function that we just created. Now, if I wanted to see the data from the audit table, I'll just choose select star from audit, and then you'll see automatically the employee ID and the date, which is basically the current time, is generated. So that's how, guys, basically you can use triggers. So with this, we come to an end of the data manipulation commands. I hope you've understood all the commands and the syntaxes and the statements that I just showed you.

Now let's move forward with the next set of statements, that is the data control language commands. Now, the data control language commands, as I previously mentioned in the starting of the session, is basically used to provide rights and privileges to the users to access database views, tables, and so on. So basically, there are only two statements that you need to understand in this particular section: that is the grant statement and the revoke statement. So let's consider the grant statement. So the grant command is basically used to grant privileges to the databases or tables. For example, let's say you know we consider the table one we created over here. So if I right-click over here and go to properties and let's say I go to Securities, you see that you know there's no grantee privileges, there's nothing present over here because there are no privileges granted to this particular table. So let's grant permissions to this particular table. So what I'm going to do is I'm going to type in Grant select on, then I'll mention the table name, that is table 1 to, and I'll mention public, and then I'll just execute this particular query. You'll see that you know the query has been returned successfully, and now what I'll do is I'll right-click over here, go to properties, and then go to parameters, and then go to security over here, and then you'll see that you know automatically we have granted a public privilege to this particular table.

Now let's say you know we want to grant privileges on basically the command insert on. Right? So whenever there's some insert on, we want to grant privileges to the public, so anybody can insert into this particular table. Now let's say you know we want to grant insert on privileges to the employee table. Right? So basically, anybody can insert into this particular table. So that is basically Grant insert on employee to public. If I just execute, you see the output of query returns successfully. Right? So now what I'll do is I'll just go to my employee table over here, go to properties, go to security, and you'll see public, and then you'll see a privileges of a right, basically all. So that's how basically you can grant privileges, guys. Now you can also revoke back your privileges. Let's say you know you want to revoke back the privilege that you just gave. So for that, you just have to use the statement revoke. Right? So you'll type in revoke insert on employee, and then instead of to, you'll mention fra. So you'll mention revoke insert on employee from public. Right? So you'll just execute this particular query, and then we'll go to properties again over here, go to security, and then you'll see that you know there's no more public privilege present over here. So guys, that's how basically you can control privileges and rights for your databases and tables.

So guys, that was about data control language commands. Now moving forward, the next type of commands that we have is the transaction control language commands. So the transaction control language commands come into the picture when you want to make sure that you know the transaction in the database is meeting all the standards, that is basically the ACID properties. So ACID properties are basically a term which the consistency, isolation, and durability. So basically, if you want to make sure that you know your database is making sure that the transaction properties are met, then you have to use this transaction control language commands. So to use transaction language control commands, what I'm going to do is I'm going to perform transaction on table one. Right? So let me just see what values are present in table one. So let me just see, I forgot to mention from over here, so it's Select Staff from table one, and then you'll see one free. Right? Now what I'm going to do is I'm going to insert around values till 10. So let's insert all the other values. I'm just going to copy it from my doc over here. So since I have already one and three values present over here, what I'm going to do is I'm not going to insert these values, so I'll just remove these, and then I'll just execute them. Right? So you'll see that you know data has been inserted into my table. Now let's begin a transaction. When I say begin a transaction, you have to use the syntax known as begin. So you'll type in begin, and then let's say you know we want to delete all the values which have the ID greater than 5. Right? So basically, all the tuple values which have the either greater than 5 have to be deleted. So for that, we are initializing a transaction, and then I'll mention delete from and table 1 where table one ID. So let me just check the column name, that's tbl1 ID is greater than 5. So I mentioned begin, so basically my transaction will begin, and then what I'll do is I'll delete. So let's just do that. Right? So you can see that you know the transaction is running on, and then we have deleted till 5. Now let's say you know if I want to roll back, rollback is basically I don't want it to occur. Right? So when I hit on rollback, you'll see that you know automatically all the 10 values will come back. Right? So if I just use the syntax of Select star from table one, you'll see the output of 1 to 10 again. So what you should understand from over here is basically that you know the begin is basically used to begin the transaction, and the rollback is basically used to roll back from the previous transaction. So what I've done is that I started the transaction, and then I deleted the values greater than 5, so all the values got deleted. Now when I hit on roll back, what happened is that you know the transaction got rolled back, then automatically all the values got retrieved. So that's how basically you can do roll back. Now similarly, you can do commit. Right? So what I can do now is I can type on Commit over here, and then I can begin a transaction again. Right? So so once I begin a transaction again and once I delete all the values greater than 5, and then when I hit on Commit, you cannot roll back. Right? So all the values will be deleted whose IDs will be greater than 5. So if I just execute this particular statement, you'll see that you know you only have one to five values. Now similarly, you can also about the transaction using the statement aboard.

So guys, that was all about transaction language control commands. Now let's move forward with the next topic, that is how you can export and import data. Well, guys, exporting and importing data is really simple. For example, let's say you know I want to export and import data of the table one values. Right? So what I'll do is I'll right-click over here, and then go to import export option, and then what I'll do is I'll mention the file name. Right? So basically, I'm exporting, and I'll search for let's say demo.csv. Right? So now demo.csv is present in my e folder. Right? I'll choose that, and then I'll click on create. Once I click on create, you'll see that you know if I want to replace, well, I have a pre-existing file, so I'm just allowing it to replace. Well, you can do that. Right? And then you'll click on OK. Once you click on OK, you'll automatically see that you know the details have been copied. Right? So what I'll do is I'll go over here, go to e-fold domain, and go to demo.csv. So in the demo.csv, you can see that you know we've got the data one to five because we just had one row column that is one to five, and we just deleted the other values. So that's how, guys, basically you can also export and import data. It's really simple in PG admin.

Now finally coming to the final topic for today's session, that is the UUID data type. Now the UUID data type is basically the data type which is based to uniquely identify a particular value. Right? For example, as I was talking in employee, I said SSN. Right? So for every value, I had to insert an SSN, basically I had to insert a value. Maybe if you don't want to do it, what you can do is you can just directly use this particular extension, and then you can directly use that particular value. So now let me just shift back to my PG admin. Now let me close this particular part. Let me scroll back, and now let's say you know we want to see first what are the available extensions. Right? So I'll just type in select star from PG hyphen available extensions. So I'll mention this and I'll click on execute. Once I click on execute, you'll see that you know we have name, we have default value, we have installed version, and we have comment. Right? So we have a lot of available extensions, but what I want to use is the uuid OSB. Right? So if I scroll down more, you'll see this particular one. Right? That is uuidosp, that's what we want to use over here. So initially, if you know if you do not have this extension, what you can do is you can just create this extension. So you'll type in create extension and mention if not exists, and then you'll mention uuid hyphen OSP. So this has to be in single quotes, and then you'll just execute this. So let me just execute this by dragging this down. So it says it's not fine. Oh yes, it has to be in double quotes itself. That was my bad. So when you create extension if not exists uuid OSP, you see an output of you know create extension. Now what you can do is you can just directly select from the available extension. Now once I create the extension, and then if I select uuid generate V4, you'll see that you know automatically a new ID is getting generated. Right? Now the next time I execute this particular statement again, you'll see that you know a different ID will be generated. So that's how basically you can use uuid as a primary key for the table. So for example, in the social security number of employee table, you could have used in this. Now in that scenario, you don't have to sit and mention the SSN over there, you can just put the specific function that is uuid underscore generate underscore V4, and automatically you see that you know every time you hit the query, you'll see a new ID will be generated. Right? So guys, that was all about uuid data type. Now you can use uuid data type as a primary key to uniquely identify your data type.

[Music] What is database management system and what are its different types? Database management system, or most commonly known as DBMS, is a software application used to access, create, and manage databases. With the help of DBMS, you can easily create, retrieve, and update data in the databases. A DBMS consists of a group of commands to manipulate the database and also acts as an interface between the end users of the database. So if I have to just summarize DBMS for you, then DBMS allows the users to define the data, to update the data, to retrieve the data, and also for the administration of the users. When I say define the data, it allows the users to create, modify, and delete the definitions which define the organization of the database. When I say update the data, what I mean by that is that you know it provides access to the users to insert, modify, and delete the data from the database. Coming to retrieve data, it allows the users to retrieve the data from the database based on the requirement. And finally, coming to administration of users, it registers the users and monitors their action and enforces data security, maintains data security, monitors performance, and deals with the concurrency control. So guys, that was about DBMS. Now there are mainly four types of DBMS: that is the hierarchical DBMS, the network DBMS, the relational DBMS, and the object-oriented DBMS. Talking about the hierarchical one, as the name suggests, this type of database management system showcases a style of predecessor and successive type of relationship. So you can consider it to be similar to a tree wherein the nodes of the tree represent the records and the branches of the tree represent the fields. Coming to relational database management system, this type of database management system has a structure which allows the users to identify and access the data in relation to another piece of data in the database. In this type of database management system, the data is stored in the form of the tables. Coming to the network database management system, the network database management system supports the many-to-many relationships wherein multiple user records can be linked. And finally, coming to object-oriented database management system, this type of database management system uses small individual softwares called objects, and and here each object contains a piece of data and the instructions for the actions to be done with the data. So if you ask me if you popular database management softwares, then they have MySQL, PostgreSQL, Oracle, SQLite, MariaDB, and Microsoft SQL Server. Now all these softwares are based on different types of database Management Systems available in the market, so it's completely based on the user's choice, or I would say your choice, on which type of database you want to work on and what type of DBMS would benefit you more. So I hope that you've understood what is DBMS and what are the different types of DBMS. Now let's move forward with the next topic for today's session, that is SQL, structured query language, or pronounced as SQL, or sometimes also known as SQL, is a standard language for dealing with the relational databases. Now to explain you further, let me take an example for you. Now if two people want to communicate with each other, then they have to use certain language which is understood by both of them. Right? So if we consider these two people as one as the user and other as the database, then the language which is used to communicate between these two is nothing but the structured query language. So similarly, how a language has a grammar and various rules on how it could be used, even SQL has its own directives. SQL is effectively used to insert, search, update, delete, and modify the database records, and it doesn't mean that you know SQL cannot do things beyond that. It can do things beyond that also. It can provide you integrity checking; it can also provide you with embedded DML, which is used for general-purpose programming languages. It has various sets of commands to create different kinds of views, tables, and other networks to understand the database effectively, and many such more. So guys, this was about the basics of SQL and DBMS. If you want to learn more about SQL, then you can refer to our session on what is SQL, and I'm sure you'll get a better idea of what is SQL. But since this session is based on SQL Server, let's get into the main topic for today's session, that is what is SQL Server. Now Microsoft SQL Server is basically a relational database management system which supports the structured query language and comes with its own implementation of the SQL language, which is known as the Transact-SQL or the T-SQL. So it basically has an integrated environment to handle SQL databases, which is nothing but the SQL Server Management Studio. Now the key components of SQL Server are, as you can see on my screen, we have a database engine, and this component is basically used to handle storage, rapid transactions processing, and securing the data. Coming to SQL Server service, this service is used to start, stop, pause, and continue the instance of the Microsoft SQL Server. Moving on to the next component, which is the SQL Server Agent, the SQL Server Agent service placed the role of the task scheduler and is triggered by any event or as per the requirement. Coming to SQL Server Browser, this service is used to connect the incoming request to the desired SQL Server instance. Coming to SQL Server full-text search, this is used to let the user run full-text queries against the character data in SQL tables. Coming to SQL Server VSS Writer, this particular service allows backups and restoration of data files when the SQL Server does not run. Moving on to the next component, that is SQL Server Analysis Services, that is SSAS, this service is used to provide data analysis, data mining, and machine learning capabilities. The SQL Server is also integrated with Python and R for advanced data analytics. Coming to SQL Server Reporting Services, which is SSRS, as the name suggests, this service is used to provide features and decision-making capabilities, including integration with Hadoop. Finally, coming to the last component, that is SQL Server Integration Services, that is SSIS, this service is used to perform the ETL operations for different types of data from multiple sources of the data. So I hope that you've understood what is SQL Server. Now let's move forward with the next topic for today's session, that is features of the SQL Server. So the first one is user experience. So when I say user experience, what I mean by that is that you know SQL Server can be used on various operating systems like Windows, Linux, and Docker. So you just have to develop once and deploy anywhere with their consistent experience from on-premise to Cloud. Right? Not only this, but they make sure that you know you as a user get a consistent experience from on-premise to the cloud and also provide easy-to-use tools and the connectors. So you can use the Azure Active Directory and the SQL Server Management Studio to manage your database infrastructure across on-premise SQL Server and also Microsoft Azure. So isn't that great, guys? Now moving on to the next feature, the next feature is availability. So when I say availability, again, what I mean by that is that you know SQL Server make sure that you know it provides high availability and disaster recovery. So with this, you can gain mission-critical uptime, fast payload, easy to set up, and load balancing of the readable secondaries with the enhanced SQL Server versions. So you can get unified solutions for high availability and disaster recovery on Linux and Windows. Not only this, but you can also put up an asynchronous replica in the Azure virtual machines for the hybrid high availabilities. So that was about availability, guys. Moving on to the next feature, that is performance. So when I say performance, what I mean by that is that you can scale your price and performance in a parallel manner. So SQL Server makes sure that your real-world application performance benchmarks are set, and then your application using the SQL Server database is not failed down or is not turned down. Right? So you can get great performance for your application, and it is also one of the highest-performing data warehouses. Moving on to the next feature, that is analytics. So when I say analytics, what I mean by that is that you know SQL Server provides the built-in analytics, or you can say the built-in database advanced analytics. So with the help of the built-in analytics and the SQL Server Machine Learning Services using R and Python, you can move beyond the reactive and into predictive and prescriptive analytics by performing advanced analytics directly within the database. So by using multi-threading and massively parallel processing, you'll gain insights faster than using open-source R and Python. So guys, that is one major plus point of SQL Server. Now moving on to the next feature, that is security. So security, as the name suggests, I would say that you know it provides less vulnerable databases. So you can make sure that you know your data is protected in a proper manner and is less vulnerable to any other major attacks. Not only this, but you can also make sure that you know you

Have levels of security and compliance for the databases. Now coming to the final feature, guys, that is business intelligence. So obviously, as the name suggests, business intelligence is almost used in today's market in every company, and every company needs a manner to understand and visualize the reports and also gain insights. Right? So SQL Server provides you with this feature and allows you to build comprehensive Enterprise-scale analytics solutions by benefiting from the fast performance of in-memory built into the tabular model. So basically, what happens is that unit reduces the time to insights using direct querying against tabular and multi-dimensional models. So guys, those were the features of SQL Server. So I hope that you have understood what is SQL Server and its features.

So now that you know the basics of Database Management Systems, SQL, SQL Server, let's move forward and install SQL Server. So to install SQL Server, what you have to do is you have to follow the steps that you can see on my screen. Initially, you have to install the SQL Server, and then you have to connect to the SQL Server using SSMS, that is the SQL Server Management Studio. After that, you have to access your database engine. I hope I'm clear with these points. All right, so let's start with the installation of SQL Server. So initially, what I'll do is I'll install the SQL Server, then I'll connect to the SQL Server using SQL Server Management Studio, and then I'll access the database engine.

Now, to install the SQL Server, what you have to do is you have to go to this official website of Microsoft SQL Server download. Right? So I'll just go to this particular page, and once you go to this page, you see these two options: that is SQL Server 2017 on-premises and on the cloud. Now, what this means is that you know you can either use SQL Server locally on your system or maybe on the cloud. So now what you have to do is you have to scroll down this particular page, and you will see this option of developer and the Enterprise Edition. So here I'll be downloading the Developer Edition. So to download, you just have to click on this option of download now. Now you can see that you know the application is getting downloaded. So once the application is downloaded, what you have to do is you have to double-click on this particular file, and then you will see a window opening up. So let's just wait for that to happen. So as you can see, our application is opening up now. Once the application opens up, you see various types of installation types: that is the basic type, the custom type, and the download Media. So what I'll do is I'll just choose the basic type. So when you choose the basic type, you can select the basic installation type to install the SQL Server database engine feature with the default configurations. Just remember, guys, when you're choosing the basic type, you're installing SQL Server with the default configuration.

Moving on to custom type. So when you select the custom installation type to step through the SQL Server installation wizard, you choose the features, or I would say you choose the configuration based on your choice. Right? So I would say if you're using it on an Enterprise level or maybe a complete company is using SQL Server, then I would say you can go forward with the custom installation because you may have few features, or you may want few configurations which must be the same for the complete users. Right? So that's when I would say you can go for the custom one, but if you're someone who is just using SQL Server locally on your machine and then you just want to get hands-on experience on that, I would say go for the basic one. Right? So on that note, I'll just choose the basic one, and then once I choose the basic one, you can see that you know we get this page of SQL Server license terms. So what you can do is you can just go through the license terms, and then you can just click on the accept button. So I'll just directly click on the accept button, and once I click on the accept button, you have to next specify the SQL Server installation directory. Right? So that means where you want to install your SQL Server. So I'll just let it be as it is, and then I'll click on install. Now, once you click on install, you will see that all the required packages and the libraries are getting downloaded. Now let's just wait for the installation to complete. So as you can see, the computer requires a restart, so let me just restart my computer. Right? So let's just increase start.

Now, once the installation has completed, what you next have to do is you have to go to this customize option pillow to basically configure your SQL Server database. Right? So I'll just click on this customize option. Now, once you click on the customize option, this is a screen that you will see. So over here, what you just have to do is you just have to click on next, and once you click on next, you'll basically see that the files are getting installed. Right? So let's just wait for that to happen, and then you keep clicking on next. I'll tell you when you have to configure for something. So let's just wait for that to happen. All right. Now, once the installation rules are also done, the next thing that you have to do is you have to choose the installation type. So since we are performing a new installation, we'll just choose this option of perform a new installation of SQL Server 2017. But yes, if you had any pre-installed SQL versions, then you'll choose the second option. Right? So I'll just choose this option of perform a new installation of SQL Server 2017, and then I'll click on next. Now, in the next wizard that opens up, you have to choose basically the type of Edition that you are installed initially, that is the Developer Edition or the Enterprise. Since I downloaded the Developer Edition, I'll just choose developer, and then what I'll do is I'll click on next. Now, after that, you have to read this license terms and then just click on this radio button of I accept the license terms and then click on next. Now, in the next wizard that opens up, you have to choose the features which you wish to install. Also, you can choose the instance root directory and then click on next. So what I'll do is I'll just choose the features, let's say database engine, and then I'll let the root directory be the same, and then I'll click on next. Now, after that, what you have to do is you have to name your instance, and then this will automatically return an instance ID. Right? So I'll just name my instance, let's say edureka. Right? And once I mention my instance name, you'll see that you know automatically my instance ID will be edureka. So after that, what I'll do is I'll just click on next. Now, in the server configuration wizard, just click on next, and then once you click on next, you'll be redirected to this database engine configuration. So over here, you have the Windows authentication mode and the mixed Port. So over here, what I'll do is I'll just choose the mixed mode, and then I can mention the password. Right? So I'll just mention the password, and then I'll confirm the password, and then what I'll do is I'll just click on ADD current user, and you'll see that in automatically a user has been added. So this particular user will be the admin. After that, as you saw, I just mentioned the password, and then I'll click on next. Now, once we click on next, you can see the summary of the installation, like what are the properties or the features which will be installed. So you can just go through that, and then what you can do is you can just directly click on install. So I'll just click on install over here, and now let's just wait for the installation to complete. Now, once the installation is complete, this is the wizard that you see, that means that your installation has completed. So I'll just click on close, and then with this we finish our installation.

Now, the next step is to connect a SQL server using the SQL Server Management Studio. So for that, what we'll do is we'll go back to this particular screen, and then I'll click on install ssms. Now, once you click on install ssms, you'll see that you know you'll be redirected to a web page. So let's just wait for that to happen. So guys, this is a screen that you see once you click on install ssms. Now, what you have to do is you have to just click on this download option. So I'll just click on this download SQL Server Management Studio link, and then once I click on the link, you can see that you know the setup is getting downloaded. Right? So let's just wait for that to happen again. All right. Now, once the setup has been downloaded, just double-click on this particular file, and then you'll see this particular screen. So over here, you can just choose the location or the installation directory for your SQL Server Management Studio. I'll let it be as it is, and then I'll just click on install. Now, once I click on install, you can see that you know our SQL Server Management Studio is getting installed. So let's just wait for that to happen, and once that is done, what we'll do is we'll basically access our database engine. So let's just wait for installation to complete. Now, once the installation is completed, you see that you know restart is required in order to do the complete setup. Now, once the SQL Server Management Studio is installed, you just have to open your SQL Server Management Studio from the Windows Explorer. So here you can just type in SQL server, and then you'll see this icon. So you just click on open, and once you click on open, this is basically what you see. Now, over here, what you have to do is you have to choose your server name. So you can just go for browse for more and just choose server name, and let's say we choose our desktop ID edu breaker. Right? That is because that is the one that we chose. So we gave our instance ID to be Eddie Eureka if you remember. So I'll choose that, and I'll click on OK, and then I'll click on connect. Now, once you log in, guys, this is the screen that you see. Now, the next thing that you have to do is you have to basically start your query editor. Right? So before we get into the query editor and start using the commands, let's understand how does the SQL Server architecture look like. So the SQL Server architecture mainly has few components that you can see on my screen. So it has a server, it has the relational engine, the command parser, the optimizer, the query executor, and the storage engine. Coming to the server first, this is where the SQL services are installed, and the database resides. Moving on to relational engine, this contains the query passer, Optimizer, and the executor, and the execution happens in the relational Engine. Moving on to command parser, well, this checks the syntax of the query and converts the query to the machine language. Moving forward with Optimizer, this prepares the execution plan as the output by taking statistics query and the algebra tree as input. Moving forward with the next component, that is query executed, well, this is the place where queries get executed step by step, and the storage engine is responsible for storage and retrieval of data on the storage system manipulation of data, managing and locking transactions. So you have a transaction log, and then you have a data file. You also have a storage engine which has the transaction manager, the access methods, and the buffer manager. After that, we have the relational engine. Well, the relational engine has the optimizer and the command passer, and the command passer is connected to the query tree, and similarly, we also have the query executor which executes the query, and the optimizer optimizes the query. Finally, we also have a protocol layer which has the Sni, and then this is connected to the SQL Server network interface. Well, guys, this was about the SQL Server architecture on a high level. By now, I hope that you've understood and got a good understanding of the SQL Server. Now let's move forward and get into the SQL command categories where there are mainly four command categories that we're going to consider: that is the data definition language commands, the data manipulation language commands, the data control language commands, and the transaction control language commands. Coming to data definition language commands, well, this consists of the commands that can be used to define the database schema. Moving on to data manipulation language commands, well, this deals with the manipulation of the data present in the database. Coming to data control language commands, well, this deals with the rights and permissions and the controls of the database system. And finally, coming to transaction control language commands, and this consists of the commands which deal with the transaction of the database. So I hope that you've understood what are the SQL command categories. So before we move forward with the First Command category, that is the data definition language command category, let me talk a little bit about the SQL Server data types. Well, there are various kinds of SQL Server data types present. So when I say data types, I mean what kind of data can be stored in your databases. So you can store exact numeric data types, the approximate numeric data types, the date and time values, the character strings, the Unicode character strings, the binary strings, and many other data types. So talking about the exact numeric data type, well, the exact numeric data type is used to basically store the numbers. So in this data type, you have other data types like the numeric, the tinyint, smallint, bigint, and so on. Moving on to approximate numerics, well, approximate numerics are used to store decimal or float value. So you have the float data type and the real data type. Coming to date and time, as the name suggests, this type of data type is used to store the date and time values in the database. So we have date, small datetime, datetime, datetime2, and so on. Moving on to character strings, well, this particular data type is used to store the character strings like char, varchar, text, and so on. The Unicode character strings are used to store the nchar, nvarchar, and ntext. After that, coming to Binary strings, binary strings, as the name suggests again, are used to store the binary values. So we have binary, varbinary, and image values in this particular data type. And in the other data type sections, we have data types like the cursor, the rowversion, hierarchyid, uniqueidentifier, and so on. Well, I would say once you get a Hands-On practice on how to write queries and how to manipulate data in your database, you'll definitely understand which type of data type you need to use or you need to use to define your columns. So I hope that you've understood. So on that note, let's start with the first language command category, that is the data definition language commands. So to demonstrate the data definition language commands, what I'm going to do is I'm going to create few queries, and then I'm going to explain how you can use that. So now what I'll do is I'll just add a query pane. So to do that, what I'll do is I'll just go to this new query option, and then you'll see that in automatically our query pane opens up. Let me just zoom in a little bit. So now that I've zoomed in, let's get started with the session. Initially, what I'll do is I'll just create a database. So to create a database, you'll type in a command create database, and then you'll mention the database name. Right? So let's say I mentioned the database name to be students. Now, after that, you just have to select this particular statement and click on execute. Now, once you click on execute, you clearly see that you know the commands have completed successfully. So our database has been created. If I just refresh this particular section and then I go to databases, you see that you know we've got our students database. Right? So now to perform any action in a database, you have to first use that database. So for that, you'll just type in use, and then you'll mention the database name to be students. Right? And then what you'll do is you'll just execute again. Right? And once you execute again, you'll see that you know the commands have been successful. So that means whatever actions that you're going to perform is going to happen under this particular database. Now, after that, what you can simply do is you can just create a table. Right? So to create a table again, you just have to use this command of create table. Right? So I'll just mention create table, and then you can mention the table's name. So let's say we just mention it to be students info. Right? And then in brackets, what you have to do is you have to mention your column names and its data types. So the column names could be like student ID, let's say it to be of int. Right? Next, let's say student name, let's say varchar of 8000. Similarly, we can have parent name, again of varchar, let's say 8000. After that, you can have phone number, let's say bigint because it's going to have a large value. After that, we can have address of a student. Right? So I'll just mention address of a student, again varchar. Then I'll mention City, let's say varchar of 8000. Then I'll mention country, again of varchar of 8000. After that, you can just close this, and then once you do, you can just execute this particular statement. So after the statement is executed, what you can do is you can just refresh this particular section, go to databases, go to students, and in students, you'll see that you know if you go into the table section, we find a table of students info. So that's how, guys, basically you can create a table also. Now, for example, let's say you want to drop a table. Now, dropping a table is also similar. You just have to use the command drop table, and then you mention the table's name, so that it is students info. Right? So I'll just mention students info. Right? And then what I'll do is I'll just execute. Once I execute and then if I refresh, you'll see that you know a table is gone. So let's just wait for it to happen. If I go to the table section, you see that there is no table present. So that's how basically you can create a table and drop a table. Now, similarly, you can also drop a database also. So to drop a database, what you have to simply do is you just mentioned drop database, and then you mentioned the database name which was students. So I'll just execute, and then once I execute, you see an error that you know we cannot drop the database because it's in current use. Right? So what you can do is you can just create another database, let's say students one, and then we use students one, and then you can go back and drop this database of students. Right? So once you drop this database of students, you'll see that a new database has been created, that is students one, and the students database has gone. Right? So let's just wait for that to happen. Right? So as you can see, we just have one database, that is students one. Right? So that's how, guys, basically you can drop and create the databases and the tables. Now, the next command that you need to know in the DDL commands is the alter command. But before we start with the alter command, what I'll just do is I'll just use this particular database, and then I'll just create back this table again. Right? And then what I'll do is I'll just write the alter command. So for example, let's say you want to add a column of blood. Right? So what you'll do is you'll just mention alter table, then you'll mention the table's name, that the students info, and then you'll mention add blood group. So that is basically a column name that we want to add, and then we'll mention varchar of 8000. Right? And then I'll click on execute. Once I click on execute and go to tables, and then once we go to this particular table and go to columns on the left-hand side, you clearly see that our blood group column has been added. Similarly, you can drop the same column also. So what you'll do is you'll just copy-paste this. Right? And then what you'll do is you'll just change the add function to drop function. Right? So you'll mention alter table, and then you'll mention the table's name, and then you'll mention drop, and then you'll mention blood group. Right? So if I just execute this, oh, I'm sorry, I have to remove this particular data type also because we're not creating the column. Right? So I'll just execute this particular statement again. All right, it says blood group is not a constraint. Now, this is one of the most common errors, as you know, people

Just remove the command and then try to remove that column. But what you have to do is you have to mention that it's a column; right? So, for that you'll mention all the table, table name, and then you'll mention drop column, and then the column name. After that, you'll click on execute. And then once you click on execute and refresh, you see that our blood group column has gone. So that's how, basically guys, you can add a column or you can delete a column.

Now, for example, let's say you want to add a column and then you want to change the data type also, right? So you want to do both: you want to add a column and then you want to change the data type also. So what you'll do is you'll just mention all the table; we'll just copy paste this particular statement, and then we'll mention all the table students info, that is basically a table name. And then let's say we want to add a date of birth column, right? So I'll just mention dob over here, right? And let's say our data type to be date, right? And then I'll just execute. Once I execute, you see that, you know, our column will be added. Now what I'll do is I want to change the data type, right? So to change the data type, what you do is we copy paste the statement again, and then I'll just remove this particular part and I'll mention all the column, and then I'll mention column name, so that was date of birth, and then I'll mention the new data type, right? So let's say I want it to be date time, right? So I'll just mention date time and close.

Right. So that's how basically you could play around with DDL commands, guys. It's very easy and it's very interesting to learn with. So guys, that was about the alt command. Now let's say, you know, you want to truncate a table. So when I say truncate the table, what I mean by that is that, you know, you want to delete the information present in the table, but the table itself is not deleted. But before that, let's just include some information into the table. So to include information, you have to mention insert into, and then you'll mention table's name, right? So that's students info, right? And then you'll mention values, and then let's say I mention few values, right? So I'll just mention. So I'll just execute this particular statement. Oh, it says column name or number of does not match the table definition. We see this error because, you know, I forgot to drop the column of dob. So I'll just drop the column. So to drop the column, I'll just mention Auto Traver drop column, and then I'll mention dob, right? So let me just copy this particular section from here, and then I'll execute the statement. And once I execute the statement, I'll execute the statement again, and then you will see that, you know, our values have been inserted.

Now to truncate the table, what you have to do is you basically have to use the syntax of truncate. So you'll just mention truncate, and then you'll mention the table name. Our table name is students info, so I'll just mention students info, and then I'll click on execute. Once I click on execute, we see that, you know, the commands have completed successfully, right? Initially our columns have few values, but now our columns have no values over there, right? Apart from this, if you want to also rename a table or rename a database, you have to use the command of SP_rename. This is something different from the other databases as generally the rename command or the queries used, but in SQL Server you have to use SP_rename, and then you'll mention students one, that is basically our database name, and then you'll mention students info, and now you'll mention what you want to change it to, right? Let's say we want to change it to info students, right? And then let's just execute. Okay, it says it cannot find, so I'll just remove this particular part and execute. And once I execute, you can see that, you know, our table name has changed. So what I'll do is I'll just refresh this left hand side and I'll go to students one, I'll go to tables over here, and then you can see that, you know, it has changed to info students.

So I hope I'm clear with the DDL commands, guys. Well, these are a few basic commands that you need to know before you start handing and manipulating databases. On that note, let's take a look at the next topic for today's session, that is keys in the database. Now the different types of keys used in the database are the candidate key, the super key, the primary key, the alternate key, and the foreign key.

Now coming to candidate key, candidate key is a set of attributes which can uniquely identify a table. So a table can have more than a single candidate key, and out of the chosen candidate keys, a single key is chosen as a primary key. Coming to super key, this is a set of attributes which can uniquely identify a tuple. So candidate keys, unique keys, and primary keys are super keys, but the vice versa isn't true. Coming to primary keys, the primary keys are used to uniquely identify every tuple. So a table can have only one primary key, and that key will identify every tuple uniquely in the table. Moving on to alternate key, the alternate keys are those candidate keys which are not chosen as the primary key. And finally coming to the foreign key, the foreign key is an attribute that can only take the values present as the values of some other attribute, and that is the foreign key to the attribute to which it refers. So guys, these were the various types of keys in database. So it's completely based on your understanding or how you want to design your database model, that which key should be primary key and which keys together can uniquely identify a table and so on.

Apart from this, we also have few constraints which are very popular in the database. So next in the session, let's take a look at the popular constraints available in the database. So the constraints used in the database are not null, unique, check, default, and index. Let's talk about not null first. The not null constraint ensures that a column cannot have a null value, right? So that is very simple, as the name suggests, it ensures that, you know, a column cannot have any null value. So if you just assign the constraint of not null to any particular column, then automatically you have to mention a value into that particular column to enter that particular tuple into the database. Coming to unique, the unique constraint makes sure that, you know, all the values in the column are different. So basically, when you mention a constraint unique to a specific column, then automatically what happens is that all the values present in the column are unique. So two or more values cannot be the same. Coming to check constraint, this constraint ensures that all the values in a column satisfy a specific condition. So whenever you mention the check constant, you'll mention a condition, and all the values which satisfy the condition can be present in that particular column. Any value which doesn't satisfy the condition cannot be present in that particular column.

Moving on to default, well this constraint consists of a set of default values of a column where no value is specified, right? For example, let's say while entering values in a column you forget to mention a few, but yes, while creating the table or maybe while adding a constraint you add the constraint of default for that particular table, let's say 10. So all the places where you do not mention any value, 10 will be automatically added to that particular place. And finally coming to the last type of constraint, that is index. This constraint is used to create and retrieve data from the database very quickly, right? If you want to create and retrieve data from the database very quickly, then you have to use the index constraints.

So now that I've explained you keys and constraints in database, let me just switch back to my SQL Server Management Studio, and then what I'll do is I'll just execute few commands or queries based on this particular section. So let's get started. So what I'll do is I'll just copy this particular section from over here, right? And then let's say I just add a segment so that it's clear to us, and then I'll copy paste over here. And then let's say we want to use the not null constraint. So for example, let's say we want to make sure that, you know, the student name and the address of the student is definitely present, or maybe when the user is entering values, it's mandate for the user to enter the student name and the address of student, right? So then what we'll do is we'll just mention not null constraint over here, right? And again I'll just mention not null constraint over here, right? And then what I'll do is I'll just create this particular table, right? Now once this table is created, what I'll do is I'll just copy paste this insert statement from over here, I'll paste this, and let's say, you know, I just remove the address part, right? So I'll just remove this particular section and then I'll mention null, and then I'll click on execute. When I click on execute, you can clearly see the error that, you know, cannot insert the value null into the column because, you know, the column does not allow null. That is because we have given the null constraint to the address column, right? So that's how basically you can use the not null on create table.

Now similarly, if you want to use not null on the alter table, what you basically have to do is you just have to mention the alter table statement, and then at the end you have to mention not null. For example, let's say I want to mention alter table students info, right? And then I'll mention, let's say, alter column, and then I'll mention phone number, right? And let's say I mentioned int, sorry, end not null, right? And then I'll just click on execute. And once I click on execute, you can see that here the command has been successful. So whatever happens, you cannot mention the null values in the phone number column. So guys, that's how basically you can use the null constraint on the create and the alter table. Now let's move forward with the next constraint, that was the unique constraint. Also, while working on the unique constraint, let's just check how to add the primary key. So what I'll do is I'll just drop this particular table. So I'll just mention drop table students info, right? I'll just execute, right? And then what I'll do is I'll just copy paste this section, paste it over here. So what I'll do is I'll just mention the unique constraint over here, and then what I'll do is I'll mention primary key, and in brackets I'll mention student ID, right? After that, I'll just click on execute. And once I click on execute, you can see that, you know, the student ID will be unique. So every ID will be unique, and since every ID will be unique, it will uniquely identify every tuple. So that could be the primary key. So that's how basically you can add the unique constraint for a single column.

Now let's say you want to add a unique constraint for multiple columns, right? So similarly, what I'll do is I'll just drop table again. I'll copy paste the section, paste it over here, remove the student ID, and remove unique constraint from over here. And then what I'll do is I'll just mention constraint, right? And then I'll mention the constraint name that I want to give, so it could be UC, let's say students info, and then I'll mention unique, and in the brackets I'll mention student ID, and let's say we want the phone number also to be unique, right? So we'll mention phone number, right? And then what I'll do is I'll just execute again. So once I execute again, you can clearly see that, you know, our table has been created. So if I just refresh on the left hand side, right? And then what I'll do is I'll just go to the constraints part over here, or you can see that, you know, if I go to the column section over here, you can see that our constraints are clearly visible on the left hand side over here. Also, if I go to the key section where you can see that, you know, our students info constraint which I just mentioned over here is clearly present over here. So that's how, guys, basically you can add a unique constraint on multiple columns.

Now similarly, if you want to add a unique constraint on an alter table, it's very simple. You just have to mention alter table, and then what you do is you mention the table's name as we previously did, and then we'll mention add, and we'll mention the constraint that is unique constraint, and over here we'll mention the column on which we want to add the unique constraint, right? So I want to add it on my student ID, so I'll mention student ID, and then I'll just execute, right? So that's how basically you can add a unique constraint on an alter table also. Now similarly, if you want to drop the constraint also, guys, you just have to mention alter table, and then you'll mention students info, and then what you'll do is you'll mention drop, and then you'll mention constraint, and then you'll mention the constraints name, right? For example, let's say I'll mention this particular name, and then I'll just execute the statement. Now if I just refresh this left hand side and let's just open again, so I'll go to tables, I'll go to students info, and then if I'll just refresh, so I'll go to tables, I'll go to students info, and then if I go to Keys, we see that, you know, there's no UC students info constraint present, but then this particular constraint that we had just added before on the alter table statement, that is present. So that's how basically you can add the unique constraint.

Now let's move forward with the next type of constraint, that is the check constraint. Well, the check constraint, as I previously mentioned, is used to add a condition, right? So for example, let's say, you know, you want to add the check constraint while creating the table itself. So to do that, what I'll do is I'll create a table, but before that let me just drop this table again. And now what we'll do is we'll just copy paste this particular section, put it over here, remove this part, and let's say, you know, we want our country to be India. So all the values which could be entered into the table must have the country value to be India, right? So we'll just mention check over here, and then in brackets I'll mention country equal to, I'll mention India, right? And then what I'll do is I'll just execute this particular statement. So after that, let's say if I want to insert a statement, so for that I'll just copy paste this particular section, let's I put it over here, and over here let's say I just mentioned any value like nice Road, right? And let's say we mention over here Germany, right? And I'll just try to execute, and once if I try to execute, you can clearly see the error that, you know, insert statement conflicted with the check constraint. The conflict occurred in the database because, you know, the column country has to be India, right? And then we have mentioned Germany. So now what you can just do is you can just go back, change the country to India, and then you can insert the value. So that's how you can use the check constraint on the create table.

Now let's say you want to use the check constraint on the alter table. Now similar to that of the unique constraint, what you'll do is you'll just mention alter table, and then you'll mention the table's name, and then what you'll do is you'll just mention add check, and in brackets you'll mention country equal to India, and then you'll execute. Now that's how basically you can add the check constraint on the alter table. Similarly, if you want to give the name to the check constraint, well that's not necessary that you always give the name, but yes, if you're handling on an enterprise level and then you're handling a lot of databases, then giving a name must be a priority, right? So to add the name, what you simply do is you'll just use this alter table statement again, right? And then you'll mention the table name, and over here you have to add constraint, right? And then you'll mention the name, so let's say I mentioned the check, let's say constraint name, right? And then what I'll do is I'll mention the check condition, and that is India, right? So if I just execute the statement again, you'll see that it completely works. And if I refresh on the left hand side, go to tables, go to students info, go to constraints, you'll see that, you know, a constraint name has been added up, right? So similarly you can drop a constraint. While dropping a constraint is again same, you have to use alter table students info, and then you just mention drop constraint, and then you can just mention the drop constraint name. So I'll just execute this particular statement again, and you'll see that, you know, a constraint has been dropped. So guys, that was about the drop constraint.

Now let's go forward with the default constraint, where the default constraint, as I previously said, is used to add the default value. So what I'll do is I'll just drop this table again, right? And then what I'll do is I'll just copy paste the section, paste it over here, I'll just remove this particular section, and then let's say our default country value is India, right? So I'll just mention default, sorry, spelling mistake, and then I'll mention India. So basically all the values which will be inserted into the table will have the default value India. So whenever there is no value that you enter, for example, let's say you are entering 10 values, and out of 10, 5 you have entered as Germany and 5 we've not entered any of them, then all those other 5 will go, will get the value as India, right? So I'll just execute this particular statement, and then what you can just do is you can just check with the insert statement. So now similarly, if you want to add the default constraint with the alter table, you just have to again use alter table students info, and then what you'll do is you'll just mention add constraint, and let's say you give the constraint name to be, let's say default, let's say country, right? And then you'll mention the condition that is default, which will be India, and then you'll mention the column name which is country, and then I'll click on execute. All right, it says that, you know, the column is already bound. I'm sorry. So what we'll do is we'll add, let's say City, and we'll just change it to City over here, and let's say we change it to HYD, right? And then I'll execute again. Once I execute, you can see that, you know, it's clearly working. Now to drop the default constraint also, it's very simple. You'll right click over here and just choose delete, and then once you choose delete, you can just choose the object name and click on OK, right? So once you click on OK, you'll automatically see that, you know, your default constraint has been dropped. Now one more way to drop the default constraint is by using the alter table. You just have to mention alter table students info, and then mention drop constraint, and then you'll just execute this particular statement, right? So that's how basically you can drop the constraint, guys.

Now let's move forward with the next constraint, that is the index constraint. So the index constraint, as I said, is used for the fast creation and retrieval of the database. So for that you'll mention create index, and then let's say we mention the index name to be, let's say student name, right? And then I'll mention on which table, that is the students info table, right? And then on which column, so we want student name from the students info table, right? So I'll just create this particular index, right? And then what I'll do is I'll just refresh this particular section, and over here what I can do is I can go and check on my left hand side. Now if you want to delete your index constraint, what you'll do is drop index, and then you'll mention the index name. So I'll just mention index name, and then I'll click on execute. It says that, you know, we must specify the table name and the index name. So I'll just mention the table name also. So I'll just mention table name dot index name, right? And then I click on execute, and then you can see that our index constraint has been dropped. So that's how, guys, basically you can create, alter, and drop your constraints. I hope you've understood what are keys and constraints and how you can manipulate your data based on those keys and constraints, right? Now let's move forward in the session and go to the next SQL.

Command Category: Data Manipulation Language Commands

The data manipulation language (DML) commands are used to manipulate, or retrieve, data in databases based on your requirements. To demonstrate, I will insert values into a table and then manipulate the data. I will show you the USE command, INSERT command, UPDATE command, DELETE command, MERGE command, and SELECT commands, including CUBE, ROLLUP, OFFSET, FETCH, TOP, and PIVOT. Additionally, we will discuss various operators. Let's get started.

The USE command is used to select a database. To use a database, you mention the command `USE` followed by the database name; for example, `USE students1`.

To insert values, use the INSERT statement. As you can see on my screen, it's `INSERT INTO` followed by the table name, `VALUES`, and then the required values.

I will drop this table to remove constraints: `DROP TABLE students_info`. Then, I will recreate the table. I will copy and paste the table creation script from here. After creating the table, I will use the INSERT command. I have already explained the INSERT statement, so I will not repeat it. The INSERT statement inserts values. There are two ways: mentioning column names and then values, or just mentioning the values.

For example: `INSERT INTO students_info (column names) VALUES (specific values)`. Or: `INSERT INTO students_info VALUES (all values)`.

I will select all and execute. After execution, you can see that the table has values. To check if the values are inserted, type `SELECT * FROM students_info` and execute. You will see that all values have been inserted.

Now, let's update some data. For example, for student ID 1, let's change the student name to Ahana and the city to Ahmedabad. The command is:

`UPDATE students_info SET student_name = 'Ahana', City = 'Ahmedabad' WHERE student_ID = 1;`

Execute the statement. You can see that the student name has changed to Ahana and the city to Ahmedabad. That's how you update data.

To delete data, use: `DELETE FROM students_info WHERE student_name = 'Ahana';`

After executing, you see that the student with the name Ahana has been deleted. That's how you insert, update, and delete values.

The MERGE command performs INSERT, UPDATE, and DELETE operations on a table using a source table. When you have two tables (A and B), where A is the target and B is the source, and there are matched rows, merging allows INSERT, UPDATE, and DELETE operations.

The syntax is simple: `MERGE target_table_name USING source_table_name ON merge_condition WHEN MATCHED THEN UPDATE statement WHEN NOT MATCHED BY TARGET THEN INSERT statement WHEN NOT MATCHED BY SOURCE THEN DELETE statement`.

To illustrate, let's create two tables: `sample_source_table` and `sample_target_table`.

I will create these tables, insert values into both, and then merge them using:

`MERGE sample_target_table AS Target USING sample_source_table AS Source ON (Target.student_ID = Source.student_ID)`

`WHEN MATCHED AND (Target.student_name = Source.student_name OR Target.marks = Source.marks) THEN UPDATE SET Target.student_name = Source.student_name, Target.marks = Source.marks`

`WHEN NOT MATCHED BY TARGET THEN INSERT (student_ID, student_name, marks) VALUES (Source.student_ID, Source.student_name, Source.marks)`

`WHEN NOT MATCHED BY SOURCE THEN DELETE;`

I will insert values into both tables, and then execute the MERGE statement. After execution, observe the changes in the `sample_target_table`. The values have changed, reflecting the merge operation. That's how you merge tables.

Now, let's examine the SELECT statement. To select specific columns: `SELECT student_ID, student_name FROM students_info;`

To select all columns: `SELECT * FROM students_info;`

To select the top three records: `SELECT TOP 3 * FROM students_info;`

To select distinct values: `SELECT DISTINCT City FROM students_info;`

The `ORDER BY`, `GROUP BY`, and `HAVING` clauses can also be used with the SELECT statement.

For example, to sort by parent name: `SELECT * FROM students_info ORDER BY parent_name;` Add `DESC` for descending order. You can sort by multiple columns, specifying ascending (ASC) or descending (DESC) for each.

The SELECT statement is popular for data manipulation because it's easy to retrieve data in the desired format.

To count students from each city: `SELECT COUNT(student_ID), City FROM students_info GROUP BY City;`

Grouping sets were introduced in SQL Server 2008. The syntax is: `SELECT column_names FROM table_name GROUP BY GROUPING SETS ( (column_names), (column_names), etc. );`

The HAVING clause is used when the WHERE keyword cannot be used. For example:

`SELECT COUNT(student_ID), City FROM students_info GROUP BY City HAVING COUNT(student_ID) = 1 ORDER BY COUNT(student_ID) DESC;`

To create a backup: `SELECT * INTO students_backup FROM students_info;`

You can also select specific columns into a new table and add conditions: `SELECT * INTO Pune_students FROM students_info WHERE City = 'Pune';`

The CUBE command is an extension of the GROUP BY clause. It generates subtotals for all combinations of grouping columns: `SELECT student_ID, COUNT(*), City FROM students_info GROUP BY CUBE (student_ID, City) ORDER BY student_ID;`

The ROLLUP command is similar, also extending the GROUP BY clause and including subtotals.

The super aggregated rows, along with the grand total row, are similar to that of the cube clause. I'll just mention for the roll up clause: so I'll mention "select student ID, account, City from students info Group by" and then over here I'll mention "roll up", and then I'll just remove this order by statement. So you can just click on execute, and then you'll see that, you know, the null equal to four will come at the bottom of the table. So when you executed the cube statement, what you observed was that, you know, the super aggregated value that was basically the subtotal came in the first row, but when you execute the role of statement, you see that, you know, it comes in the last row. So that was about the cube and the roll up, guys.

Now moving on to the next DML command, that is the offset clause. The offset clause is used with the select and order by statement to retrieve a range of records. It must be used with the order by clause since it cannot be used on its own. Also, the range that you mentioned must be equal to or greater than zero. So if you mention a negative value, then it shows an error.

To demonstrate this, let's just create a table. So I'll just mention "create table", let's say "offset marks", and then I'll mention "marks" end. So that will be our table column. And then what I'll do is I'll just insert values into this. So I'll just mention "insert into", and let's say I'll mention "offset marks", and let's say I mentioned a few random values. So initially I'll just execute this particular statement, and after that what I'll do is I'll just execute the statement. Before that, I forgot to mention "values" over here. So I'll mention "values" and execute this, and similarly I'll execute the other statements. So let me just copy paste and I'll just change the values over here and I'll execute again. Now after that, what I'll do is I'll use the offset statement. So I'll just mention "select * from", I'll mention the table name that is "offset marks", "order by Max", and then we want to mention "offset one row". So that means our first value, which had 61, so when we use this "order by Max", we see the table values to be sorted on 61, 62, 64, 65, and 65. And after that, when we say "offset 1 marks", the first tuple will be deleted. So that is the reason we get only 62, 64, 65, and 65. So that's how we can use the offset statement, guys.

Now let's move forward with the next one, that is the fetch statement. Well, the fetch clause is used to return a set number of rows. So it has to be used in conjunction with the offset clause. So to do that, what we'll do is we'll just mention "select * from offset marks", and then we'll mention "order by", let's say "marks", and then what we'll do is we'll mention, let's say, "offset three rows", and then "fetch next two rows only". So we'll just fetch the next two rows after leaving the first three rows. So if I just execute this particular statement, we get the two rows, that is 65 and 65. Now similarly, you can also select the top three records from a table by using the top keyword as I had mentioned previously also. So if we just mention "select top three * from offset marks", you'll get the top three tuples from the table. So guys, that was about the offset clause and the top clause.

Now let's move forward with the next one, that is the pivot. Well, the pivot is used to rotate the rows to column values and run aggregations when required on the remaining column values. Now the syntax of pivot is also very simple, guys. You just mention "select non-pivoted column name", and then you've mentioned "first pivoted column name as a column name", and then so on till the last pivoted column name as a column name, "from", and then you mention a select query which produces the data as a pivot, and then in the pivot section you mentioned the aggregation function for the column name. So what I'll do is to give you a detailed understanding; I'll consider an example. So I'll just create a supplier table which has a supplier ID, the days of manufacture, the cost, the customer ID, and the purchase ID. Our supplier ID should not be null. And then what I'll do is I'll just insert a few values into it. So let me just execute this statement first. After that, I'll just go back and then copy paste this section, and then what I'll do is I'll just insert. After the values have been inserted into the table, now what I'll do is I'll just select the customer ID, the average cost as the average cost of the customer from the supplied table, and then I'll group it with the customer ID. So for that, I'll just type in the command "select customer ID, average of cost as", and then I'll mention, let's say, "average cost of customer from supplier table Group by", let's say, "customer ID". And then I'll just execute the statement. So once I execute the statement, you see that, you know, we have the customer ID 11, and then the average cost of all the customers with the customer ID 11 is 1676. Similarly, all the customers with the customer ID 22 have the average cost of customer as 4654, and similarly for the third one, that is 33, we have 5238. Now what we're going to do is we're going to create a SQL pivot table with one row and three columns. So over here, if you observe, we had three rows. Now what we'll do is we'll just create the pivot table with one row and three columns. So for that, we'll just type in the command "select", let's say, "average cost of customer as", let's say we just change it to "cost according to customers", and then we mentioned 11, 22, and 33, and then we mentioned "from", and in the inner section we mentioned "select customer ID", and then we mentioned "cost from supplier table as", let's say, "so stable", and then what we'll mention is we'll mention "pivot", and in brackets when mentioned "average cost for customer ID", and in brackets we'll mention "11, 22, 33 as pivot table". So I'll just mention "pivot table", and then I'll just close. So I've just mentioned "select average cost of customer as customer according to the customers 11, 22, 33". So we have one row and three columns. We want to select "customer ID and cost from the supply table are so stable", and then continue. And so I'll just execute. So once I execute, you can see that, you know, the average cost of customers has been named as "customer according to the customers", and we have 11, 22, 33. So where if I just drag, you can see that, you know, the average has been put over here. So basically, in our previous table which were rows have now become the columns. So that's how, guys, you can create a SQL pivot table.

Now similarly, you can unpivot it all. So for example, let's say I create a table "sample table", and in that I mentioned "supplier ID", let's say "int", "AAA of n type", let's say "BBB of n type", and "CCC of n type". And then I just type on go, and then I mentioned "insert into", let's say, "sample table", and then I mentioned "values". In brackets I'll just mention, let's say, "1, 3, 5, 6". Similarly, I'll just mention the other values also. So let me just copy paste all right, and then I'll click on go. So I'll just execute the statement. And now what I'll do is I'll just show you the value. So I'll just mention "select * from sample table". And I'll just execute this. Once I execute this, so you can see that, you know, we have three rows and four columns. So we have the supplier ID, and then we have AAA, BBB, and CCC. Now what we'll do is we'll unpivot it. So to unpivot it, what you have to do is you have to mention "select", that says "supplier ID", that is basically our column names, and then we'll mention "customers", and let's say "products from", and brackets again I'll mention "select supplier ID", and then I'll mention "AAA, BBB, and CCC", and I'll mention "from sample table". So I'll just give a space, give "sample table", and then I'll mention "unpivot", and over here I'll mention "products for customers in", and in brackets again I'll just mention the values, that is "AAA, BBB, and CCC as", let's say, "example", and then I'll just put on go, and then I'll click on execute. Once I click on execute, you can see that, you know, what we had as four columns in three rows has now been converted. So for every customer, that is AAA, the products show three, the values that we have entered previously are shown. For example, let's say A which had value 398 are now put into three different rows. Similarly goes for BBB and CCC. So that's how you can unpivot the table also, guys. Well, that was about a little bit section of the DML commands. Now if you want to know in depth about SQL pivot and unpivot, I'll leave a blog link in the description box below, and you can refer to that.

Well, guys, that was about this part of the section. Now let's move forward with the next part of the session, that is operators. Now I would say operators is a very important part of the session because operators play a very important role to handle and manipulate data, I would say different ways to retrieve the data. So the different operators present in the SQL Server are the arithmetic operators, the assignment operators, the bitwise operators, the comparison operators, the compound operators, the logical, the scope resolution operators, the set operators, the string concat, and the aggregate functions.

So talking about the arithmetic operators first, well, the arithmetic operators have the addition, subtraction, multiplication, division, and the moduli sign. So you can just add, subtract, multiply, divide, or find the remainder. Coming to assignment, the assignment operators are used to assign a value to the variable. Coming to the bitwise operators, the bitwise operators are used to perform the bitwise and, or, an exclusive or operations. Moving on to the next operators, that is the comparison operators. Well, the comparison operators are the relational operators which are used to perform comparison operations like greater than, less than, equal to, greater than equal to, not equal to, less than equal to, and so on. Moving on to the compound operators, well, the compound operators are used to perform the compound operations of addition, subtraction, multiplication, division, moduli, and function or function on the sort function. Coming to logical operators, where the logical operators are used to perform logical operations between the data. So these are generally used in the nested queries. So the different kinds of logical operators are as you can see on my screen, like all, and, any, between, exists, in, like, not, R, and sum. I'm not going to go into the depth of each one of them because, you know, it's completely based on your understanding of how which operator will benefit you better, but I would say the more you practice, the more you will have an understanding about the different operators.

Moving on to the next type of operator, that is the scope resolution operator. Well, this operator is used to define the scope. And after the scope resolution operators, we have the set operators. So in the set operators, we have the union operator, the intersect operator, and the minus operator. So the union operator is used to combine the rows from both the query. So when you have a left query and right query, and you perform union operator, and then you apply the unit operator later, then automatically you will see that, you know, it will combine rows from both the queries. Coming on to the intersect operator, while the intersect operator is used to keep the rows which are common in both the queries. So for example, there could be few common queries in both the left query and the right query, then when you apply the intersect operator, only those queries will be taken into account. And finally, coming to the minus operator, the minus or the except operator is used to keep the rows from the left query which are not present in the right query, and the vice versa. So when you have two queries or the two tables, let's say left query and the right query, when you say A minus B, it keeps all the rows from the left query which are not present in the right query, and if you say B minus A, then it keeps all the rows from the right query which are not present in the left query.

Now coming to string concat operators, well, the string concat operators are used to perform various actions on the string, like, you know, string concatenation, then wildcard characters to be matched to wildcard characters which match just a single value or maybe multiple values, and so on. And finally, coming to aggregate functions, as I previously spoke about in the session, aggregate functions are used to find the sum, average, count, min, max, first, and last values. So all of these operators are very simple to use, guys. For your better understanding, let me give you a few examples, but I would say the more you practice, the more will you benefit. For example, let's say you want to use the arithmetic operator additions, you can just mention "select 40 plus", let's say, "60", and then you can just execute. Once you execute, you see the output as 100. Similarly, for example, let's say you want to use the comparison operators, let's say greater than equal to. So for that, you'll mention "select * from", let's say we choose the table "offset marks", "where marks is greater than or equal to", and then you mention, let's say, "62". And after that, you'll just execute. So you can see that, you know, you will get all those tuples which have marks which are greater than or equal to 62. Now similarly, you can also use the compound operators also. For example, let's say let's just declare two variables. So I'll just declare, let's say, "@bar one of n type", let's say, "to be of 30". And then what I'll do is I'll just set it to be divided by, let's say, "16". So for that, I'll just use this compound operator and then equal it to 16. And then I'll mention "select @where one as example". And then what I'll do is I'll just execute. Oh, it says that we must declare it first. I'll just declare it first, and then what I'll do is I'll just mention "where one". I'll just set as 16. I'll just execute it again, and when I execute it again, you see the example as one. That is because, you know, when we divide 16 by 30, our quotient is one. So similarly, if you use the moduli symbol over here, then you'll see the remainder. So I'll just execute it again, and then you see that remainder to be 14. So that's how you can use the compound operators.

Now let's say if you want to use the logical operators. For example, let's say if you want to find out the marks between 62 and 65, what you'll do is you'll just mention "select * from", and then you'll mention "offset marks where", and then you'll mention "marks", which is a column name, and then you'll mention "between", and then you'll mention "62 and", which is again a logical operator, and you'll mention "65". Right, okay, my bad, this has to be "select", and then I click on execute. So if we get all the marks between 62 and 65. Now for example, let's say we want to find out those marks which are greater than 62 or marks which are equal to 67. So what we'll do is we'll just change this statement. So "select * from offset where marks", and then we'll use the comparison operators are "greater than 62 and or", I would say, "or Max equal to", what did I say it was? 67, and then I'll execute again, and then you see that, you know, marks greater than 62 are just 64, 65. So we get that, and since there are no marks which are equal to 67, we do not get that.

Now let's move forward with the next one, that is the like operator. So the like operator is one of the most popular questions asked in your interviews. Now this is since people often get confused between how to use the like operators. So for that, I'll just show you a few examples. So let's say, you know, we want to find out all those students' names start with, let's say, "s". We'll just mention "Select Staff from", and then we'll use "students info", where I'll mention "student name like", and then what I'll do is I'll mention "s", and then I'll mention the percentage symbol. So when I execute, we see that, you know, only one student with the name Shania, because her name starts with "s", is in the result set. Well, that was about this query, guys. Now for example, let's say, you know, you want to find out the student name whose name starts with "m" and the name has six letters. So what I'll do is I'll just mention "select * from student name like", and then I'll mention "M", and then I'll mention "five underscores", and then mention a percentage symbol. And then I'll click on execute. When I click on execute, we again see only one query because Mansas' name starts with "m" and has around six letters including "M" itself. So the five underscores were for the rest five letters, and "M" was the starting letter, and percentage symbol represents anything can be there after that. So that was about this particular query. Now let's say we want to find out all those tuples whose student name starts with "m" and then ends with "a". So I'll just change this particular query only. I'll just remove the underscore and then put a percentage symbol and mention "a". What I mean by this particular statement is basically that, you know, the student name should start with "m", should end with "a", and any number of letters can be present in between. Well, that was about this particular query, guys.

Now let's say you want to use the scope resolution operator to access the get root member of the hierarchy ID type. Well, to do that, what I'll do is I'll just declare a variable. So let's just declare "@example ID of hierarchy ID type", and then what I'll do is I'll select this particular ID. So I'll just mention "select @example ID equal to hierarchy ID", and then I'll mention the scope resolution operator, and then I'll mention "get root". After that, I'll just print "@example ID", that is basically a variable to string. So basically, I'm just converting it to string. And then what I'll do is I'll just execute this particular set of statements, and then once I execute the set of statements, you see this output. So that's how you can use the scope resolution operator also, guys. Well, that was about this particular operator.

Now let's say you want to use the string concatenation operators. Well, to use the string concatenation operator, let me just consider the example of "Select", let's say we take "student name". So I'll just mention "student name", and then I'll put a plus mark over here, that is I'm using the string concatenation operator, and then what I'll do is I'll just use single quotes. I'll put comma, and then I'll put a plus sign again, and then choose "parent name". And then I'll just use the analysis function, that is I'm combining these two columns and putting it as another column, and let's say I just mentioned it to be "name from students info". And then I execute. So as you can see the output, you can clearly see that, you know, we've got a "name" column which has this concatenated values of the student name and the parent name. So if you want to give a space, then you have to mention spaces over here, and then you click on execute again, and then you can clearly see that, you know, the space is visible. So that's how you can use the string concatenation operators, guys.

Now let's say you want to move forward with the aggregate functions, where aggregate functions were used before also when we were doing the order by in the group by clauses. For your right understanding, let's say if you want to just calculate the average of all the marks, you'll just mention "select", and then you'll choose "average marks". So that's basically a column name, and then you'll mention the table name, that is "offset marks", and then you click on execute. So once you click on execute, we get our average of all the marks present. So that's how you can use the aggregate functions also, guys. Now let's move forward with the set operators. Well, as I explained before, the set operators consist of Union, intersect.

And the accept operations. So what I'll do is I'll just consider another table, which is similar to that of our student table. So I'll just create one more table. So let me just scroll up right, and I'll just copy this particular section, come down, paste it over here, change it to, let's say, students details, right, and then I'll also insert few values, right. So let me just copy paste from over here so that it's faster. So I'll just execute this particular statement now. And now once our table has been created, I'll just execute these three statements again. And now there are two tables: students info and students details, and both of them have few values. Now let's just perform the union operation, the intersect operation, and the accept operation.

So I'll just mention select star from students info, and then I'll mention Union, and let's say we mentioned Select Star from the table 2, that is students details, right. So I'll just search for students details, right, and let's just execute. Now once we execute, you can clearly see that, you know, all our table values have been inserted. So we had few values in at first table and a few values in our second tables; all the values got combined into our third table, right. Now similarly, if we just do the intersect option, so I'll just mention intersect, and then we can see the common values in both the tables. So I'll just mention intersect and execute, and we can see that, you know, the fourth and the fifth record are common in both the tables. When I type in students info except students details, all the tuples which are present in students info and not present in student details are given as output. And similarly, if I just do the reverse, right, so if I just change it to students details except students info, so let me just do that, and then I'll just do it to info over here, you'll see the opposite output, right. So that's how basically, guys, you can use the set operators.

I hope that you've understood how to use the different kinds of operators to manipulate and retrieve and handle your databases. Now let's move forward with the next part of the session, that is nested queries. Now nested queries are also one of the most popular concepts that you need to know because, you know, nested queries are SQL queries which have an outer query and an inner subquery. So the subquery is a query nested within another query, such as the select, insert, update, and the delete statements. So this was about the nested query, guys. So as you can see on my screen, we have an outer query, and then we can have a subquery. So what will happen is that, you know, the first the subquery or the inner query will be executed, and whatever output comes, that output will be the input to the outer query, and then we get the final output. That was about the nested queries, guys.

So for your better understanding, if I have to give you an example, we can just write a query like, you know, select student name and let's say parent name from, we mentioned students info, right, and then I'll mention where address of student in, and then we can have an inner query which says select address of student from students backup that we had initially created where, let's say, country is equal to India, right. And now we can just execute this particular query, and then we get the output. So that's how you can type the nested queries, guys. Now let's move forward with the next part for today's session, that is joins. Now joins in SQL are commands which are used to combine rows from two or more tables based on a related column between those tables. So they are predominantly used when a user is trying to extract data from the tables which have one-to-many or many-to-many relationships between them. Now there are mainly four types of joins that you have to understand, guys, that is the inner join, the left join, the right join, and the full join.

Now the inner join returns the records which have matching values in both the tables. The left join returns the records from the left table and also those records would satisfy the condition from the right table. The right join returns the request from the right table and also those records would satisfy the condition from the left table. And finally, coming to the full join, the full join returns the records which either have a match in the left or the right table. So for your better understanding, what I'll do is I'll just consider an example. So apart from the students info table, let's just consider the subjects table, right. So for that, I'll just create the subjects table. So let me just type in create table subjects, and let's say we have subject ID of n type, right, and let's say we have student ID of in type, then we have subject name of let's say varchar type, and after that let me just insert few values. So I'll just mention insert into subjects values 10, 10, maths, and 211, physics, and 312, chemistry. So I'll just execute these statements.

Now once the statements are executed, let's apply the join functions. So let's say we want to apply the inner join, right. So we'll just mention select subjects.subject ID, and let's say students info. and we want the student name, right, from both these tables, from we want from subjects table that is at table a, and then we'll mention inner join, that is a join condition, and then we'll mention the second table name that is students info, and we'll mention on, and after that we'll mention the condition that the subjects.student ID must match students info.student ID, right, and then we'll just execute this particular statement. And once you execute the statement, we see that, you know, there are no common values present, so that is the reason we do not get any values. Well, guys, that was about the inner join. Now let's say we want to apply for the left join, right. So what I'll do is I'll just select students info.student name, and let's say we also select the subject ID from the subjects table, and let's say our first table is students info, right, so that is what we are considering over here, and over here I'll mention left join, and after that what I'll do is I'll mention the other table name that the subjects, and then I'll mention on, and then what I'll do is I'll just match the students info.student ID equal to subject.subject ID, and then let's say we order it by the student name, right. So I'll just mention students info, let's say student name, right. Now I'll just execute this particular statement, and then we can see that, you know, we get all the values from the left table, that is the students info table, and then also those records which match the condition from the right table. Similarly, if I apply the right join over here, you'll see all the records from the right table and also those records which satisfy the condition from the left table. Now finally, let's apply the final type of joins, that is the full outer join, and then let me just execute, and once I execute, we see that, you know, we get all those records which have either a match in the left table or the right table. So guys, this was in short about the different types of joins in SQL. Now if you want to learn in depth more about the SQL joins, you can refer to my session on SQL joins. With that, guys, we come to an end to the joins part of this particular session.

Now let's move forward to the stored procedures. I am sure that you know you might have an understanding of what stored procedures are. Stored procedures are those reusable units that can encapsulate a specific business logic of the application. So it is a group of SQL statements and logic compiled and stored together to perform a specific task. The syntax of stored procedures is as you can see on my screen, right. So you just have to mention create or replace procedure, and then you mention the procedure name, and after that you'll mention the parameters name, and then you'll use the aliases is or as, and then you say begin, right, and when you say begin, you declare the section, and then finally you end the procedure. So to demonstrate this, let me just create a procedure for you. So let's say we create procedure, let's say students City, right, and then we choose the parameter name to be @sat, and let's say to be of varchar type 8000, right, and after that we choose as, and then we select from students info, and then we can mention where City equal to @, and then we mention it to either it as @sCity, then we create go, and after that we mention select star from students info again. Now once it is created, what you can do is you can just execute the statement simultaneously also. So for that you'll just use in the command execute, right. So execute students city, right, and then you'll mention @sCity because that is the type of the variable that you've created, and let's say to be of Hyderabad, right, and then you'll click on execute. So once you click on execute, you can see that, you know, you select all the students from the students info, and you see that, you know, there's no student from Hyderabad. For example, if you mentioned Kolkata over here, right, so I'll just mention Kolkata, right, and then if I execute it again, you can see that, you know, we get an error that, you know, there's already an object named student City. So I'll just execute this particular section, and we see that we get only those tuples whose city has Kolkata value. So that's how, guys, you can use stored procedures. You just write the code once, and then you can keep using it again and again like any other programming languages. So guys, that was about the stored procedures, and with this we come to an end to the DML commands.

Now let's move forward with the next section of commands, that is the DCL commands. So as I mentioned before, the TCL commands are used to grant or revoke privileges to a user. So for example, let's say you want to create a user. So to create a user, what you can do is you can just mention create login sample with, we mentioned the password to be edureka. This will basically create a user. So I'll just execute the statement. Okay, it says that, you know, the sample user already exists. So I'll just mention it to be sample1, right, and then I'll click on execute, and once I click on execute, you can see that, you know, my user who's with the name sample1 and password edureka has been created. Now what you can do is you can just use this user to perform various actions rather than only using the admin login. So this is how you can create a login sample1 with the password edureka. Now to create a user, what you'll mention is you'll mention create, and then you'll mention user edureka, right, and for login, and then you'll mention sample1. So to create a user, what you initially have to do is you have to create a login for that particular user, and then you go forward and create a user, right. So I've created a login, and then I'll just create this user. So I'll execute this, and now this particular user can be used rather than just using the admin login credentials. Now what you can do is now you can grant and revoke any kind of privileges to a specific user. Now for example, let's say you want to grant few privileges for this user edureka, right. So for that you'll type in grant select on, and then you'll mention the table name, let's say students info, right, and then what I'll do is I'll mention to, and then I'll mention the username that is @edureka. So I'm just granting this privileges to this particular user. Now similarly, I can also revoke back the granted privileges. So I'll just go back and choose revoke. So I'll just mention revoke over here, and then I can just go back and execute, right. So once I execute, you can see that, you know, no privileges are there. Also, if you want to check, you can go to security, you can go to users over here on the left-hand side, and then you can choose edureka, and then once you choose edureka, once you double click on that particular user, you can see all kinds of permissions granted to this particular user. So since none are granted, you can't see anything presently, but yes, if you grant some, then you can definitely see over here. So guys, that was about the DCL commands.

Now let's move forward with the next section for today's session, that is the TCL commands or the transaction control language commands. Well, these commands are used to handle the transactions in your database. To demonstrate this, what I'll do is I'll just create the table. So I'll just create a table and insert few values. So let me just copy paste the same. I've just created a table as TCL sample with the student ID, student name, and marks columns, and then these are the values which will be inserted, right. So I'll just click on execute. Now once these values are inserted, now let's just start our transaction, right. So to start a transaction, what I'll do is I'll just mention begin try, so that's a try-catch block which I'll come to later in the session, so don't worry. After that, I'll mention begin transaction, right, and then I'll mention insert into TCL sample, that's a table name, and then I'll mention values, and let's say we mentioned few values, let's say 5, and then I mentioned the name, and let's say we've mentioned other values, right. So I'll just mention 56. This need not be in code, so I'll just remove that, right. And after that, what I'll do is I'll just mention update TCL sample, that's a table name, and then I mention set student name equal to, let's say we mentioned the student name to be Akash where our student ID is 5. Also, we want to update our TCL sample table again and set our marks equal to 67 where our student ID is 5, right. After that, we want to commit this transaction and then print that transaction completed, right. So I'll just print a print on the screen, and then I'll end my try block, right, and begin my catch block now, and over here I'll mention rollback transaction, and over here I'll mention again print transaction unsuccessful and rolled back. After that, I'll end my catch block. So if you observe over here, what I've done is I've just started my try-catch block, and then I've begun my transaction. After that, I've inserted a value into the table. Now after that, I want the value to be updated, right. So I want to set the student name to be Akash with the student ID is 5, and this marks to be 67 with the student ID is 5. After that, I want to commit the transaction and print transaction completed, and then only if there is no error the try block will end, but if there is any error found or any exception found, then the catch block will be executed where it will print transaction unsuccessful and rolled back. So what I'll do is I'll just execute the statement. Okay, I'm sorry, I missed a comma over here, right, and now let me just re-execute the statement again, and once I execute this statement, you see an output that, you know, transaction completed, that means that, you know, we have inserted this value into the table, and then we have also updated the values, right. So I'll just show you that. So let me just type in select star from TCL sample, right. So when I execute, you can see that, you know, we have our fifth student with the name Akash and the marks to be 67. Now let's say, you know, you set the marks to 67 by 0, and then let's just execute the section again. Now once I execute the section again, you clearly see an output that, you know, transaction unsuccessful and rolled back, that is because, you know, we cannot set up marks as 67 by 0 as we have given that, you know, marks column is an INT column, and then an INT column cannot have this particular kind of values. So that's how, guys, the transaction control language commands works, right. With this, we come to an end to the different SQL command categories that you need to understand about.

Now let's move forward with the final topic for today's session, that is exception handling. Well, exception handling in SQL Server is almost similar to that of the other programming languages. It's the same as you handle exceptions in all the other programming languages. You have a try block, and then you also have a try-catch block. So talking about the try block first, or I would say the throw clause, this clause is used to raise an exception and transfers the execution to a catch block of the try and catch construct. If you want to see the syntax, the syntax is as you can see on my screen. You mention throw, and then you mention the error number, and then you can mention local variable message, and so on. Coming to the try-catch block, the try-catch block is used to implement exception handling in transact SQL. So a group of statements can be enclosed in a try block. So in case an error occurs in the try block, the control is then passed to another group of statements that are enclosed in the catch block, as we just saw in the transaction control language commands. So the syntax is as you can see on my screen. It starts with begin try, then we mentioned few SQL statements, then we mention end try, then we mention begin catch, and then we again mention few SQL statements, and then we mention end catch. So that's how you can do exception handling, guys. So for your understanding, let me just give you a quick example. So let's say if you want to use the throw clause, you'll mention throw, and then I said you'll mention the error number, right. So let's say I'll mention 51000, and let's say I mention it as record does not exist, right, and then what we can just do is we'll put a comma and then put on one, and then when I execute this particular statement, you can clearly see that, you know, message 51000, and then you can see that, you know, state line is one, and the message is record does not exist, right. So that's how you can use the throw clause. Now similarly, you can use the try and catch block as you saw before. So for that you'll just type in begin try, right, and let's say we select phone number + student name, right. So if you remember our student name was of varchar type and our phone number was of bigint type, right. So we cannot concatenate both of them. So I'll just mention phone number concatenate student name from students info, and then what I want to do is I want to do end try, then I'll begin the catch block, right, and then I'll mention print not possible, right, and let's say I'll just mention end catch, right, and then we can just execute the statement. So when I execute this particular statement, you see that, you know, no column name, but if I go to messages, you can clearly see that, you know, if the message shows not possible, right. So that means a try block did not get executed; only a catch block got executed and shows the exception of not possible, that indicates the user that, you know, we cannot add these two columns. So that's how you can perform exception handling in Microsoft SQL Server, guys.

Let's look at the first question for today's session, that is mention the differences between SQL Server and MySQL. Now this is one of the most popular questions as, as you know, both of them are relational database management systems. So if you have to give the differences between SQL Server and MySQL, then I would say SQL Server is developed by Microsoft, and MySQL was developed by Oracle. SQL Server is a licensed product, so you do not have the free edition for it, and MySQL is an open-source software, right. So if you want to know how to install both of them, I'll leave the links in the description box below, but let me tell you over here that, you know, you can easily install MySQL in very few steps, but when it comes to SQL Server, you have to enable few ports and name pipes, and then you have to follow a proper step to configure the databases. So I would say if you have to compare the installation step between both of them, then I would say installing MySQL is very easy comparative to that of SQL Server. Coming to the next difference, SQL Server supports C#, Java, C++, PHP, Visual Basic, Perl, Python, and Ruby. Coming to MySQL, MySQL also supports various programming languages like, you know, PHP, Perl, Python, Ruby, and so on, right. So both of them offer quite a good amount of support to build various kinds.

Of applications using different technologies, coming to the next difference, I would say SQL Server doesn't allow any kind of database file manipulation while running the database, whereas MySQL allows database file manipulations while running. SQL Server allows query cancellation midway in the process, but this is not the scenario in MySQL, as MySQL does not allow query cancellation midway in the process.

Moving on to the next difference, while backing up the data, SQL Server doesn't block the database, but when it comes to MySQL, it blocks the database. Right, and coming to the next difference, you can say that SQL Server takes a large amount of operation storage space, whereas that's not the scenario in MySQL, as it takes a less amount of operation storage space.

Coming to the last difference, SQL Server is available in the Express and the custom mode, and MySQL is available in the MySQL Community Edition and the Enterprise Edition. So guys, these are a few differences between SQL Server and MySQL. Apart from that, also you can answer the interview by talking about your personal experience while using SQL Server and MySQL. Right, you might have created databases in both of them, and maybe you have manipulated data using both of them. Right, so you can talk about what happens when you want to do a specific set of actions in MySQL and SQL Server. So with this, we come to an end to the first question. Now let's move forward with the second question, that is, what do you understand by SQL Server agent?

Now, SQL Server agent is one of the most popular components of SQL Server. Right, so basically, if you have to explain SQL Server, then you can just say that SQL Server agent is a Windows service which is used to schedule and execute the jobs. So here, each job contains one or more steps, and each step can contain a task. So what happens is that the SQL Server agent uses the SQL Server to store the job information and run a job on a schedule. Now, the main components of SQL Server agent are basically jobs, schedules, operators, and alerts. So if you have to explain with an example over here, you can just consider the example like, if an enterprise wishes to take the backup of the company servers at 9 pm on every Friday. Now what you can do is you can just automate the tasks and let the task happen at the scheduled time. But in a scenario where a backup encounters an error, the SQL Server agent records the events and notifies the corresponding team. So that's how you can use the SQL Server agent, guys. Well, this was one of the simple usages; you can do it in a very complicated way also. So I would just say that SQL Server agent is one of the most important concepts, or you can say the most important component that you need to understand about Microsoft SQL Server.

Moving on in this tutorial on Microsoft SQL Server, let's look at the next question that has mentioned the different authentication modes in SQL Server. Now, before I tell you the different authentication modes in SQL Server, let me tell you that the authentication mode is used for authenticating a user in the SQL Server. So the authentication mode is selected while setting up the database engine, and the different authentication modes offered by SQL Server are basically the Windows authentication mode and the mixed mode. Now, the Windows authentication mode is used to connect the server through a Windows account. So what basically happens over here is that the server takes the computer's username and password for authentication purposes, and also the SQL Server authentication mode is disabled in this mode. Coming to mixed mode, the mixed mode is used to connect with an instance of SQL Server using either the SQL Server authentication or the Windows authentication. So in this mode, basically, there's a username and a password set by the user for the database, and then when you want to log into your SQL Server, you have to mention those username and passwords. So guys, these were two authentication modes, that is, the Windows mode and the mixed mode. Now let's move forward with the next question that is mentioned the differences between local and global temporary tables.

Now, the local tables are basically those tables which only exist for the duration of the connection or the duration of that particular statement which is executing. But when it comes to global temporary tables, the global temporary tables exist permanently in the databases, and only the rows get deleted when the connection gets closed. Right, so over here you have to remember that the structure does not get deleted; only the rows get deleted. So if you have to talk about the syntax between both of them, then I would say the local temporary variable, you can write a syntax as, create table and then put a hash mark and mention the table name. Coming to global temporary tables, the only difference in syntax is that you have to mention two hashes, so you'll mention create table # and then again # and then you'll mention the table name. So guys, these were the differences between local temporary table and global temporary table. Now let's move forward with the next question, that is, how can you check the version of SQL Server?

Now, I would say you could be asked this question just to check whether you have a good hand on the commands or not. So to check the version of SQL Server, you just have to mention the command that you can see on my screen, that is, SELECT @@VERSION. Now this particular command will basically give you the version of the SQL Server that's installed onto your system, and this gives an output as one n wire cache string. Now let's move forward with the next question, that is, what is single user mode and what are the steps you should follow to start SQL Server in a single user mode?

Now, as the name suggests, the single user mode, this particular mode is basically used when you only want a single user to be active on your SQL Server. So single user mode is a mode where only a single user connects to the server. Now you might be wondering when do we use it. Right, now let me tell you that it may often happen that you would want to start an instance of a SQL Server in the single user mode, and you would want to do this either when you want to recover the data from another database system or maybe you want to change the server configurations. So basically, there are two scenarios where you would want to use the single user mode: that is, either you want to recover data from another database system or you would want to change the server configurations. So when you start the SQL Server in single user mode, then any member of the computer's local administrators group gets connected to the instance of SQL Server as the system admin. Now, once you start the SQL Server in a single user mode, what happens is that a single user connects to the server, and the checkpoint process is not executed since it is executed by default at the starter. Also note that you have to stop the SQL Server agent service before connecting to an instance of the SQL Server in the single user mode. Now this is a little bit of an extra information that you can give to an interviewer, but I would say it would be nice if you answer like that. Now to start the SQL Server in single user mode, you basically have to use the command of SQLCMD -M. Right, so you just type in SQLCMD -M, and then you can start the SQL Server in the single user mode. Now to connect through a query editor in the Management Studio, you can just mention -M, and then you can mention the Microsoft SQL Server Management Studio query. That query is completely on your basis, that how you want to connect, but these are the two ways through which you can start the SQL Server in a single user mode. So guys, that was about this question. Now let's move forward with the next question, that is, what is the SQL Server Profiler?

The Microsoft SQL Server Profiler is an interface used to create and manage traces. So basically, what it does is that it analyzes and replays the trace results. So here, the events are saved in a trace file, which are later analyzed or are used to replay a specific series of steps while debugging an issue. Now you can use the SQL Server Profiler for activities as you can see on my screen, like finding the root cause of the problem, monitoring the performance of SQL Server to handle workloads, diagnosing the slow queries, capturing a series of SQL statements causing a problem to further replicate the problem on the test server while debugging the issue, and also correlate the performance counters to debug the issues easily. So guys, this was about SQL Server Profiler. Now let's move forward with the next question, that is, what is a TCP port on which SQL Server runs?

Now, this is one of the most interesting questions that is asked in interviews because you know it's a number that you have to guess exactly, and then your answer cannot be wrong. Right, so well, the answer to this particular question is that the TCP/IP port on which SQL Server runs is 1433. Right, so that's 1433 that you have to keep in your minds. Now let's move forward with the next question, that is, what are some subqueries in SQL Server, and then can you mention a few properties of it?

So if I have to explain to you what a subquery is, a subquery is a query inside another query where a query is defined to retrieve data or information back from the database. So in a subquery, the outer query is called the main query, whereas the inner query is called the subquery. Subqueries are always executed first, and the result of the subquery is passed to the main query. Now subqueries can be nested inside a select statement, update statement, or any other query. A subquery can also use comparison operators like greater than, less than, or equal to. Now if you have to mention a few properties of subqueries, then you can say that it must be enclosed in parentheses as it must be executed first before the main query. More than one query can be included, and a subquery should not have the ORDER BY clause but can definitely include the WHERE, GROUP BY, and HAVING clauses. The subquery must be on the right-hand side of the comparison operator of the main query and must include a SELECT clause and a FROM clause. So guys, these are a few properties of subqueries. Now let's move forward with the next question, that is, how do you start single user mode in cluster installations?

Now, in clustered installations, the SQL Server basically uses the DLL available connections and thus blocks any other connection to the server. Now, in this state, if you try to bring the SQL Server agent resources online, then it may fail the SQL resources to a different node as it could be configured to a group. So to start a single user mode in cluster installations, you have to follow the steps that you can see on my screen. You have to first go to the advanced properties and then remove the -M startup parameter. After that, you have to put the SQL Server resource offline and then issue the command from the command prompt and make sure that you are at the current owner node of the group. So the command is basically NET START MSSQLSERVER /m. After that, you have to verify from the cluster administrator or Failover Cluster Management console that a SQL Server resource is still offline or not, and then you have to connect the SQL Server by using the command SQLCMD -e -s and then do the required operations. Once an operation is complete, you have to close the command prompt and then bring back the SQL Server and other resources online through the cluster administrator. So guys, these are a few steps that you have to follow to start single user mode in cluster installations.

Moving on to the next question, that is, what do you understand by replication in SQL Server and what are the different types of replication that are present in SQL Server?

Now, replication in Microsoft SQL Server is a process to synchronize the data across multiple servers. Now, this is generally done by the replica set, and these sets provide multiple copies of data with redundancy and high availability on different servers. Not only this, but replication also provides a mechanism to recover from the failures, so it basically removes the dependencies from a single server to protect the loss of data from that particular server. Now, the different types of replication available in SQL Server are merge replication, transactional replication, and snapshot replication. Now, the merge replication basically groups the data from various sources to a single centralized database and is used in the server-to-client information. Coming to transactional replication, this particular application is basically a process of distributing data from publisher to subscriber and is used in the server-to-server environments. Moving on to the final replication, that is, snapshot replication, the snapshot replication basically distributes data exactly as it appears at a specific moment and is used for replicating data which changes infrequently. So guys, that was about replication and its types. Now let's move forward with the next question, that is, what are the differences between Microsoft SQL Server and Oracle?

If you have to mention the differences between Microsoft SQL Server and Oracle, then MS SQL Server basically provides simple and easy syntax, whereas Oracle consists of complex and comparatively more efficient syntaxes. The MS SQL Server uses basically the Transact-SQL or the T-SQL, whereas Oracle uses the PL/SQL. Moving on to the next difference, SQL Server does not support query optimization, but Oracle supports query optimization and uses the star query optimization. Moving on to the next difference, in SQL Server, rollbacks are not allowed in the transaction processes, but in Oracle, rollbacks are definitely allowed during the transaction processes. SQL Server allows incremental, partial, and full backups, whereas Oracle allows incremental, full, file-level, and differential backups. SQL Server does not support clustering, whereas Oracle offers support for clustered configurations. In SQL Server, statements such as INSERT, UPDATE, DELETE are executed serially, whereas in Oracle, statements such as INSERT, UPDATE, DELETE, and MERGE are executed parallelly. And finally, coming to the last difference, jobs are scheduled via the SQL Server Agent in SQL Server, whereas jobs are scheduled via the Oracle Scheduler or the OEM in Oracle. So guys, these were a few differences between SQL Server and Oracle. So as I said before, you can also talk about your personal experience while using both of them. Now let's move forward with the next question, that is, what do you understand by intent logs?

Microsoft SQL Server uses a lock hierarchy whenever the data is read or something is changed in the data. So whenever a row is read, the SQL Server acquires a shared lock, and whenever you change a row, the SQL Server acquires an exclusive lock. So these locks are basically incompatible with each other, and this is where the intent logs come into the picture. So the intent logs are basically used to indicate at a higher level which locks are applied within a lock hierarchy. Now there are mainly three kinds of intent locks: that is, the intent shared lock, the intent update lock, and the intent exclusive lock. Now, as the name suggests, the intent shared lock is basically used when you have a shared lock at the row level. Coming to intent update lock, the intent update lock is used when you have an update lock at the row level. And finally, coming to intent exclusive lock, this particular lock is used when you have an exclusive lock at the row level. Now let's move forward with the next question, that is, what are the steps you must follow to hide SQL Server instances?

The steps that you must follow to hide SQL Server instances are, as you can see on my screen, initially you have to open the SQL Server Configuration Manager, and then you have to go to the SQL Server Network Configuration. After that, in the SQL Server Network Configuration, go to Protocols and choose the instance of the SQL Server. Later on, you just have to right-click on the instance and select the Properties. After that, you'll see a dialog box which opens up, so go to the Flags tab in that particular dialog box, and then you see an option of Hide Instance over there. So over there, you just have to go to that particular option of Hide Instance and just say yes and then open the drop-down and choose yes. So once you choose yes, you just have to finally click on OK, and then automatically your instance will be hidden. So guys, these were the steps to hide the instance in SQL Server. Next in this tutorial on SQL Server, let's move forward with the next question, that is, what do you understand by Data Quality Services in SQL Server?

The Data Quality Services in SQL Server is basically a knowledge-driven data quality product. Right, so the SQL Server Data Quality Services enable the user to build a knowledge base and thereafter use it to perform tasks such as correction, deduplication, enrichment, and standardization of data. Apart from this, the Data Quality Services also provide profiling and enable you to perform data cleaning with the help of cloud-based data services. Now, the DQS services, or the Data Quality Services, basically consist of two components: the Data Quality Server and the Data Quality Client. Now talking about the server first, so the Data Quality Server is basically a SQL Server instance feature consisting of three SQL Server catalogs with data quality functionality and storage. Coming to Data Quality Client, it is also a SQL Server feature which users can use to perform computer-assisted data quality analysis and manage the data quality interactively. Right, so guys, that was about the Data Quality Services. Now let's move forward with the next question, that is, explain magic tables in SQL Server.

Now, magic tables are tables which are automatically created in SQL Server and are used to internally store the inserted, updated values for DML operations such as SELECT, DELETE, INSERT, UPDATE, and so on. Right, so basically, guys, magic tables are just automatically created tables inside SQL Server used to basically store values, maybe inserted, updated, or deleted, and you can understand that magic tables are used on a temporary basis. Now let's move forward with the next question, that is, what do you understand by Change Data Capture?

So Change Data Capture, or most commonly known as CDC, is used to record INSERT, UPDATE, DELETE activities applied on the tables. So as the name suggests, the Change Data Capture is used to capture the data that has been changed recently. So the column information and the metadata required to apply the changes to the target information are captured for the modified rows and are eventually stored in the change tables. So these change tables are the mirror images of the original column structure. So guys, that was about Change Data Capture. Now let's move forward with the next question, that is, what do you understand by triggers and mention the different types of it?

So if you have to explain triggers, then triggers are used to execute batches of SQL code whenever INSERT, DELETE, or UPDATE commands are executed against the table. So basically, triggers are automatically executed whenever the data is modified based on the data manipulation operations, or you can just understand that triggers are triggered when there's an event happening. So the different types of triggers are basically INSERT, UPDATE, DELETE, and INSTEAD OF. So guys, that was about triggers. Now let's move forward with the next question, that is, what do you understand by recursive stored procedures?

A recursive stored procedure is basically a problem-solving method through which you can arrive at the solution again and again and again. Right, so in programming also we see recursive functions. Right, so you can just keep calling back the function, and with the help of that, you can keep getting solutions again and again and again. Right, so that's the same in SQL also. Recursive stored procedures is basically a method through which you can arrive at the solution again and again. So that was about recursive stored procedures, guys. Let's move forward with the next question, that is, explain log shipping and its advantages.

Now, log shipping is basically the process of automation of backup to restore databases from one standalone server to another standalone standby server. So you can understand log shipping as one of those disaster recovery solutions as it makes sure that even if one server fails, the standby server will have the same data as that of the server itself. So the advantages of log shipping are, as you can see in my screen, it needs low maintenance and it's easy to set up. The secondary database created is used for read-only purposes only, and you can also create multiple secondary standby servers. Not only this, but it also allows a delay specified by the user for the time between the primary.

Servers backup the log of the primary database. And when the secondary servers restore or apply the log backer. So guys, these were a few advantages of log shipping. Now let's move forward with the next question; that is, what are Trace flags and mention a few common Trace flags that you might have faced.

So the trace flags are basically those flags which are used to alter server behaviors or set server characteristics. Now, few common Trace flags that all of us use or encounter: basically 1204, 1205, 1222. So all three of them I've used for deadlock information. The 174 trace flag is used to increase the SQL Server database engine plan cache bucket count from 40,009 to 1,60,001 on 64-bit systems. Coming to 1118; so 1118 forces uniform extant allocations instead of mixed page allocations.

Moving on to the next one, that is 652. Now 652 is basically used to disable the page prefetching scans, and 2566 is used to basically run the DBCC CHECKDB command without the data purity check unless the data purity option is specified. So guys, these are a few Trace flags that I've encountered or I've used. Now this answer is not something that you know you have to give only these trace flags; there are hundreds of Trace flags present. So whatever you have encountered or maybe whatever you have used, you can mention that.

Right, now let's move forward with the next one; that is, mention the differences between substring and character index in SQL Server. Substring is basically used to return a specific portion of the string in a given string, but whereas the character index is used to return a character position in a given specified string. Right, so for example, if you have substring at edureka, one, comma four, so what the syntax mentioned is that you know edureka is our string, one is a starting value from where the characters have to be extracted, and four is the range still where the characters have to be extracted. So if you count edureka on your fingers, we have seven letters, right? So we've mentioned one to four, so our output should be e d u r. So it starts with e, that's the first letter, then d, second one, u, third one, and r, fourth one. But when it comes to character index, character index as I mentioned before is used to return a character position in the given string. Right, so for example, if you mention an example character index r, comma edureka, comma one; r is basically the character for which we want to find out the position; it requires a string, and one is the starting range of the string. So if you again count edureka on your fingers, then you see r is at the fourth position, so we see output as four. So guys, these were the differences between substring and character index in SQL Server.

Now let's move forward with the next question; that is, what do you understand by Analysis Services in SQL Server? So Analysis Services in Microsoft SQL Server is an analytical data engine used in business analytics and decision support. So the service basically provides enterprise-grade semantic models for client applications and reports such as Power BI, Microsoft Excel, and other visualization tools. So the Analysis Services is basically available in platforms like, you know, Azure Analysis Services, Power BI Premium, and SQL Server Analysis Services. So guys, that was about Analysis Services in SQL Server.

Now let's move forward with the next question; that is, what do you understand by mirroring and mention a few advantages of it? So mirroring in SQL Server is basically designed to maintain a hot standby server that is consistent with the primary server in terms of the transaction. Also, the transaction log records are sent from the principal server to the secondary server. Now the advantages of mirroring are, as you can see on my screen, it consists of an automatic failover mechanism; it is more efficient than log shipping and is more robust; and the primary server is synced with a secondary server in real time. So guys, that was about mirroring.

Now let's move forward with the next question; that is, when do you think a developer should use SQL Server-based cursors? So SQL Server-based cursors are used when you wish to work on a record at an instance of time rather than taking all the data from a table as a bulk. However, cursors are not preferred to be used when large volumes of data is present as it affects the performance. So in a scenario where it is not possible to avoid the cursors, then I would suggest try to reduce the number of records to process by using a temporary table and then eventually build the cursor from this. So I think guys, this is one of the most practical questions that could be asked where the interview checks whether you have practical knowledge of where SQL can be used and how you can use different commands or different functionalities based on the scenarios.

Now let's move forward with the next question; that is, what part of database design do you think affects the performance of a SQL Server-based application? Well, I would say the physical and the logical design plays an important role in the performance of SQL Server-based applications, and we need to ensure that the correct data is captured in the proper table; the data items have proper relationships between them, and the data redundancy is reduced. I would also suggest that you know while you're designing a database, make sure that it is an iterative process to achieve all the required system goals and is then the constant observation to make sure you know all the client requirements are added and the database satisfies the requirement. Now I'm saying this because you know once the database design is set, it's very tough to change the database design according to the requirements that come later on. So you cannot change the basic entities of the databases, but you can only add new relationships and data items. So I would say if something affects the performance of a SQL Server-based application, then I would say the physical and the logical design of the database affects the most.

Now let's move forward with the next question; that is, what do you understand by user-defined functions in SQL Server and then what are the steps to create and execute the user-defined function in a SQL Server? Well, a user-defined function, as the name suggests, is a function written as per the needs of the user by implementing a specific logic. Now in these kinds of functions, the user is not limited to any predefined functions and simplifies the complex code of a predefined function by writing a simple code. Apart from this, let me also tell you that you know the user-defined function returns a scalar value or a table. Now to create a user-defined function, you can refer to the example that you can see on my screen. I've just created a function sample_func, and then in the brackets I've put @customer_num int; so basically it's an integer, and then it returns a table as return select * from customers where customer_id = @customer_num. Right now, right, we're trying to basically return all the customer IDs from our customer table and store it in a table. Now after that, to execute the function that we had just created, you just have to mention the command select * from sample_func, that is basically the function's name, and in brackets you'll mention the customer ID. So for example, I've mentioned 10 over here. So that's how guys, you can create a user-defined function and also execute it.

Now let's move forward with the next question; that is, how can you ensure that the database and SQL Server-based applications perform well? Well, I would say to ensure that the database and the SQL Server-based applications perform well, a developer must check the types of information stored, the volumes of data, and what data will be accessed. So in a scenario where you're upgrading an existing system, you should analyze the present data, the existing data volumes occur, and then check the method through which the data is accessed to help you understand the problem areas for the design. But on the other hand, if you're creating a new system, then you have to keep the information about what data will be captured, what are the constituents of data, and the relationship between the data items. So like that, the developer can make sure that you know the database and SQL Server-based applications can perform well.

Now let's move forward with the next question; that is, what are relationships in databases and what are the different types of it? Well, I would say a relationship in database management system is a scenario where two entities are related to each other. So basically, if you have two tables, table A and table B, then the table consisting of the foreign key references to that of the primary key of the other table. So the different types of relationships in DBMS or database management systems are one-to-one relationship, one-to-many relationship, many-to-many relationship, and self-referencing relationship. Coming to one-to-one relationship, so this is basically used when a single row in table A is related to a single row in table B. Coming to one-to-many relationship, this is used when a single row in table A is related to many rows in table B. Coming to many-to-many relationship, this is used when you have many rows in table A related to many rows in table B. And finally, coming to self-referencing relationship, this is used when a record in table A is related to the same table itself.

Now let's move forward with the next question; that is, what are joins in SQL and what are the different types of joins? A join clause is basically used to combine rows from two or more tables based on a related column between them, and it is used to merge two tables or retrieve data from there. So there are mainly four types of joins in SQL: the inner join, the right join, the left join, and the full join. Right, so I'm now going to go into depth of them. So if you want to know how to use SQL joins, you can refer to my session on SQL joins on that node. Let's move forward with the session and let's look into the next question; that is, what is the command DBCC CHECKDB used for?

So the command DBCC CHECKDB is used to basically check the physical and the logical integrity of all the objects in the mentioned database. So to do that, it basically performs the operations that you can see on my screen. It runs the DBCC CHECKALLOC command on the database and on every table and view in the database; the DBCC CHECKTABLE command is executed. It also runs the DBCC CHECKCATALOG on the database, and then it validates the contents of every index view in the mentioned database. After that, it also validates the link level consistency between file system directories and table metadata while storing via binary max data in the file system using file stream. Finally, it validates the service broker data in the database. So if you observe clearly, you just have to execute the DBCC CHECKDB command, and automatically the DBCC CHECKALLOC, the CHECKTABLE, and the CHECKCATALOG command gets executed. Also note that DBCC is supported on databases that contain memory-optimized tables but does not provide repair operations. So basically, this implies that you must regularly backup databases and test those backups. So guys, that was about the DBCC CHECKDB command.

Now let's move forward with the next question; that is, what do you understand by check constraint in SQL Server? So the check constraint in SQL Server is basically used to limit the values or the type of data stored in a column. Now once you apply the check constraint on a single column, you can go forward and apply specific values for that particular column. See the example on my screen. I've created a table customers with a few columns like customer_id, first_name, age, and city, and then I've applied the check constraint, and then I've given the name to be check_customer, and the condition that I've applied is basically age should be greater than 20 and city should be Hyderabad. So guys, that is basically how you can use the check constraint.

Now let's move forward with the next question; that is, what do you understand by COALESCE in SQL Server? Now the COALESCE function is used to basically return the first non-null expression within the arguments. So the COALESCE command is basically used to return a non-null value from more than a single column in arguments. So to use the COALESCE command, you can refer to the example that you can see on my screen; that is, select coalesce, and then I've mentioned customer_id, customer_name, amount from customers. Right, so basically customers was a table, and customer_id, customer_name, amount are basically column names. Right, so I'm basically trying to return the first non-null expressions from customer_id, customer_name, and amount.

Now let's move forward with the next question; that is, explain the usage of FLOOR function in SQL Server. Now the FLOOR function is used to round up a non-integer value to the previous least integer value. This function returns a unique value after rounding of the digits. Now the syntax is, as you can see on my screen, it's basically FLOOR, and then you mention the expression. And if you also want to know how to use it, you can see the example on my screen. I've just mentioned FLOOR, and then I've mentioned in bracket 7.3, so it will basically round off the value to 7. So guys, that was about the FLOOR function.

Now let's move forward with the next question; that is, what is the command used to check logs in Microsoft SQL Server? So to check logs in a database, you have to use an inbuilt stored procedure, that is sp_log. The syntax is again, as you can see on my screen, it's sp_log, and then you mentioned @dbid = 1 and session_id 1. You can go forward and mention the session_id 2 and so on, right? You can also go forward and explain the command to the interviewer by giving them an example. Right, so for example, if you want to list all the logs currently held in an instance of a database engine, you can use the command sp_log. As you can see on my screen, I've mentioned use sample_database, that is basically my database name, and then I've mentioned go execute sp_log and then go again over there. So that is basically how I want to list all the logs currently held in an instance of the database engine.

Now let's move forward with the next question; that is, mention the three ways to get a count on the number of records in a table. Now the three ways through which you can get a count of the number of records in a table are, as you can see on my screen, you can initially write a query like, you know, select * from table_name. This will basically retrieve all the data from the table, right? So and over there you can clearly get a count of the number of records in the table. The second way is basically you use the count function. Right, so for that you'll write a query like, as you can see on the screen, that is select count(*) from table_name. Right, so you'll basically count all the row values and then you'll mention. And the third one is basically select rows from indexes where id = object_id('table_name') and index_id < 2. Right, so guys, these are the three ways through which you can get a count of the number of records in a table.

Now let's move forward with the next question; that is, what is the usage of the SIGN function? Now the SIGN function is basically used to determine whether the mentioned number is 0, positive, or negative. So it will either return 0, +1, or -1. So the syntax is, as you can see on my screen, is just SIGN, and in brackets you mentioned the number. And if you want to see the example, the example is again on my screen like, you know, if you mention SIGN(0), then it will return 0; if you mention SIGN(21), then it will return 1; and if you mention SIGN(-21), it will return -1. So guys, that was about the SIGN function.

Now let's move forward with the next question; that is, write a SQL query to find the first weekday of the month. Now to find the first weekday of the month, you can write a query like, as you can see on my screen, that is select datename(dw, DATEADD(dd, (datediff(dd,0,getdate())/7)*7, 0)). So that's how you basically get the weekday of the month. Now DATEADD, DATEDIFF, GETDATE are all predefined functions that you can use.

Now let's move forward with the next question; that is, mention the command used to rename the database. Now the command used to rename the database is sp_renamedb. So to know how to use this command, you can look at my screen. You basically have to mention sp_renamedb, and then you have to mention the old database name and then the new database name. So for example, if you have customers initially and then you want to change it to customers_information, you mentioned sp_renamedb customers, and then customers_information. So that's how guys, you can rename the database.

Now let's move forward with the next question; that is, write a query to find the fifth highest amount paid from the customers table. Now to find the fifth highest amount paid from the customers table, you can write a query as you can see on my screen; that is, select top 1 amount from (select distinct top 5 amount from customers order by amount desc) as top5 order by amount. So basically, in a query, we're basically trying to find out the top five distinct amounts paid by the customers in the customer table, and then we'll order it by descending order, and when the output comes to the main query or the outer query, in the outer query it is ordered by the amount, and then it is in the descending order already, so you just pick up the first amount. So guys, that's how you can write a query to find the fifth highest amount paid from the customers table.

Now let's move forward with the next question and understand how can we delete a table in SQL Server. Well, to delete the table in SQL Server, you basically have to use the drop command. So the syntax is, as you can see on my screen, you just mentioned drop table table_name. So for example, if you have to delete the customers table, then you mentioned drop table customers. So guys, that was about how you can delete a table in SQL Server.

Now let's move forward with the next question; that is, what is the purpose of UPDATE STATISTICS and SCOPE_IDENTITY function? The UPDATE STATISTICS function is basically used to update the information used by the indexes such as the distribution of key values for one or more statistics groups as mentioned in the index view or the table. Coming to SCOPE_IDENTITY function, the SCOPE_IDENTITY function is used to create identity values for tables in the current execution scope.

Now let's move forward with the next question; that is, what do you understand by physical_only option in DBCC CHECKDB command? Well, the physical_only option is used to limit the checking to the integrity or physical structure of the record headers, page, and also the allocation consistency of the database. The physical_only check is used to provide a small overhead check of the physical consistency of the database, and this option also causes a shorter runtime for DBCC CHECKDB on large databases. So it's generally recommended for frequent use on production systems.

Now let's move forward with the next question; that is, can you explain how long are the locks retained with repeatable read and serializable isolation levels during a read operation with low-level locking? Well, with repeatable read and serializable isolation levels, the locks are held during the transaction. The answer to this particular question is that you know the locks are held during the transaction, but if you consider the read committed, then the locks are held for the isolation level. So guys, that was about this question.

Now let's move forward with the next question; that is, mention the differences between HAVING and WHERE clause. Well, the HAVING clause is basically used only with the select statement, whereas the WHERE clause is used in a group by clause. The HAVING clause is used with a group by function in a query, whereas the WHERE clause is applied to each row before they are a part of the group by function in a query. Also note that you know whenever a group by function is not used, HAVING behaves like a WHERE clause. Right, so guys, these were the differences.

Between having and where clauses, now let's move forward with the next question. That is, what do you understand by integration services in SQL Server? Well, integration services is a platform offered by Microsoft to build enterprise-level data transformation solutions and integration. Now, this services solve complex versus problems by loading data warehouses, perform data wrangling, copy or download files, and manage SQL Server objects. Also, integration services can extract and transform data from a wide variety of sources such as relational data sources, XML data files, load the data into more than a single database. So basically, you can use the integration services to create solutions without coding or maybe core complex tasks, program the extensive integration object model to create objects. Not only this, but the integration services include a good set of built-in tasks and transformations and graphical tools used for building packages and also contain the catalog database to store, run, and manage packages.

So guys, that was about integration services in SQL Server. Now let's move forward with the next question. That is, what do you understand by hot fixes and patches in SQL Server? So hot fixes are single, cumulative software packages applied to live systems. So basically, this includes one or more files used to address a problem in a software product. The patches are a program installed on the machines to rectify the problem occurred in the system and ensure the security of that particular system. So basically, hot fixes are a kind of patch offered by Microsoft SQL Server to address specific issues.

Now let's move forward with the next question. That is, can you name a few encryption mechanisms in SQL Server? Well, few encryption mechanisms in SQL Server to encrypt the data and database are, as you can see on my screen, that is transparent data encryption, symmetric keys, asymmetric keys, Transact-SQL functions, and certificates. Right, so these are few encryption mechanisms through which you can protect your data; you can encrypt the data in a database.

Now let's move forward with the next question. That is, what are the options which must be set to allow the usage of optimistic models? Well, the options that must be set to allow the usage of optimistic models are the `read_committed_snapshot` option and `allow_snapshot_isolation` option. Right, so basically, these two options are used, that is, the read committed snapshot and the allow snapshot isolation option. So the read committed snapshot option is basically used to read the committed optimistic model, and the allow snapshot isolation is used for the snapshot isolation levels. Right, so guys, these are the two options that you must keep in mind.

Now let's move forward with the final question for this particular session. That is, what are the common performance issues in SQL Server? Now, this is one of the most practical questions I would say that could be asked because you know it's completely on your experience basis on how much you have used the databases and how many issues that you have faced. So the most common performance issues in SQL Server are fragmentation, input/output bottleneck, blocking, queues, deadlocks, and unused indexes. So these are few common performance issues that I had seen. But if you think you've also seen any other issues, you can definitely go forward and mention it. So I would say in this particular question also, please explain with examples on which scenarios did you see the performance issues and how did you resolve it.

So on that note, guys, we come to an end to this particular session. I hope you found this session interesting and informative. So thank you and have a great day. I hope you have enjoyed listening to this video. Please be kind enough to like it, and you can comment any of your doubts and queries, and we will reply them at the earliest. Do look out for more videos in our playlist, and subscribe to edureka channel to learn more. Happy learning.