Trending December 2023 # Learn Working Of Json In Swift With Examples # Suggested January 2024 # Top 13 Popular

You are reading the article Learn Working Of Json In Swift With Examples updated in December 2023 on the website Achiashop.com. 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 January 2024 Learn Working Of Json In Swift With Examples

Introduction to Swift JSON

Swift JSON is used for communication of the IOS web application with the server by returning a series of formatted data or information. This formatted data organized in a proper hierarchical manner is called Swift JSON. Foundation framework that includes a class called JSONSerialization is exclusively used for converting any JSON involved within the web application into Swift data types like array, number, bool, String, and Dictionary. It is very difficult to predict the actual structure or the order in which values of JSON-based web applications will receive as part of returned data.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

There is no proper syntax for any Swift JSON it can be any resource file containing the data in an ordered manner as represented below but then indentation does matter while validating any JSON data as improper JSON input might vary and can behave differently while parsing and traversing as well.

{ "title": "some_data", "url": "any_url_can_be_included", "category": "Category_for_swift_language", "views": 25648 } How JSON works in Swift?

JSON parsing or manipulation with JSON in any programming language is a common functionality when any web application tries to communicate with the other server.

Any web application dealing with JSON data tries to decode the JSON data in an ordered manner. Swift JSON parsing is very important for any IOS developer as they will most often get acquainted with these kinds of data.

Decoding modules in swift are quite flexible and are very easy to understand without any indulgence of external API.

There are times when swift JSON containing JSONSerialization class method returns a value of any type and throws error in case the data cannot get parsed easily then a proper validation with error elicitation will be given to the user for identification of the actual exception.

Although the JSON data will get validated still there will be times when JSON may contain a single value, a response from a web application can encode an object or array as any top-level object for manipulation.

All the data types related to swift get used as per requirement and any optional value can be considered for it.

There is quite a need to create Model objects from the Model-view-controller design pattern that are often used to convert json data to objects which are specific to the application’s domain in a model view.

If the applications are related to one or more web services do not return a single, or consistent model for the representation of a model object, considering implementation of several initializers to handle all the possible representations.

JSON initializer helps a lot when it comes to extracting and getting the detailed implementation with errors and exceptions. Error Handling with error protocols helps in deserialization with the fail for protocol.

Many times, it happens that the application returns multiple endpoints for any resource that returns a single JSON response following any particular protocol.

A search endpoint may return zero or more endpoints then in that case the requested query may contain more or other metadata while presenting for the endpoint.

JSON parser plays a pivotal role in parsing as it helps in making the entire JSON data organized in a properly visualized format which gives an impression that the data can be organized in a proper manner.

Swift is the programming language that allows programmers to use and make the data ordered and visualized in a very easy and effective manner by giving an idea of proper idealization and organization for operations and manipulations.

Examples of Swift JSON

Here are the following examples mentioned below.

Example #1

This program demonstrates the JSON data where the input feed is represented as follows and the output feed after execution of the JSON parsing comes out to be shown as output. But it makes the Sample usage feed with the codeable mapping.

Code:

{ "title": "Usage of the optional Swift language.", "version": "4.0", "category": "Swift_version", "views": 25642 }

Output:

Example #2

This program demonstrates the JSON data where the input feed is represented with the same input as example 1 but with the mere difference of the fact that the JSON decoder will make use of the Object mapper for conversion of JSON String to model. This is shown in the output as shown:

Code:

{ "title": "Usage of the optional Swift language.", "version": "4.0", "category": "Swift_version", "views": 25642 }

Output:

Example #3

This program demonstrates the JSON data where the input feed is represented with the same input as example 1 but with the more difference of the fact that the JSON decoder will make use of the dictionary mapper for conversion of JSON String to model. This is shown in the output as shown:

{ "title": "Usage of the optional Swift language.", "version": "4.0", "category": "Swift_version", "views": 25642 }

Output:

Example #4

