Trending February 2024 # How Typedef Work In C++ With Examples # Suggested March 2024 # Top 11 Popular

You are reading the article How Typedef Work In C++ With Examples updated in February 2024 on the website Tai-facebook.edu.vn. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 How Typedef Work In C++ With Examples

Introduction to C++ typedef

Web development, programming languages, Software testing & others

Syntax:

In C++ each object, variables and keywords have their own syntax and attributes for declaring in the programming codes. Based on the requirement, we will utilize the special keywords or reserved keywords from the programming library.

datatype main() { typedef old datatype name new datatype name; typedef struct structure name; { datatype initialization; } —coding logics— }

The above codes are the basic syntax for using the typedef keywords in the programming logic. We can use the typedef as the structure using struct keyword type; by using this type, we can create n number of data types declaration as well as change the name in a single process.

How does typedef work in C++?

Generally, the typedef is one of the reserved keywords; it provides the same level of abstractions from the actual data type and changes data types that are being used for programmers to allow it with the more focus on the coding concepts. It also makes it easier to write the programming codes and clean them using some destroy() or any other default methods because garbage collectors are the main area for destroying the unwanted codes and clean it for the memory space areas. Depending on the data types, the sizes must be calculated, and it allocates the memory space for the big storage data type variables and small amount storage variables.

Normally the typedef declarations are used with the two different types like typedef type-declaration and typedef type-definition identifier; these two standard typedef declarations are covered with the new name types alias with the some syntax declarations for the language identifiers, and the other type is covered with the some standard libraries and in other POSIX specifications are included with the typedef definitions, and it is more often in the both prefix and suffix, and it includes the common sizes with more number of time calculations included in the codes. Moreover, a typedef keyword often used with the some documentations while indicating the number of the specific variable via included in the programming contexts that may include in the expressions with a variable number of unit measures with counts.

The keyword also used to simplified the variable declarations for the some compound types like struct, union etc. or even though we included some pointers type in the syntax while we used pointer in the typedef keyword, it creates the specific memory storage in the compiler and as well as the address of the variable also changed in the both old and new data types. We can also use structure pointers in the typedef keyword that contains multiple variables with the same type and to declare with the single level statements even though the pointers are included or not in the structure type. The functional pointers also specified with the typedef the preceding number of coding lines will be rewritten with the typedef keyword it reduces the length and complexity of the programs. The functional declarations will be more cryptic, and it clearly shows with the accepts of arguments or the types, it will return the variables.

Examples of C++ typedef

Given below are the examples of C++ typedef:

Example #1

Code:

using namespace std; typedef struct example { int id; char name[14]; int mobile; }s; class demo { int a; public: demo(int a_i = 1) : a{a_i } { cout << “The conversion is called through this method” << endl; } operator string() { cout << “The casting conversion operation is:” << endl; return to_string(a); } }; int main() { s j, k, l; demo b(4) string s = b; b = 32; j.id = 2; strcpy(j.name,”siva”); j.mobile = 82202; k.id = 4; strcpy(j.name,”raman”); j.mobile = 57464; k.id = 6; strcpy(k.name,”sivaraman”); k.mobile = 198591; cout << “Welcome To My Domain” << endl; cout << “ID1 : ” << chúng tôi << endl; cout << “name1 : ” << chúng tôi << endl; cout << “mobile1 : ” << j.mobile << endl; cout << “ID2 : ” << chúng tôi << endl; cout << “name2 : ” << chúng tôi << endl; cout << “mobile2 : ” << k.mobile << endl; cout << “ID3 : ” << chúng tôi << endl; cout << “name3 : ” << chúng tôi << endl; cout << “mobile3 : ” << l.mobile << endl; return 0; }

Example #2

Code:

int main(){ typedef unsigned int a; a p = 3, q = 5; std::cout << “p = ” << p << std::endl; std::cout << “q = ” << q << std::endl; return 1; }

Output:

Example #3

using namespace std; struct example { char *domain; int id; }; typedef int *pr; int main() { struct example eg; eg.domain = “Welcome To My Domain”; eg.id = 7879; cout << “Have a Nice day user for chhosing the domain: ” << eg.domain << ‘n’; cout << “Your User id is: ” << eg.id; pr pvar; return 0; }

