Trending March 2024 # How Timestamp Data Type Works In Mysql ? # Suggested April 2024 # Top 7 Popular

You are reading the article How Timestamp Data Type Works In Mysql ? updated in March 2024 on the website Cattuongwedding.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 April 2024 How Timestamp Data Type Works In Mysql ?

Introduction to MySQL Timestamp

MySQL Timestamp is a time-based MySQL data type containing date and time together. Timestamp supports Universal Time Coordinated(UTC) for MySQL. The format of the timestamp in MySQL is set to 19 characters: YYYY-MM-DD HH:MM:SS. Timestamp data type values range from 1st January 1970 UTC to 19th January 2038 UTC. UTC refers to a coordinated time scale conserved by the Bureau International des Poids et Mesures (BIPM). MySQL recognizes UTC as “Z time” or “Zulu Time”. MySQL converts a timestamp value to UTC format, adjusts it to the time zone connection, and then stores it in the database table when it is inserted into a table. Whereas if we execute a query to access the timestamp, the server MySQL changes the UTC Timestamp value reversing to the respective time zone connection. This can be essential to outlook the Timestamp value, which helps to know in time zone format. Remember that this type of conversion only takes place in the Timestamp data type but not for others like the DATETIME MySQL data type. By default, the time zone connection is the same as the time zone o MySQL server. Connecting to MySQL Server allows you to apply a different time zone.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax

The Timestamp()function, which denotes a data type, returns a DateTime-based value.

The basic syntax of a timestamp is as follows:

Timestamp (exp, time)

Here, the two parameters represent these two values in the syntax:

exp is required, which denotes an expression with a date or DateTime value.

time is an optional time value to add to the first parameter expression in the syntax above.

Note: For this article, we have used the PostgreSQL server.

How does Timestamp data type work in MySQL?

We can use the two arguments of the Timestamp function resulting from a DateTime value and combine it with a SELECT clause to retrieve the result as shown below:

SELECT TIMESTAMP ("2024-03-26", "10:15:11");

Here, the function converts the expression to a DateTime value, and a time interval is added to the value. The result will be simply in the format of the timestamp:

When a user enters a timestamp value in MySQL from a location with a different time zone, and the value is fetched from another location with an unlike time zone, the retrieved value may not be identical to the value stored in the database. If you don’t alter the time zone, then the similar Timestamp MySQL value you have stored will be fetched. This issue occurs because the time zone used for conversion is not the same as the time zone being used. But for data type DATETIME, the value remains unchanged.

Examples to Implement MySQL Timestamp

Let us explain the Timestamp keyword and how it handles the values by the following examples:

Example #1

MySQL Timestamp time zone: Suppose we have created a table named demo_timestamp, which includes a column with a Timestamp data type named asts1.

Code:

CREATE TABLE demo_timestamp(ts1 TIMESTAMP);

Now, let us enter a Timestamp MySQL value into the demo_timestamp table.

Code:

INSERT INTO demo_timestamp(ts1) VALUES('2024-03-27 03:20:01');

After inserting this Timestamp value, you can view the column value by using a SELECT SQL statement on the table:

Code:

SELECT ts1 FROM demo_timestamp;

Output:

Example #2

Initialize and update Timestamp Columns Automatically:

Let us study the following illustration where we have created a table ‘Employee’:

Code:

CREATE TABLE Employee(Empid INT PRIMARY KEY, EmpName VARCHAR (255) NOT NULL, Creation_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);

After this, let us insert a new record into the Employee table, but we will not specify any value for column Timestamp, i.e., Creation_time.

Code:

INSERT INTO Employee (Empid,EmpName) VALUES ('1','ABC');

We can view the table record and check the value stored in the Timestamp column by executing the following SQL query:

Code:

SELECT * FROM Employee;

Output:

We see that the current timestamp automatically initializes the column when the row has been inserted. We refer to this feature as Automatic Initialization.

Example #3

we will add a next column’Update_time’ in the table:

Code:

ALTER TABLE Employee ADD COLUMN Update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

The ON UPDATE keyword in this context is a clause that updates the time whenever there is a modification in the column value.