This program demonstrates the custom mapping for each defined key with the mapping of a blog and key and value pairs with the JSON and making the key encoding as the main conversion of the JSON to a blog.

Code:

{ "title": "Sat_Sun_Week:end_Comboff", "version": "swift_version_4.0", "visitors_way": 258965, "posts_for_members": 62542 }

Output:

Example #5

This program demonstrates the custom mapping for each defined key with the mapping of a blog and key and value pairs with the JSON and making the Object mapper in use for representation as shown in the output.

{ "title": "Sat_Sun_Week:end_Comboff", "version": "swift_version_4.0", "visitors_way": 258965, "posts_for_members": 62542 }

Output:

Example #6

This program demonstrates the custom mapping for each defined key with the mapping of a blog, key and value pairs with the JSON and making the Dictionary mapper in use for representation as shown in the output.

Code:

{ "title": "Sat_Sun_Week:end_Comboff", "version": "swift_version_4.0", "visitors_way": 258965, "posts_for_members": 62542 }

Output:

Conclusion

Swift JSON is the proper way of validating and making the entire data set and information organized in a visualized manner for the programmers. The successful communication between any web application and server helps a lot to analyze the entire application for product analysis and division of information uniformly among all applications efficiently.

Recommended Articles

This is a guide to Swift JSON. Here we discuss the introduction, syntax, and working of Swift JSON along with examples and code implementation. You may also have a look at the following articles to learn more –

You're reading Learn Working Of Json In Swift With Examples

Working Of Mixin In Typescript With Examples

Introduction to TypeScript Mixins

Web development, programming languages, Software testing & others

Working of Mixin in Typescript with Examples

There is no particular syntax for writing mixin class as it is an extra class written to overcome the single inheritance problem, which means there is no restriction for extending a single class one at a time. Using mixin class is used in building simple partial classes, and this mixin class returns a new class. Therefore, the syntax of the mixin class cannot be defined exactly as it is a class that can take a constructor to create a class that has the functionalities of the constructor by extending the previous class and then returns a new class.

Suppose if we have two classes X and Y where class X wants to get the functionality of class Y, and this can be done using extending class X extends class Y, but in Typescript, mixins are used to extend the class Y, and therefore this function Y takes class X, and therefore it returns the new class with added functionality, and here the function Y is a mixin. In general, the mixin is a function that takes a constructor of the class to extend its functionality within the new class that is created, and this new class is returned.

The exact working of mixin can be demonstrated as a process of mixing multiple classes to a single target class, and this is done by using the “implement” keyword in Typescript for the target mixin class, which also uses some generic helper functions which helps to copy the properties of each mixin to the target mixin. But we cannot use interfaces as it can only extend the members of the class but not their implementations. Therefore, TypeScript provides mixins that help to inherit or extend from more than one class, and these mixins create partial classes and combine multiple classes to form a single class that inherits all the functionalities and properties from these partial classes.

Example of TypeScript Mixins

Different example are given below:

Example #1

Code:

console.log(" Demonstration of mixin using extends in Typescript") class Courses { name = ""; x = 0; y = 0; constructor(name: string) { this.name = name; } } return class Scaling extends Base { _scale = 1; setScale(scale: number) { this._scale = scale; } get scale(): number { return this._scale; } }; } const Institute = Scale(Courses); const numcourse = new Institute("Educba"); numcourse.setScale(3); console.log(numcourse.scale);

In the above program, we are first creating class “Courses” which we are trying to scale the number of courses in the institute but to extend this class property we are using mixin concept that is first take a constructor as to make mixin extend the class “Courses” with new functionalities and the constructor is defined using “constructor” keyword. Then to extend the class “Courses”, we need to use the keyword “extends”, which is done n the function Scale where we are extending the constructor of the class to create a new class and return that class. The output of the code can be seen in the screenshot, where we are inheriting the property setscale() by extending the constructor and creating a new class named “Institute”, which is extended by the “Course” class.