Output:

In the above three examples, we used typedef in the different categories using the pointer concepts and the variables that have addressed the old and new ones.

Conclusion

In typedef is the specific reserved keyword area of the C++. It has a lot of pre-defined keywords used to implement the programming logic in the application. Here we used this keyword to mostly reduce the lines of codes and the memory areas also; we can use and edit the codes very clearly, so underlying the codes, it’s the must one for this keyword.

Recommended Articles

This is a guide to C++ typedef. Here we discuss the introduction, how typedef work in C++? Along with examples, respectively. You may also have a look at the following articles to learn more –

You're reading How Typedef Work In C++ With Examples

How Unserialize Function Work In Php With Examples?

Introduction to PHP unserialize

The PHP unserialize is one of the functions that can be used for to convert the serialized datas into the actual user input datas; it is an opposite process of serialize function mainly it will focus on the arrays, mapping collections it will calculate the array index for each element the big size or some other complex data structures we used some default method for operating the datas also the unserialize () method is returning the Boolean value if the user input is not unserializeable, so the false is returned on the output console the object is created separately for unserialize function.

Start Your Free Software Development Course

Syntax:

PHP has its own syntax for variables, keywords, and functions for creating web-based applications more sophisticated. Generally, PHP serialize format is not well documented like serialize() function; it supports serialized integers, floats, booleans, strings, arrays. Objects and it includes other references for support in the unserialize implementation.

<?php $input= array('',''); $var = serialize($input); $var1 = unserialize($var); ---some php codes based on the user needs---

The above codes are the basic syntax for using the serialize() and unserialize() function in PHP. It supports all the data types and other default functions.

How unserialize Function Work in PHP?

The unserialize function depends on the serialize function; whatever the datas are called and used on that function, it will be fully serialized with keys. If we want to access the data, we want to deserialize the datas or unserialize the datas in the code. Then only we accessed the data; it is also used for the file concepts. Using these serialize and unserialize() functions always return the Boolean conditions it will be to secure and more protected on the unserializing objects, or we can call it as untrusted datas. So it will be avoided for some other malwares, viruses from the outside of the machine. It also secured with the code injections and even db end it will avoid some sql injections attacks for untrusted malware sites.

Generally, the unserialize() function takes two parameters, str and options; the str is one of the parameters it contains serialized strings waiting for to be deserialized, and options are one of the arrays it contains for the control for certain function behaviors it accepts only for valid users particularly inbuilt classes like allowed_classes. It accepts only for the specified class names and particularly some methods like _wakeup() and _destruct(); these methods are implementing by using the serialized objects; when we use this method, it automatically executed when the unserialize() function is called on the specific object.

Examples of PHP unserialize

Given below are the examples of PHP unserialize:

Example #1

Code:

<?php $inputs = serialize(array('Siva', 'Raman', 'Sivaraman', 'wdigb', 'dwiugv', '87dhg', 'wdhgv', 'edhgfv', 'hfe', 'wgieufv', 'ehoije', 'iwuoegf', 'wuieguv','jdgv', 'wqgdjf', 'khwdjgh','jdhfdkswi', 'uqiwuke', 'iqweyf', 'oiuqiwleyugu' )); $vars = unserialize($inputs); var_dump ($vars); echo $vars;

In the above example, we used the serialize and unserialize() functions are in the same codes. Whenever the user gives the input to the application, it will store it on a separate variable, and it is the serialized one and it also to be print on the console by using the echo statements. We want to unserialize the datas by using the unserialize() function, and it will be stored it on a separate variable, and also it will be printed by using the same echo statements. If we want to print the results on the console, we will use other default methods like print, echo etc. these are some methods which is used on the PHP scripts.

Example #2

Code:

<?php class demo { public $vars; } class demo1 { public $vars1; } class demo2 extends demo { public $vars2, $vars3; } class demo3 extends demo2{ public $vars4; } class demo4 extends demo3 { public $vars5; } class demo5 extends demo4 { public $vars6; } class demo6 extends demo5{ public $vars7; } class demo7 extends demo6 { public $vars8,$vars9, $vars10; } $c1 = new demo(); $c3 = new demo2(); $c2 = new demo1(); $d1 = serialize($c1); $d2 = serialize($c2); $d5 = serialize($c3);