Suppose insert a new record:

Code:

INSERT INTO Employee (Empid,EmpName) VALUES('2','XYZ');

Code:

SELECT * FROM Employee;

Output:

Example #4

For this time, both Timestamp values are the same, but when we make any update like:

Code:

UPDATE Employee SET EmpName = 'JKL' WHERE Empid = 2;

Again, select all from the table to view the changes:

Code:

SELECT * FROM Employee;

Output:

Explanation: You can see that the Update_time_at column value changed to the date and time when the column value was updated, whereas the Creation_time remains unchanged, indicating the insertion time value. This functionality is referred to as Automatic Updating in MySQL for the TIMESTAMP function. Remember, if we update again with the same value, the Timestamp value for the Update_time column will not change.

Advantages of using Timestamp in MySQL

The timestamp function adds data and time columns to the table to manage all the activities relating to inserting, deleting, or updating any value serving as Logs.

MySQL maintains Universal Time Coordinated (UTC) using Timestamp to store data and time values together, and we can modify it based on the client’s zone setting.

Timestamp needs only 4 bytes’ storage capacity and contains a trailing fractional seconds part up to microseconds, i.e., 6 digits’exactness.

Conclusion

The Timestamp in MySQL returns the value comprising date and time parts. In MySQL, users can utilize a feature to determine the date and time of value insertion into a table or any changes that occur. This feature can be quite helpful. The MySQL Timestamp data type column features automatic initialization and updating. CURRENT_TIMESTAMP function, then, we get the current date and time of any operating system of the server on which the SQL executing.

Recommended Articles

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

You're reading How Timestamp Data Type Works In Mysql ?

How With Clause Works In Mysql?

Introduction to MySQL WITH Clause

MySQL WITH clause defines the CTE (Common table expressions). A common table expression is a named temporary result set that can be used multiple times. The CTE can be defined using WITH clause and can have one or more sub-clauses separated by a comma. The defined sub-clauses consist of each result set associated with a name to it. CTE can be used in other CTEs. We also have recursive CTE, which will be referred to as itself. The result set exists only within the scope of a single statement as SELECT, INSERT, UPDATE, or DELETE.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

In this session, let us see how CTE will be defined using the WITH clause, along with an example.

Syntax of MySQL WITH

Now let us consider the syntax of declaring the CTE using WITH clause:

1. Declaration of Single CTE

< QUERY STATEMENT >

2. Declaration of Multiple CTE

Syntax:

< QUERY STATEMENT > < QUERY STATEMENT >

WITH clause can be used in the beginning as:

WITH … SELECT …

WITH … UPDATE …

WITH … DELETE …

WITH statement can immediately precede as below:

CREATE TABLE … WITH … SELECT …

CREATE VIEW … WITH … SELECT …

INSERT … WITH … SELECT …

REPLACE … WITH … SELECT …

DECLARE CURSOR … WITH … SELECT …

EXPLAIN … WITH … SELECT …

How does WITH Clause Work in MySQL?

Now let us consider the tables that apply the CTE concept using the WITH clause:

1. Let us create a Table, use the above Syntax format, and insert Data into the Table.

create table Order_detail ( shop_id int, product_id int, brand_id int, Shop_name varchar(20), quantity int, price int );

2. Now, let us insert Data into the Table.

insert into Order_detail (shop_id, product_id, brand_id, Shop_name, quantity, price) values (1,1,1,'Kellogs',45,45); insert into Order_detail (shop_id, product_id, brand_id, Shop_name, quantity, price) values (2,7,5,'Fantasy Store',75,145); insert into Order_detail (shop_id, product_id, brand_id, Shop_name, quantity, price) values (3,3,2,'Laxshmi store',65,85); insert into Order_detail (shop_id, product_id, brand_id, Shop_name, quantity, price) values (4,4,7,'General store',25,65); insert into Order_detail (shop_id, product_id, brand_id, Shop_name, quantity, price) values (5,5,8,'Corn store',35,75);

Query:

select * from Order_detail;

Output:

3. Now let us Perform the Simple CTE Creation on the above Table.

Query:

With CTE_Orders_Store AS ( Select shop_id, product_id, brand_id, shop_name, quantity from order_detail where UPPER(shop_name) like '%store%' )

Output:

Explanation: Here we are finding the shops that have stored in their “shop_name” and the number of products sold exceeds 50.

4. Now let us Perform another Simple CTE on the above Table.

Query:

With CTE_Orders_quantity AS ( Select shop_id, product_id, brand_id, shop_name, quantity ) Select * from CTE_Orders_quantity where shop_idin( 2, 1);

5. Now let us Consider the above-Created table “order_detail” and create another Table as below.

Query:

create table Details_People ( id int, name varchar(20), location varchar(20), pincodeint, product_idint );

6. Insert the Below Rows into the Table as below.

Query:

insert into DETAILS_PEOPLE values (1, 'Sam', 'MP', 564321,1); insert into DETAILS_PEOPLE values (2, 'Sohan', 'Bangalore', 523321,7); insert into DETAILS_PEOPLE values (3, 'Will', 'Tamilnadu', 523021,3); insert into DETAILS_PEOPLE values (4, 'Ben', 'UP', 564000,3); insert into DETAILS_PEOPLE values (5, 'Hamington', 'UP', 564000,4); insert into DETAILS_PEOPLE values (6, 'Ji eun', 'Bangalore', 523321,2); insert into DETAILS_PEOPLE values (7, 'Jimin', 'UP', 564000,5); insert into DETAILS_PEOPLE values (8, 'Jk', 'Bangalore', 523321,4); insert into DETAILS_PEOPLE values (9, 'V', 'AP', 590001,5); insert into DETAILS_PEOPLE values (10, 'Jhope', 'Bangalore', 523321,1);

7. Now let us Select the Columns from the Table

Query:

Select * from Details_People;

Output:

8. let us perform the Complex CTE Between the two Tables.

With CTE_Orders_Store AS ( Select shop_id, product_id, brand_id, shop_name, quantity from order_detail where UPPER(shop_name) like '%store%' ) Select * from CTE_Orders_Stores JOIN details_people p ON s.product_id=p.product_id

Output:

Explanation: Here in the above query, we are finding the shops which have stored in their “shop_name” and the number of products sold greater than 50. The output of the CTE we have joined with the “details_people” and got the output.

Query:

With CTE_Orders_quantity AS ( Select shop_id, product_id, brand_id, shop_name, quantity ) Select * from CTE_Orders_quantity s JOIN details_people p ON s.product_id=p.product_id where shop_idin( 2, 1);

Output:

9. Now let us see the RECURSIVE CTE

Query:

WITH RECURSIVE REC_cte AS ( SELECT 1 AS A, 1 AS B, -1 AS C UNION ALL SELECT A + 1, B * 2, C * 2 FROM REC_cte WHERE A < 5 ) SELECT * FROM REC_cte;

Output:

Conclusion

MySQL WITH clause defines the CTE (Common table expressions). A common table expression is a named temporary result set that can be used multiple times.

You can define the CTE using the WITH clause, which allows for one or more sub-clauses separated by a comma in active voice.

Each sub-clause in the CTE defines a result set and associates it with a name. You can use CTEs within other CTEs. Additionally, recursive CTEs refer to themselves.

The result set exists only within the scope of the single statement as SELECT, INSERT, UPDATE, or DELETE

Recommended Articles

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

How Unwind Works In Mongodb?

Definition of Mongodb unwind

MongoDB unwind operator is used to deconstructing the array field from input to output documents, it will be used for each element from the document. The difference between input and output document in unwind operator is very simple, the output document value of a field of array is replaced by a single item of the input array of documents. MongoDB unwind operator is basically used for transfer complex documents into simple documents, it will improve the documents readability and understanding. Using unwind operator in MongoDB we can also perform operations like grouping and sorting on the data.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

Below is the syntax of unwind operator in MongoDB.

2)

}

1) Unwind operator –

This operator is used to deconstruct the documents in MongoDB. Every output and input documents depend on each other to deconstruct the value. We have passing the input parameter with unwind operator to display the result. Unwind operator is used with prefix as $ while using in MongoDB.