Now let us see another example where it will take multiple classes and how the mixin works.

Example #2 console.log(" Demonstration of mixin in Typescript ") class  Mathfunc{ calculate(): void { console.log("The math formula is getting executed"); } } class Variables { display(): void { console.log("The variables given are calculated and display the result"); } } class Add implements Mathfunc, Variables { a: number; b: number; constructor(a, b) { this.a = a; this.b = b; } res(): number { return this.a + this.b; } display(): void { } calculate(): void { } } function applyMixins(derivedCtor: any, baseCtors: any[]) { Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name)); }); }); } applyMixins(Add, [Mathfunc, Variables]); let p: Add = new Add(9, 7); p.calculate(); p.display(); let r = p.res(); console.log("The Additin of two given numbers  is as follows:"); console.log(r);

Output:

In the above program, we can see we have classes “mathfunc”, “variables”, and “Add” where t display we are just providing “implements” keyword to extend the class properties. We are providing empty implementations which mixin helper functions will later replace. Therefore this mixin created iterate through properties of the base classes and then copy all these properties from these single classes into one single target class, and this done in the function apply mixin in the above program. Therefore we are trying to calculate the sum of two numbers where we have created a constructor with two different variables, and the result is displayed using the res() function, which returns the sum.

Conclusion

This article concludes with a demonstration of mixin in typescript where we saw how mixin works with keyword “extends” and “implements”. In this article, we saw an example of demonstrating the mixin which supports single inheritance by using these keywords in the program. We should also note that it may take much time in compiling the above approaches.

Recommended Articles

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

Working Of Bless() Function In Perl With Examples

Introduction to Perl bless function

Web development, programming languages, Software testing & others

Working of bless() function in Perl with examples

In this article, we will discuss a built-in function where to make the program understand that the variable can be made an object of a particular class in Perl, where this function is known as the bless() function. Unlike in other programming languages, Perl creates an object similar to creating or declaring variables. Therefore the Perl programming language provides a built-in function called bless() function, which makes the variable look like an object of the particular class that it belongs to.

Now let us see the syntax and examples of how the bless() function works in the below example.

Syntax:

bless var_ref, class_name;

Parameters:

var_ref: this parameter refers to the variable as an object of the class whose class name is specified.

class_name: This parameter specifies the class name to which the object is created by marking the variable reference as an object of this class specified in this parameter.

This function can take only var_ref as an argument also, and this function returns the reference of the marked variable as a reference to an object blessed into a particular or specified class name as specified in the arguments passed to the function.

Examples

Now let us see a simple example of demonstrating the bless() function in the below section.

Example #1 use strict; use warnings; print "Demonstration of bless() function in Perl."; print "n"; print "n"; package student_data; sub stud { my $class_name = shift; my $var_ref = { }; print "The bless() function is now implemented:"; print "n"; bless $var_ref, $class_name; return $var_ref; } print "Object creation"; print "n"; print "n"; my $info = stud student_data("Alen","Python",32); print "The student's name is :"; print "n"; print "n"; print "The course name student taken is:"; print "n"; print "n"; print "The student's age is :"; print "n"; print "n";

Output:

In the above program, we can see we have defined class “stud” using a keyword package in Perl. Then we created a subroutine to print the student’s details. In this variable, we are referring each variable to the class name using the variable reference to object creation and class name as arguments in the bless() function in the above program. Then we are printing each value of the objects created.

Now we will see bless function taking only one argument and two arguments in the example below.