Output:

Example #3

Code:

<?php class demo { public $vars; } $vars1= new demo(); $vars2= serialize($vars1); $vars3= unserialize($vars2); echo  var_dump($vars3);

Output:

In the final example, we used both serialize and unserialize functions in that we used key-value pairs for the unserialize the arrays and objects in PHP. We used one variable with the value “Siva” it will be a plain text string and then is converted back to the object that is serialized and unserialized the values.

Conclusion

Recommended Articles

This is a guide to PHP unserialize. Here we discuss the introduction, syntax, and working of unserialize functions in PHP along with different examples, respectively. You may also have a look at the following articles to learn more –

C# Class & Object Tutorial With Examples

C# is based on the C++ programming language. Hence, the C# programming language has in-built support for classes and objects. A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity.

For example, if you want to work with employee’s data in a particular application.

All of these operations can be represented as a class in C#. In this chapter, we will look at how we can work with classes and objects in C# in more detail.

In this tutorial, you will learn-

What is Class and Object?

Let’s first begin with classes.

As we discussed earlier classes are an encapsulation of data properties and data methods.

The properties are used to describe the data the class will be holding.

The methods tell what are the operations that can be performed on the data.

To get a better understanding of class and objects, let’s look at an example below of how a class would look like.

The name of the class is “Tutorial”. The class has the following properties

Tutorial ID – This will be used to store a unique number which would represent the Tutorial.

Tutorial Name – This will be used to store the name of the tutorial as a string.

A class also comprises of methods. Our class has the following methods,

SetTutorial – This method would be used to set the ID and name of the Tutorial. So for example, if we wanted to create a tutorial for .Net, we might create an object for this. The object would have an ID of let’s say 1. Secondly, we would assign a name of “.Net” as the name of the Tutorial. The ID value of 1 and the name of “.Net” would be stored as a property of the object.

GetTutorial – This method would be used to get the details of a specific tutorial. So if we wanted to get the name of the Tutorial, this method would return the string “.Net”.

Below is a snapshot of how an object might look like for our Tutorial class. We have 3 objects, each with their own respective TutorialID and TutorialName.

How to Create a Class and Object

Let’s now dive into Visual Studio to create our class. We are going to build upon our existing console application which was created in our earlier chapter. We will create a class in Visual Studio for our current application.

Let’s follow the below-mentioned steps to get this example in place.

Step 1) The first step involves the creation of a new class within our existing application. This is done with the help of Visual Studio.

Step 2) The next step is to provide a name for the class and add it to our solution.

In the project dialog box, we first need to provide a name for our class. Let’s provide a name of chúng tôi for our class. Note that the file name should end with .cs to ensure it is treated as a proper class file.

If the above steps are followed, you will get the below output in Visual Studio.

Output:-

A class named chúng tôi will be added to the solution. If you open the file, you will find the below code added to the class file.

Code Explanation:-

The first part contains the mandatory modules which Visual Studio adds to any .Net file. These modules are always required to ensure any .Net program runs in a Windows environment.

The second part is the class which is added to the file. The class name is ‘Tutorial’ in our case. This is the name which was specified with the class was added to the solution.

For the moment, our class file does not do anything. In the following topics, we will look into more details on how to work with the class.

Fields and methods

We have already seen how fields and methods are defined in classes in the earlier topic.

For our Tutorial class, we can have the following properties.

Tutorial ID – This will be used to store a unique number which would represent the Tutorial.

Tutorial Name – This will be used to store the name of the tutorial as a string.

Our Tutorial class can also have the below-mentioned methods.

SetTutorial – This method would be used to set the ID and name of the Tutorial.

GetTutorial – This method would be used to get the details of a specific tutorial.

Let’s now see how we can incorporate fields and methods in our code.

Step 1) The first step is to ensure the Tutorial class has the right fields and methods defined. In this step, we add the below code to the chúng tôi file.

Code Explanation:-

The first step is to add the fields of TutorialID and TutorialName to the class file. Since the TutorialID field will be a number, we define it as an Integer, while TutorialName will be defined as a string.