2) Path –

Type of this parameter in MongoDB unwind operator is a string. This is the path field of an array, path is used to specify the path of documents. This is a mandatory parameter while using unwind operator in MongoDB.

3) IncludeArrayIndex –

This is an optional parameter while using unwind operator in MongoDB. Type of this parameter in MongoDB unwind operator is a string. This states that the new name of a field is used to hold the index array for the element. This parameter name does not start with the $ sign.

4) PreserveNullEmptyArrays –

Type of this parameter in MongoDB unwind operator is Boolean. PreserveNullEmptyArrays is an optional parameter while using unwind operator in MongoDB. If the path of this parameter contains the true value unwind operator will show the output, if the path of this parameter contains the false value then unwind operator will not show the output.

How unwind work in Mongodb?

MongoDB unwind operator will deconstructs the documents for every document. Unwind operator is basically works on array elements. We can also use embedded documents with unwind operators.

I suppose our array contains the ABC student mark as {50, 55, 60, 70, 75}. Unwind operator will return the output as below.

{Name: “ABC”, mark: 75}

The above output shows that the array will be deconstructs into multiple documents. Our array contains the single documents value, but we can see the output will show the multiple documents in it.

We can pass includeArrayIndex and preserveNullEmptyArrays parameter while using unwind operator in MongoDB. Both parameters are optional while using unwind operator.

Unwind operator will duplicates each array element into different documents. This is used in an array that contains the data like a month, day of the week, and year.

Unwind operator is also working with the non-array path field. Before MongoDB version 3.2 if we have used a non-array path field it will show an error. After version 3.4 every non-array path field will not show any error it will return single elements of an array.

In the below example, we have used the non-array path field as a name. After using the non-array path field the array element will retrieve the single document.

Code:

db.MongoDB_Update.find ()

Figure – Unwind operator is work with non-array path field in MongoDB.

If we have missed any value in the path, unwind operator will not generate any output if we have entered an incorrect value.

Code:

Figure – unwind operator will not generate any output if we have entered any incorrect value.

In the above example, we have used id field in unwind operator, but id field is not present in MongoDB_Update collection. So unwind operator will return the empty result in output.

Example

The below example shows unwind operator in MongoDB.

1) Unwind operator with array field –

In the below example, we have used the array field name as lap_storage. After using the array field we can see that result will display each document with a different field.

Lap_storage contains the 6 array elements and MongoDB_Update collection contains the 2 documents, so we can see that unwind operator displays output as 12 documents.

db.MongoDB_Update.find ()

Figure – Example of unwind operator with array field.

2) Unwind operator with includeArrayIndex parameter –

In the below example, we have used includeArrayIndex parameter with unwind operator. We have used array field name as lap_storage and includeArrayIndex field as MongoDBIndex.

MongoIndex is a user-defined field that was used to capture the array index from lap_storage field.

Code:

db.MongoDB_Update.aggregate ([{$unwind: {path: “$lap_storage”, includeArrayIndex: “MongoDBIndex”}}])

Figure – Example of Unwind operator with includeArrayIndex parameter.

3) Unwind operator with preserveNullEmptyArrays parameter with true value –

In the below example, we have used preserveNullEmptyArrays parameter with unwind operator. We have used array field name as lap_storage and preserveNullEmptyArrays parameter value as true.

db.MongoDB_Update.find ()

Figure – Example of Unwind operator with preserveNullEmptyArrays parameter with true value

4) Unwind operator with preserveNullEmptyArrays parameter with false value –

In the below example, we have used preserveNullEmptyArrays parameter with unwind operator. We have used array field name as lap_storage and preserveNullEmptyArrays parameter value as false.

Code:

db.MongoDB_Update.find ()

Figure – Example of Unwind operator with preserveNullEmptyArrays parameter with false value.

5) Unwind operator using embedded documents –

The below example shows that unwind operator using embedded documents. We have embedded document field name as lap_spec.

Also, we have used preserveNullEmptyArrays parameter with unwind operator. We have set the value of preserveNullEmptyArrays parameter as true.

Code:

db.MongoDB_Update.find ()

Figure – Example of unwind operator using embedded documents in MongoDB.

Conclusion

Unwind operator is very useful and important in MongoDB to deconstruct the array field. We have using preserveNullEmptyArrays and includeArrayIndex optional parameter while using unwind operator. We can also use embedded documents with unwind operators. We can transfer complex documents into simple documents by using unwind operator in MongoDB.

Recommended Articles

This is a guide to Mongodb unwind. Here we discuss the definition, syntax, How unwind works in Mongodb? Examples, and code implementation. You may also have a look at the following articles to learn more –

How Encryption Works In Mongodb?

Definition of MongoDB Encryption

Mongodb encryption process involves to generate a master key of an entire database, after generating master key we are creating the unique keys for every database. Then we are encrypting our data with the database which was we have created, we can also encrypt our whole database by using master key. Any of the database involves the two forms either data at rest or data in motion, data at rest is the forms where data is not moving anywhere its static data forms. Data in motions will moves the data in network its static data forms.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

Below is the syntax of encryption in MongoDB.

1) Connect MongoDB instance by using encryption –

2) Connect MongoDB instance by using client certificate and certificate authority file –

3) Rotate KMIP master encryption key –

Parameter description syntax of MongoDB encryption are as follows.

1) Mongo – This parameter is used to login into MongoDB instance. In MongoDB we can login database instance using mongo command.

2) SSL – This is defined as login into the MongoDB database instance by using SSL authentication.

3) Host – The host and hostname is defined as IP or hostname used to login specified database instance in MongoDB. While login into any MongoDB database instance we need to use hostname.

4) sslCAFile – This is certificate authority file used to verify that certificate is present or not on database server. This file is used while login into the database server by using encryption.

5) sslPEMKeyFile – This file contains the certificate of mongo shell and this key is present on mongos or mongod instance.

6) enableEncryption – This parameter is define as use of encryption at the time of rotating master key.

7) kmipRotateMasterKey – This parameter is used to rotate master key of KMIP server. Using this parameter we can rotate master key in MongoDB.

8) kmipServerName – This is nothing but the KMIP server hostname which was used at the time of rotating master key.

9) kmipServerCAFile – This is certificate authority file of KMIP server. This file is used while rotating the master key.

10) kmipClientCertificateFile – This is client certificate file of KMIP server. This file is used while rotating the master key.

How encryption works in MongoDB?

MongoDB involves two types of data encryption forms.

2) Data in motion encryption

To encrypt the data using data at rest encryption enterprise MongoDB will provides the storage based and native symmetric key.

We can say that data at rest encryption is the data not moving over the network, we can say that it’s in static forms. Data at rest database encryption is also called as transparent data encryption its abbreviation is TDE. MongoDB uses the AES 256-bit standard encryption algorithm to encrypt the database. MongoDB uses the same encryption cipher key to encrypt as well as decrypt the data.

4) Fourth step is encrypt whole database by using the master key which was we have generated in first step.

In MongoDB, data is transacted between server application and database in two ways.

TLS and SSL are most secure protocols of encryption to send and receive data from two systems. This protocols is used in MongoDB encryption is some PEM file which was issued by the certificate authority. There are multiple settings available in MongoDB to configure the TLS and SSL protocol for client certificates.

We can also use sslCAFile to create certificate. We can store this file in MongoDB instance to use the encryption while login into the MongoDB instance. We can also rotate our encryption key. We can rotate our key by using KMIP master rotation.

Example

Below example shows encryption in MongoDB. Below steps shows how to use encryption in MongoDB.

1) First step is to create locally managed key file to manage the key management service. We can create by using OpenSSL. We have created the file name as mongodb_client.key.

Code:

# cat /encryption/mongodb_client.key

Figure – Example to create locally managed key file to manage the key management service.

2) After creating the key file, open the mongo shell command and login by using the keyfile, –shell, and –nodb option.

Code:

LOCAL_KEY

3) Third step involves load the documents of encryption using client-side encryption configuration.

Code:

}

Figure – Example to load the documents of encryption using client-side encryption configuration.