Example #2 use strict; use warnings; print "Demonstration of bless() function in Perl."; print "n"; print "n"; package student_data; sub stud { my $class_name = shift; my $var_ref = { }; print "The bless() function is now implemented:"; print "n"; bless $var_ref; return $var_ref; } package Employee; sub emp { my $class2 = shift; my $var_ref2 = { }; bless $var_ref2, $class2; return $var_ref2; } print "Object creation"; print "n"; print "n"; print "Bless function takes only one argument:"; print "n"; print "n"; my $info = stud student_data("Alen","Python",32); print "The student's name is :"; print "n"; print "n"; print "The course name student taken is:"; print "n"; print "n"; print "The student's age is :"; print "n"; print "n"; print "Bless() function takes two argument:"; print "n"; print "n"; my $per_info = emp Employee("Ram", "Shukla", 343); print "The employee's name is :"; print "n"; print "n"; print "The employee's second name student taken is:"; print "n"; print "n"; print "The employee's employee number is :"; print "n"; print "n";

Output:

In the above program, we can see we have declared two classes “student_data” and “Employee” wherein the class “Student_data” we have defined function bless() with the single argument so when the variables reference is only passed, it will by default, take only the values of its current class but not of the “employee” class.

Conclusion

In this article, we conclude that the bless() function is a built-in function in Perl for marking the variables reference to object creation which belongs to the particular class with its class name specified as an argument in the bless() function. In this article, we have seen examples of bless() function taking two arguments and what happens if there are two classes and the class name is not specified as an argument in the function, which will, by default, take the current class name.

Recommended Articles

This is a guide to Perl bless. Here we discuss the introduction and Working of bless() function in Perl with examples for better understanding. You may also have a look at the following articles to learn more –

Learn The Examples Of Sql Datediff()

Introduction to SQL Datediff()

In SQL server suppose we have dates in our data and we want to know the difference between those dates then we can use the DATEDIFF function to know the difference between those dates in days, months, or years. So this function returns an integer as output and to understand more about this function lets know it’s syntax first.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax of Datediff() in SQL DATEDIFF (interval, startdate, enddate)

1. Interval – This is also called datepart and it is provided as a string to this function. This argument can be anything that represents a time interval like a month, week, day, year. We can also specify the quarter of the year.

year, yyyy, yy = Year SELECT DATEDIFF(year, '2010-12-31 23:59:59.9999999', '2011-01-01 00:00:00.0000000'); quarter, qq, q = Quarter SELECT DATEDIFF(quarter,'2010-12-31 23:59:59.9999999', '2011-01-01 00:00:00.0000000'); month, mm, m = month SELECT DATEDIFF(month, '2010-12-31 23:59:59.9999999', '2011-01-01 00:00:00.0000000'); dayofyear = Day of the year SELECT DATEDIFF(dayofyear,'2010-12-31 23:59:59.9999999', '2011-01-01 00:00:00.0000000'); day, dy, y = Da SELECT DATEDIFF(day,'2010-12-31 23:59:59.9999999', '2011-01-01 00:00:00.0000000'); week, ww, wk = Week SELECT DATEDIFF(week,'2010-12-31 23:59:59.9999999', '2011-01-01 00:00:00.0000000'); hour, hh = hour SELECT DATEDIFF(hour,'2010-12-31 23:59:59.9999999', '2011-01-01 00:00:00.0000000'); minute, mi, n = Minute SELECT DATEDIFF(minute,'2010-12-31 23:59:59.9999999', '2011-01-01 00:00:00.0000000'); second, ss, s = Second SELECT DATEDIFF(second,'2010-12-31 23:59:59.9999999', '2011-01-01 00:00:00.0000000'); millisecond, ms = Millisecond SELECT DATEDIFF(millisecond,'2010-12-31 23:59:59.9999999', '2011-01-01 00:00:00.0000000'); microsecond, mcs = Microsecond SELECT DATEDIFF(microsecond,'2010-12-31 23:59:59.9999999', '2011-01-01 00:00:00.0000000');

2. startdate, enddate – These are the actual dates to get the difference between. This is a mandatory parameter.

This function works in the SQL server starting from the 2008 version, Azure SQL Data Warehouse, Azure SQL Database, Parallel Data Warehouse.

Return Value

The return value is an int and is expressed by the datepart or the interval boundary which is the difference between the start and end date.