Next, we define the SetTutorial method. This method accepts 2 parameters. So if chúng tôi calls the SetTutorial method, it would need to provide the values to these parameters. These values will be used to set the fields of the Tutorial object.

Note: let’s take an example and assume our chúng tôi file calls the SetTutorial with the parameters “1” and “.Net”. The below steps would be executed as a result of this,

The value of pID would become 1

The value of pName would be .Net.

In the SetTutorial method, these values would then be passed to TutorialID and TutorialName.

So now TutorialID would have a value of 1 and TutorialName would have a value of “.Net”.

Here we set the fields of the Tutorial class to the parameters accordingly. So we set TutorialID to pID and TutorialName to Pname.

We then define the GetTutorial method to return value of the type “String”. This method will be used to return the TutorialName to the calling program. Likewise, you can also get the tutorial id with method Int GetTutorial

Here we return the value of the TutorialName field to the calling program.

Step 2) Now let’s add code to our chúng tôi which is our Console application. The Console application will be used to create an object of the “Tutorial class” and call the SetTutorial and GetTutorial methods accordingly.

(Note:- An object is an instance of a class at any given time. The difference between a class and an object is that the object contains values for the properties.)

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoApplication { class Tutorial { int TutorialID; string TutorialName; public void SetTutorial(int pID,string pName) { TutorialID=pID; TutorialName=pName; } public String GetTutorial() { return TutorialName; } static void Main(string[] args) { Tutorial pTutor=new Tutorial(); pTutor.SetTutorial(1,".Net"); Console.WriteLine(pTutor.GetTutorial()); Console.ReadKey(); } } }

Code Explanation:-

The first step is to create an object for the Tutorial class. Mark here that this is done by using the keyword ‘new’. The ‘new’ keyword is used to create an object from a class in C#. The object is then assigned to the pTutor variable.

The method SetTutorial is then called. The parameters of 1 and “.Net” are passed to the SetTutorial method. These will then be used to set the “TutorialID” and “TutorialName” fields of the class accordingly.

We then use the GetTutorial method of the Tutorial class to get the TutorialName. This is then displayed to the console via the Console.WriteLine method.

If the above code is entered properly and the program is run the following output will be displayed.

Output:

From the output, you can clearly see that the string “.Net” was returned by the GetTutorial method.

Summary

The class is an encapsulation of data properties and methods. The properties are used to define the type of data in the class. The methods define the operations which can be performed on the data.

How Include Works In Linq With Examples?

Introduction to LINQ Include

Web development, programming languages, Software testing & others

Syntax:

Let’s understand the following syntax,

var C_OrderDetails=context.customer details.Include ("OrderDetails").ToList();

In this syntax, we use the include method to combine the related entities in the same query, like merging multiple entities in a single query.

How does include work in LINQ? Var COrderDetails=context.CustomerDetails.Include ("OrderDetails").ToList();

By using only SQL statements instead of using the Include() methods, we need to generate the following queries to retrieve the same above,

SELECT * FROM CustomerDetails;

Instead of using Include (“OrderDetails”), the code looks as follows,

SELECT * FROM CustomerDetails JOIN OrderDetails ON Customer_ID=OrderDetails.Customer_ID; Var Customer_OrderDetails= context.CustomerDetails.Include("OrderDetails").Include("LineItems").Include ("ProducDetails").ToList();

We can make it use multiple calls to Include() to get the objects along various paths. If you require the objects in the same path, you must make a single call specifying the entire path.

Example

When using Include, if we have n number of queries to execute n number of times that is time-consuming, then it’s like select N+1 problem; this issue happens only because the lazy loading mechanism enables by default to execute a single query n number of queries to do something. So it’s better to avoid the select N+1 problem in Entity Framework; we need to use the Include Method, which helps to build a single query with required data using the Join clause, and this is the most resourceful way compared to executing queries multiple times.

Let’s see the sample program with the use of LINQ_Include. We need to include the namespace chúng tôi entity which the LINQ Include is an extension method of the Data.Entity namespace. Entity Framework version provides LINQ Include() by using chúng tôi and System.Data.Entity.

Code:

using System; using System.Data.Entity; using System.Linq; using System.Collections.Generic; public class Program_LINQ_Include { public static void Main() { Inserting_Data(); using (var context = new EntityContext()) { var customers = context.Customers .ToList(); Displaying_Data(customers); } } public static void Inserting_Data() { using (var context = new EntityContext()) { context.BulkInsert(CustomerData()); context.BulkInsert(InvoiceData()); context.BulkInsert(ItemData()); } } { { new Customer() { Name ="Peter"}, new Customer() { Name ="Smith"}, new Customer() { Name ="James"} }; return list; } { { new Invoice() { Date = new DateTime(2024,5,3), CustomerID = 1}, new Invoice() { Date = DateTime.Now.AddDays(-5), CustomerID = 1}, new Invoice() { Date = DateTime.Now.AddDays(-3), CustomerID = 1}, new Invoice() { Date = new DateTime(2024,4,15), CustomerID = 2}, new Invoice() { Date = new DateTime(2024,2,20), CustomerID = 3}, new Invoice() { Date = new DateTime(2024,5,22), CustomerID = 3}, }; return list; } { { new Item() { Name = "Mobile-Charger", InvoiceID = 1}, new Item() { Name = "Laptop-DELL", InvoiceID = 1}, new Item() { Name = "Stationeries", InvoiceID = 1}, new Item() { Name = "Note-Books", InvoiceID = 2}, new Item() { Name = "DataCard", InvoiceID = 2}, new Item() { Name = "PenDrive", InvoiceID = 3}, new Item() { Name = "Water-Bottles", InvoiceID = 3}, new Item() { Name = "Stationeries", InvoiceID = 3}, new Item() { Name = "DataCard", InvoiceID = 4}, new Item() { Name = "School-Bags", InvoiceID = 4}, new Item() { Name = "Table-Chairs", InvoiceID = 4}, new Item() { Name = "Lap-Table", InvoiceID = 4}, new Item() { Name = "Mobile-Charger", InvoiceID = 5}, new Item() { Name = "School-Bags", InvoiceID = 5}, new Item() { Name = "Stationeries", InvoiceID = 6}, new Item() { Name = "Laptop-DELL", InvoiceID = 6}, new Item() { Name = "Loptop-Cover", InvoiceID = 6}, new Item() { Name = "PenDrive", InvoiceID = 6}, new Item() { Name = "Memory-Card", InvoiceID = 6}, new Item() { Name = "Mobile-Charger", InvoiceID = 6}, new Item() { Name = "School-Bags", InvoiceID = 6}, new Item() { Name = "Touch-Pad", InvoiceID = 6}, }; return list; } { foreach(var customer in list) { Console.WriteLine(customer.Name); foreach(var invoice in customer.Invoices) { Console.WriteLine("t" + invoice.Date); foreach(var item in invoice.Items) { Console.WriteLine("tt" + item.Name); } } } Console.WriteLine("tt"); } }

Output:

Let’s understand the above example, like how the LINQ Includes functionality to load the related entities. To assume that the Customer_Details Object has links to its Invoice_Details and those orders have an ItemData reference. Likewise, we can make several links to the related objects by using LINQ Include(), which allows you to specify the related entities to be read from the database in a single query.

Conclusion

I have explained the LINQ Include() method with several examples programmatically in this article. It enables us to retrieve the related entities from the database in the same query. Using the Include method in a single query, we can easily read all related entities from the database.

Recommended Articles

This is a guide to LINQ Include. Here we discuss the Introduction, Syntax, and working of include method, example, and code implementation. You may also have a look at the following articles to learn more –

How Json Works In Mongodb With Examples

Introduction to MongoDB JSON

MongoDB JSON is the lightweight interchange format; we can easily transfer MongoDB JSON from one system to other. Also, we can easily read and write the file; the abbreviated name of MongoDB JSON is JavaScript object notation. In MongoDB, high-level JSON has two entities. First is an object, and the second is an array; the object is nothing but the value pair collection, and the array is a list of order values; using these two entities, we can develop complete documents in MongoDB. While creating a JSON object is started with braces and then comes key and value.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax of MongoDB JSON

Given below is the syntax mentioned:

1. MongoDB JSON document structure syntax.

}

In the above syntax, field1 to fieldN contains the field which was we have used in the JSON documents.

Value1 to ValueN is the value of the JSON field.