4) After setting configuration connect to the local host database.

Code:

csfleDatabaseConnection = Mongo(ClientSideFieldLevelEncryptionOptions)

Figure – Example to connect the local host database.

5) Fifth stage is show the database, connect to the database and show the collections from connected database.

Code:

show collections

Figure – show the database, connect to the database and show the collections.

Conclusion

Data at rest encryption and data in motion encryption has two forms of MongoDB data encryption. Data encryption is very important in MongoDB to secure data. Encryption involves generate master key for the database. We can rotate our master key using KMIP master rotation algorithm.

Recommended Articles

This is a guide to MongoDB Encryption. Here we discuss the Definition, How encryption works in MongoDB? examples with code implementation respectively. You may also have a look at the following articles to learn more –

How Left Property Works In Css

Introduction to CSS left

CSS left property is defined to declare a left side or horizontal position of a positioned element and one of the offset properties. This is applied to the position property values like fixed, absolute, and sometimes relative. Here the left value has the preference from left to right for the container as the CSS position, in conjunction with the left value, helps to align elements concerning document viewports. If the positioned element is static, then there is no effect on this left property.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

# box { position:relative; }

length: It determines the position of an element on the left edge in px, pt, em. And negative values are not assigned here.

auto: The browser determines the position of the left edge as a default value.

percentage: The position element is specified in percentage.

How left Property works in CSS?

To have good CSS web Development, the CSS comes with aligning elements to make it easy. Elements positioned as either “fixed” or “absolute” have their distance calculated based on the left margin of the element and the left edge of the containing block. The positioned elements are the ones where their position changes anything except static. Depending upon the ancestor’s container, the working principle of the left property process differently.

1. Left on Relative Position

Here the left property adds an offset to the element’s left edge, and it moves automatically to its right to its original form. The positive value makes the box to its right.

2. Left On Absolute Position

For those having absolute positioning elements, this left property shifts the left edge of an element to its right side from the left edge having an ancestor container with the positioning. In simple terms, the element moves towards the right side from the starting position.

3. Static

This property doesn’t have any effect on this static position. We can still use this to check for an animation effect and take px or calc () values.

Code:

@keyframes anim { 40% { left: 100px; } Examples of CSS left

Below are examples of left property in CSS by looking at its effects on different positioned elements.

Example #1

An example showing the position ‘Relative’ and set a value to the ‘left’ property.

Code:

Demo On CSS left Property div{ position: relative; width: 120px; height: 100px; font-size: 25px; } #aa { left: 200px; border: 4px solid blue; } #bb { left: 70%; border: 4px solid green; } #cc { left: 80%; border: 4px solid yellow; } #exap { left: initial; border: 4px solid lightbrown; }

Output:

Example #2

Code:

Demo On CSS left Property With Image on left h1{ color: rose; } img { position :fixed; left : 40px; } And it takes a wide diverse population with skyscrapers and largest urban forests which is sometimes called as ‘city forest’. They are geographically positioned on the Main River and has important trading centres. Frankfurt is Germany’s Financial Capital city and considered to be a metropolitan city. And it takes a wide diverse population with skyscrapers and largest urban forests which is sometimes called as ‘city forest’. They are geographically positioned on the Main River  abnd has important trading centers.

Output:

Example #3

Showing two positioning in the box.

Code:

div{ float:left; width:350px; height:150px; margin:12px; text-align:center; border:6px solid maroon; background:rgba(46, 41, 112, 1); color:fuchsia; font-size:34px; line-height:3.5em; box-shadow:6px 6px 6px olive; } .container1{position:absolute;left:-40px;} .container2{position:absolute;right:600px;}

Output:

Example #4

Three positioned elements.

div.Base { position: relative; width: 310px; height: 150px; border: 4px solid teal; } div.Derived { position: absolute; left: -12px; width: 200px; height: 220px; border: 4px solid aqua; } div.Subclass{ position: fixed; left: -10px; width: 210px; height: 150px; border: 4px solid purple; }

The above code uses negative values on the left property with no positioned parents. The last class, ‘Subclass’, behaves independently despite having a fixed position. It causes the container to move towards the left margin. As a result, all three classes appear to be overlapped in the output.

Output:

Example #5

Code:

.dem-orange { position: absolute; background: orange; width: 200px; height: 200px; left: 4px; top: 4px; } .dem-blue { position : relative; background: red; width: 150px; height: 100px; left: 8px; }

Output:

Conclusion

The above article showed us how to use the left property with their work and examples. It allows nudging different elements in a different orientation with the left and right values, and the initial value always lies in the flow of the document part.

Recommended Articles

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

How Guard Statement Works In Swift

Introduction to Swift guard

Swift guard is used to transferring control in the program, it is very simple to use just like if and else in programming. We can use a guard inside any loop, function, etc. Guard statement falls under the control flow statement which is used to transfer the control within the program when passing conditions do not match. If we want to exit the program early or want to redirect the program then we can use the guard statement in Swift.

Start Your Free Software Development Course

Syntax:

As we saw guard statement falls under the category of control flow statement, they are easy and simple to use just like if else.

guard condition else { statements }

This is the official syntax for using the guard statement as per the apple documentation. To define the guard statement in Swift we are just using ‘guard’ keyword. Also, we are passing the condition here. Based on the result we can write our own logic to it whether we want to break, continue or want to throw any exception, etc.

Syntax:

guard let abc = chúng tôi else { break }

As you can see in the above piece of syntax we are just using ‘guard’ keyword to implement the guard statement in Swift.

How guard Statement Works in Swift?

As we know the guard statement is used to transfer the control flow of the program if the condition does not match or satisfy. To implement this statement in our program we just need to use the ‘guard’ keyword followed by the condition. They are pretty much the same as if and else statement and very easy to use and implement.

Here we will first discuss their internal working followed by the sample example.

1. guard

This keyword is used to make the guard statement in Swift, after this statement we can mention our condition. Guard statements are fast and have their own benefits over other control flow statements. By the use of them, we can easily break the statement eerily or we can redirect it to another part of the program. Always remember the ‘guard’ statement is should have someone else blocked associate with it otherwise it will give us an error. Also, the else block should return something from it.

Let’s see points about how the else block of guard statement has some restriction with it that needs to be followed.

2. else block in guard statement

Also, we can pass the control outside the guard statement for which we can use any of the following inside the else block of guard statement:

break: This keyword is used to break the current execution of the program and return back the control to the calling one.

 return: This keyword is used to return any value from the block which can be anything like int, string, nil, etc

 throw: This keyword is used to throw any error, if we want to throw any error inside the else block then we can use this.

 continue: This keyword is used to continue the current execution of the program.

3. return type

while writing the guard statement condition in swift it should return the bool type in Swift. That means the condition should return the bool type otherwise we will receive an error in the program. We can also define the condition of the guard statement as Optional Binding.

Now we will see one sample example of the internal flow of guard statement in swift

Example:

Code:

guard sample == “hello” else { print(“password is blank”) return “not found” } return “its a match !!” } print(demo(name: “hello”)) print(demo(name: “Hello not “))

Example of Swift guard

Given below is the example mentioned:

In this example we are trying to use a guard statement in Swift, we are trying to match a string passed in the function. based on it we are returning the result as not or not found.

Code:

guard name == “hello” else { print(“password is blank”) return “not found” } return “its a match !!” } print(“Demo to show guard statement in Swift !!”) let result1 = demo(name: “hello”) let result2 = demo(name: “bye”) let result3 = demo(name: “world”) let result4 = demo(name: “hello”) let result5 = demo(name: “123”) print(“Printing result :::”) print(“Reuslt one is :::”) print(result1) print(“Reuslt two is :::”) print(result2) print(“Reuslt three is :::”) print(result3) print(“Reuslt four is :::”) print(result4) print(“Reuslt five is :::”) print(result5)

Output:

Conclusion

By using the guard statement we can redirect the flow of the program at a very early stage. They are easy to use and implement in Swift just like if and else statement. But they have some benefits over them.

Recommended Articles

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

Update the detailed information about How Timestamp Data Type Works In Mysql ? on the Cattuongwedding.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!