If the range of the return value for int is out of[-2,147,483,648 to +2,147,483,647], DATEDIFF function returns an error. The max difference between the start and end date is 24 days, 20 hours, 31 minutes, and 23.647 seconds for the millisecond. The max difference is 68 years, 19 days, 3 hours, 14 minutes, and 7 seconds for the second.

If the start and end date have a date with different data type then DATEDIFF will set 0 the missing parts of the other date which has lower precision

The above queries have the same start and end values. These are adjacent dates and the difference between them is a hundred nanoseconds (.0000001 second). The start and end dates cross one calendar and the result of each query is 1.

Examples

Here are the examples mention below

Example #1 – Calculating Age select ID,emp_name,emp_dateOfBirth from Employee

We have the above table Employee which consists of the date of birth and from this, we will calculate the age in terms of a year, month, and days in 2 steps

Step 1: Creating a function

CREATE FUNCTION fnEmpComputeAge(@EmpDOB DATETIME) RETURNS NVARCHAR(50) AS BEGIN DECLARE @AgeTempdate DATETIME, @AgeYears INT, @AgeMonths INT, @AgeDays INT SELECT @AgeTempdate= @EmpDOB SELECT @AgeTempdate=DATEADD(YEAR, @AgeYears, @AgeTempdate) SELECT @AgeTempdate=DATEADD(MONTH, @AgeMonths, @AgeTempdate) SELECT @AgeDays=DATEDIFF(DAY, @AgeTempdate,GETDATE()) DECLARE @EmpAge NVARCHAR(50) SET @EmpAge=Cast(@AgeYears AS NVARCHAR(4))+' AgeYears '+Cast(@AgeMonths AS NVARCHAR(2))+' AgeMonths '+Cast(@AgeDays AS NVARCHAR(2))+' AgeDays Old' RETURN @EmpAge End

In the above example, we have created a SQL Function to calculate the age of the employee from the DOB so the function takes @EmpDOBas a parameter and returns NVARCHAR(50). We will see this in action when we run this function. In step, we have created this function.

Then we add the calculated years in the @AgeTempdate using the DATEADD function.

Similarly, we calculated the month and added in @AgeTempdate, and then it is used to calculate days. Next, we declared @EmpAge and set it to the concatenation of the final output. Since the calculation result is in int we used Cast function to convert it into nvarchar.

Step 2: Using the function in the query

select ID,emp_name,emp_dateOfBirth,dbo.fnEmpComputeAge(emp_dateOfBirth) as EmpAge from Employee

The result is as follows:

As we can see we have used dbo.fnEmpComputeAge function and passed emp_dateOfBirth to calculate EmpAge and the result is as above.

Example #2 – Using scalar functions and subqueries for start and end date SELECT DATEDIFF(day, (SELECT MIN([ShipDate])FROM Sales.SalesOrderHeader), (SELECT MAX([ShipDate])FROM Sales.SalesOrderHeader)) as ShippingDateDiff;

The result is as follows:

In this example, we have calculated the shipping date difference using scalar functions and scalar subqueries for min and max.

Example #3 – Using ranking functions for the start date argument SELECT FirstName as first_name,LastName as last_name, DATEDIFF(day,ROW_NUMBER() OVER (ORDER BY DepartmentName),SYSDATETIME()) AS row_number FROM dbo.DimEmployee;

The result is as follows:

In this function, we have used ROW_NUMBER() ranking function as the start date argument.

Example #4 – Using an aggregate window function for the start date argument SELECT FirstName as first_name,LastName as last_name,DepartmentName as department_name, DATEDIFF(year,MAX(HireDate) OVER (PARTITION BY DepartmentName),SYSDATETIME()) AS HireInterval FROM dbo.DimEmployee

Conclusion

Hopefully, now you know what DATEDIFF() is in the SQL server and how it is used to calculate results the difference between date according to datepart.

Recommended Articles

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