Mongoexport –collection = collection_name –db = db_name –out = filename.JSON

In the above syntax, we are creating the dump file.

The parameter mongoexport is used to export the collection into the JSON file.

Collection parameter is used to export the specified collection into the file.

DB parameter is used to export the specified database collection into the file.

Out parameter is the default that we need to use when exporting any collection in MongoDB.

The filename is the name of the JSON dump file.

3. Import the MongoDB JSON file.

In the above syntax, we are importing the JSON dump file into the specified collection.

The parameter mongoimport is used for import the JSON file data.

The collection parameter is used to import the data into the specified collection from the file.

DB parameter is used to import the data into a specified database collected from the file.

How JSON Works in MongoDB?

It is the plain text which was written in JavaScript object notation. We can use it to send the data between one computer to another computer. The use of JSON in MongoDB is very easy; also, we can use the JavaScript built-in function to convert the JSON strings into the object of JavaScript’s.

There is two built-in functions:

JSON.parse ()

JSON. Stringify ()

It supports all the data types.

Below data type is supported by MongoDB JSON:

Number

Array

Boolean

String

It makes the notation of key-value pair using strings, and it will easily be exported and imported into the various tools. The important function of JSON is to transmit the data between web applications and servers. It is basically used the alternate of an XML, which is the language-independent data format. It has a UTF-8 string format. Thus, humans and machines both understand and read the data of files.

It provides a flexible database and schema design as compared to the tabular data model, which was used in relational database models. Basically, documents are polymorphic; the fields can vary from one document to another within the same collection. Using it, we have no need to create the structure of documents for the database. We can directly start our development without creating any structure.

Examples of MongoDB JSON

Different examples are mentioned below:

Example #1

Insert the data using string data types.

In the below example, we have inserted the string value name as ABC into the MongoDB_JSON collection. Thus, the name attribute shows the field, and the ABC string shows the value of the field.

Code:

db.MongoDB_JSON.find ().pretty ()

Output:

Example #2

Insert the data using numeric data types.

In the below example, we have inserted the numeric value emp_id as 101 into the MongoDB_JSON collection. Thus, the Emp_id attribute shows the field, and 101 integers are shown the value of a field.

Code:

Output:

Example #3

Insert the data using array data types.

In the below example, we have inserted the array value into the MongoDB_JSON collection. Therefore, we have to assign MongoDB_JSON the same name as the field and the value.

Code:

var MongoDB_JSON = ["MongoDB is NoSQL DB", "MySQL is OpenSource DB", "PostgreSQL is object RDBMS"] db.MongoDB_JSON.find ().pretty ()

Output:

Example #4

Insert the data using Boolean data types.

In the below example, we have inserted the Boolean value name as true and the middlename as false into the MongoDB_JSON collection. Name and middlename attribute shows the field, and true, false Boolean value shows the value of the field.

Code:

> db.MongoDB_JSON.find ().pretty ()

Output:

Example #5

Below example shows export MongoDB_JSON collection into the MongoDB_JSON. Json file.

After exporting the data into the JSON file, we can see this file using the cat command. This data comes in a human-readable format.

Code:

[[email protected] ~]# cat MongoDB_JSON. Json

Output:

Example #6

MongoDB import from the JSON file.

The below example shows that import the data into the Mongo_JSON_NEW collection from the MongoDB_JSON. Json file.

Code:

db.Mongo_JSON_NEW.find().pretty()

Output:

Conclusion

They have their multiple data types are available in MongoDB; using this datatype, we can insert the data into the collection. We can import the data into the collection from JSON file using mongoimport; we can also export the collected data into the JSON file using mongoexport.

Recommended Articles

This is a guide to MongoDB JSON. Here we discuss the introduction, how JSON works in MongoDB? and examples for better understanding. You may also have a look at the following articles to learn more –

Expressions In Sql With Examples

Introduction to SQL Expressions

SQL expressions are the collective formula consisting of values, column names, operators, and functions present in SQL. The expressions in SQL are further classified as Boolean expressions, numeric expressions, and date-time expressions. The expressions are formulas that evaluate a particular value that can be further used according to our necessity. Boolean expressions are used to evaluate a condition that results in either true or false and can be used anywhere but mostly used in the where clause to perform restrictions on column values.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