Scala Option Working With Examples

Introduction to Scala Option

Scala Option is used in Scala Object-oriented programming whenever the return type of function can be a null. It has the values of a type or none in it, so the method returns an instance of option with the values whether be it any values or none. So in Scala Option if that value is returned, it is given back with some class generated, and if no values are returned the none class is generated. Some and none called to be called as the children of option class.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax and Parameters:

classOption [+A] extends Product with Serializable

Option has the type parameterized. We can define an option and give the data type whatever we want to for that.

Option[String], Option[Int], Option[File] etc.

Working and Examples

Scala Option checks the return type of the method and returns the value with some class if there is a value returned or else none is returned for a null value. Whenever a null is returned over a normal function and when it is not handled with in the program we are most liable to get an error of NULLpointerException, but with the help of the option over the scala code we will not get this Null pointer Exception. It is better used with Match function.

Let us check the methods and ways to create Scala Option with examples:

Example #1

Code:

object Main extends App { val b = a.get("Arpit") val c = a.get("Aman") println(b) println(c) }

Output:

This some and none are part of Scala Option that searches for the key and returns the value if it founds that and none is returned if it doesn’t find the value. So here it uses the Scala Option to fetch the value and handle none.

Example #2

Code:

object Main extends App { val b = e.get(1) val c = e.get(4) println(b) println(c) }

Output:

It can be best use when we have to implement the Scala Pattern Matching.

Let us check how we use that with the help of an example:

Example #3

Pattern matching matches the values over the collection whatever it is if the particular thing is found it returns the value else nothing is returned. So we will check how this is achieved with the help of Options.

Code:

object Main extends App { def matc(a : Option[String]) = a match { } val b = matc(f.get("Arpit") ) val c = matc(f.get("Aa")) println(b) println(c) }

Output:

We made a function named as matc that takes up the Option as an input and then checks whether the element is found or not, if the element is found we will get the value and if not the nothing return string is returned. A map is made with the key and value. Then this matches the value and we get the String written inside as the result and if nothing is there none is returned.

Methods 1. isEmpty

It checks whether the result we got from the option is Empty or Not. It returns a Boolean Value.

Example:

Code:

object Main extends App { def matc(a : Option[String]) = a match { } val res20 = matc(f.get("Arpit") ) val res19 = matc(f.get("Aa")) val d = res20.isEmpty val e = res19.isEmpty println(res20) println(res19) println(d) println(e) }

Output:

2. Non Empty

Returns True if it is Non Empty.

Example:

Code:

object Main extends App { def matc(a : Option[String]) = a match { } val res20 = matc(f.get("Arpit") ) val res19 = matc(f.get("Aa")) val d = res20.nonEmpty val e = res19.nonEmpty println(res20) println(res19) println(d) println(e) }

Output:

3. Zip And Unzip

Zips the value of the option it gets and makes a paired value, whereas unzip helps in unzipping the values from each other.

Example:

object Main extends App { def matc(a : Option[String]) = a match { } val res20 = matc(f.get("Arpit") ) val res19 = matc(f.get("Aa")) val c = res19 zip res20 val e = c.unzip println(c) println(e) }

Output:

4. getOrElse

It is just like an if else method, this works like if the option has some values get that or else return the default value.

Example:

We are creating a variable of type Option with some and none values inside it.

Code:

object Main extends App { val a : Option[Int] = Some(5) val b : Option[Int] = None val c : Option[String] = Some("Arpit") println(a.getOrElse(10)) println(a.getOrElse(3)) println(b.getOrElse(0)) println(b.getOrElse(3)) println(b.getOrElse(4)) println(c.getOrElse("Annad")) println(c.getOrElse(4)) println(c.getOrElse(4.0)) }

Output:

Here a, b, c are three variables of type Option having the type inside as String and Int.

The get or else method will check if it has some value and return accordingly.

Conclusion