The numeric expressions are used to evaluate the summarized and cumulative numeric values that are mostly used for reporting purposes. The numeric expressions can be formed by using aggregate functions of SQL such as SUM, COUNT, AVG, etc, and operators like addition, subtraction, multiplication, etc. Date and time-related expressions are used to evaluate and retrieve the current date and time or some manipulated dates and times.

Expressions in SQL with Examples 1. Boolean Expressions

The use of Boolean expressions is mainly done in the where clause of the SQL queries which can be either SELECT, INSERT, UPDATE, and DELETE. Note that the conditions and expressions used in the WHERE clause can make the use of AND, OR, NOT, etc operators so that the final value retrieved from the condition will be a Boolean value. This is called a Boolean expression. Let us see the syntax of the usage of Boolean expressions in SELECT query inside the WHERE clause

SELECT column_name1, column_name2, column_nameN FROM name of the table WHERE boolean expression;

Let us consider a simple example where we have an existing table named educba_writers_demo that has the contents as retrieved from the following query statement –

SELECT * FROM educba_writers_demo ;

The execution of the above query statement will give the following output:

Now, we will apply a boolean condition in where a clause specifies that the value of the rate column should be greater than 700. The condition will return either true or false for each of the records in the table. If it’s true then the record will be added in the final resultset or not. Let us execute the following query and observe the output –

SELECT * FROM educba_writers_demo

The execution of the above query statement will give the following output:

2. Numeric Expressions

Numeric expressions involve usage of literal values and column values and that are manipulated with the usage of operators like add, subtract, divide and multiply and different functions that are available in SAQL such as aggregate functions containing SUM(), COUNT(), AVG(), MAX(), MIN(), etc to retrieve a value that can be used further. Most of the time, numerical expressions are used in the retrieval list of the SELECT query statement to retrieve the summarized data that is sent to the client mostly for analysis purposes such as reporting and dashboarding. Let us consider simple examples that use numerical expressions. Syntax of using numerical expressions is as shown below:

SELECT Numerical expression FROM name of the table [WHERE restriction];

Let us firstly consider a simple example that we used above to explain the working of the AVG() function. We will calculate the average value of SQL numbers using the AVG() function. Let us create one simple table named numbers and store the num column value in it. We will use the following query statement to create our table –

CREATE TABLE numbers (num INT) ;

The execution of the above query statement will give the following output:

Now, we will insert the above records in the table. Our query statement will be as follows –

INSERT INTO numbers(num) VALUES (50), (100), (150), (200);

Let us now retrieve the records once:

SELECT * FROM numbers ;

The execution of the above query statement will give the following output:

Now, we will calculate the average of num column of numbers table using AVG() function using the following query statement –

SELECT AVG(num) FROM numbers ;

The execution of the above query statement will give the following output:

Similarly, we can use COUNT(), MAX(), and various other functions and also formulas involving operators. Let us consider the usage of operators along with avg() function in the following example –

SELECT AVG((num * 10) + 1) FROM numbers ;

Now, we will calculate the total of num column of numbers table using SUM() function using the following query statement –

SELECT SUM(num) FROM numbers ;

The execution of the above query statement will give the following output:

3. Date Time Expressions

The expressions that are related to date and time help in fetching the information such as current date, time, and timestamp. This is used for informative purposes and to store temporal values in the table to record the time and date during which the data was being inserted and also for assigning a default value to the fields with datatype like date, time, DateTime, and timestamp. Let us firstly use a simple query statement that retrieves the current timestamp –

SELECT CURRENT_TIMESTAMP;

The execution of the above query statement will give the following output:

Further, we can use the different functions that are available in SQL to handle temporal values such as GETDATE() to retrieve the current date and so on.

Conclusion

SQL expressions can be used to evaluate a value that results from the combination of functions, operators, literal values, and column values. The returned value of the expression is further used either for decision making as summarized data or informational purposes. The expressions are classified into three types in SQL that are boolean expressions, numerical expressions, and date time-related expressions respectively.

Recommended Articles

We hope that this EDUCBA information on “SQL Expressions” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Update the detailed information about How Typedef Work In C++ With Examples on the Tai-facebook.edu.vn website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!