From the above article we saw how Scala Option works and the benefit of using Scala Option over the Object oriented programming. With the help of examples we saw how Scala option handles the null values and the various results associated with it. We checked the syntax and functioning, so Scala Option is a better and a good approach for Scala Object-Oriented Programming.

Recommended Articles

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

Learn The Examples Of Truncate Table Statement

Introduction to SQL TRUNCATE()

TRUNCATE in standard query language (SQL) is a data definition language (DDL) statement used to delete complete data from a database table without deleting it. It frees up space or empties space in the table. However, we should note that TRUNCATE TABLE statements might need to be roll backable in many SQL databases. Also, being a DDL statement, the TRUNCATE table statement does not require a commit at each step; it automatically fires a commit at the end of the execution of the statement. Hence, we should be careful while using it.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax and Parameters

The basic syntax for using a SQL TRUNCATE TABLE statement is as follows :

TRUNCATE TABLE table_name;

Table_name: It is the name of the table whose records or rows you want to delete permanently.

How does the TRUNCATE TABLE statement work in SQL?

TRUNCATE TABLE statement in SQL works by zeroing out a file in the database, i.e., after running a TRUNCATE statement on an existing table, the table becomes empty and hence does not hold any row records. It resets the table to zero entries.

However, its structure, columns, indexes, constraints, relationships, views, etc., are preserved after truncating the table. The entire operation is like erasing data from the table but keeping the table intact.

TRUNCATE in Data Definition Language (DDL) is equivalent to DELETE in Data Manipulation Language (DML). The only difference is that the latter can be rolled back, but the first cannot. However, TRUNCATE is faster than DELETE because it usually bypasses the transaction system. It is not logged (it can vary across SQL databases) and does not follow predicates and hence seems to be faster than the DELETE operation. DELETE is a safer and slower operation.

Examples of SQL TRUNCATE()

Here are a few examples to explain the TRUNCATE TABLE statement in great detail.

Example #1

Simple SQL query to illustrate the function of the TRUNCATE TABLE statement.

To understand the SQL TRUNCATE TABLE, let us consider a “customers” table. The data in the table looks like this.

Command:

SELECT * FROM public.customers

Output:

Next, let us run the TRUNCATE TABLE statement on the customer’s table to remove all its records. We can do so using the following SQL query.

Command:

TRUNCATE TABLE customers;

Output:

We can see in the figure below that the TRUNCATE TABLE statement has removed all the records in the customer’s table. However, all the columns, relationships, indexes, and table structures have been kept safe.

Command:

SELECT * FROM customers;

Output:

Example #2

For this, let us consider two tables, “customer_details” and “students”. The table structure and the data in them look something like this. Records in the “Customer_details” table are as follows:

Command:

SELECT * FROM public.customers_details

Output:

Records in the “Students” table are as follows:

SELECT * FROM public.students

Output:

Next, we will run the TRUNCATE TABLE on the customer_details table and DROP TABLE on the student’s table, and then we will check the difference.

Command:

TRUNCATE TABLE customer_details;

Output:

Command:

Output:

We can observe from the images above that the DROP TABLE statement is faster than the TRUNCATE TABLE statement in SQL.

Now let us check what happened to the two tables after truncating and dropping, respectively.

Command:

SELECT * FROM customer_details;

Output:

Command:

SELECT * FROM students;

Output:

From the above two images, we can observe that in the TRUNCATE statement, the table structure is preserved; only the data/records in the table have been removed. Whereas in the case of the DROP TABLE statement, the entire table has been removed from the database.

Conclusion

TRUNCATE TABLE in SQL is a Data Definition Language (DDL) statement that empties an existing table by removing all the records while preserving table columns, privileges, indexes, views, constraints, relationships, etc. It is equivalent to but faster than the DELETE statement in SQL. However, unlike DELETE, it cannot be rolled back.

Recommended Articles

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

Update the detailed information about Learn Working Of Json In Swift With Examples on the Achiashop.com 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!