You are reading the article How Delegate Works In Kotlin updated in December 2023 on the website Minhminhbmm.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 How Delegate Works In Kotlin
Introduction to Kotlin delegateThe kotlin delegate is one of the design patterns that can be used to implement the application concepts like inheritance with the help of keywords like “by” or delegation methodology it’s used to derive the class to public access it implements with the other concepts like interface that allowed to call the specific object delegate used other keywords like public, default also the lazy values gets computed only in the parent classes also created anonymous objects without creating a class using the interfaces, properties and other default standard libraries other delegation types like explicit it supports oops and other delegation objects.
Start Your Free Software Development Course
Syntax of Kotlin delegateIn kotlin language, we used many default keywords, variables, and other built-in functions. Like that delegate is one of the concepts and the design pattern which helps to implement the application. With the help of “By” keyword we can achieve the delegation in the kotlin language.
interface first{ ---functions declaration— } class classname() : first{ ---override the function declaration with name which is used by the interface— } class name2(variable: interface name(first)) : first by variable fun main() { --some logic codes depends on the requirement— }The above code is the basic syntax for utilizing the kotlin delegation in the application.
How does delegate work in Kotlin?The kotlin language has many design patterns like java and other languages. Each design pattern has implemented its own logic and reduces the code complexity easily track the codes with other new users. Like that delegation is one of the design patterns and it is used to replace or on behalf of the other values the object request is received by one variable and instead of that variable will use another variable with the same logic and output results.
So that it is one of the easiest methods for providing support for both class and other properties that can be delegated to the pre-built in classes and methods. Generally, the kotlin delegation is achieved using the “by” keyword that delegates the kotlin functionality from the other interfaces with other methods. Each method has a separate behavior and its attribute.
In delegates, it is especially used to inherit from the particular class that may be the hierarchy one, and the same will be shared with the interface and decorates both internal and external objects of the original type. This can be achieved using the public APIs that delegate with the properties which are either set and get calls handling by using the object.
Examples of Kotlin delegateGiven below are examples of Kotlin delegates.
Example #1Code:
interface first { fun demo() fun demo1() } class example(val y: String) : first { override fun demo() { print(y) } override fun demo1() { println(y) } } class example1(f: first) : first by f { override fun demo() { print("Welcome To My Domain its the first example that related to the kotlin delegation") } } data class examples(val user: String, val ID: Int, val city: String) fun main() { val b = example("nHave a Nice Day users, Please try again!") example1(b).demo() example1(b).demo1() val inp1 = listOf( examples("Siva", 1, "your location is chennai"), examples("Raman", 2, "your location is tiruppur"), examples("Siva Raman", 3, "your location is mumbai"), examples("Arun", 4, "your location is andhra"), examples("Kumar", 5, "your location is jammu"), examples("Arun Kumar", 6, "your location is kahmir"), examples("Madhavan", 7, "your location is madurai"), examples("Nayar",8, "your location is karnataka"), examples("Madhavan Nayar", 9, "your location is delhi"), examples("Rajan", 10, "your location is west bengal"), ) val inp2 = inp1 .filter { it.user.startsWith("M") } .maxByOrNull{ chúng tôi } println(inp2) println("Your input user lists are : ${inp2?.user}" ) println("The user IDs are shown: ${inp2?.ID}" ) println("city: ${inp2?.city}" ) println("Thank you users for spenting the time with our application kindly try and spent more with our application its useful for your knowledge, $inp1") }In the first example, we used delegates design pattern with a collection list to perform the datas in array operations.
Example #2Code:
import kotlin.properties.Delegates class Employee { } } class EmployeeDetails { var Id: Int = 0 var oldID: Int by this::Id } val eg = fun(a: Int, b: Int): Int = a + b val eg1 = fun(a: Int, b: Int): Int { val multipl = a * b return multipl } val eg2 = fun(a: Int, b: Int): Int = a - b val addition = a + b demo(addition) } val subtraction = a - b demo(subtraction) } fun main() { println("Welcome To My Domain its the second example that related to the kotlin delegates") println("Thank You users have a nice day") val Employee = Employee() Employee.EmployeeName = "first" Employee.EmployeeName = "second" val EmployeeDetails = EmployeeDetails() EmployeeDetails.oldID = 41 println(EmployeeDetails.Id) val sum = eg(23,34) val multipl = eg1(34,23) val minus = eg2(34,23) println("Thank you users the sum of two numbers is: $sum") println("Thank you users the multiply of two numbers is: $multipl") println("Thank you users the subtraction of two numbers is: $minus") val new = { println("Thank you for using the kotlin delegates concepts in the application!")} new() new.invoke() val new1 = arrayOf(27,71,93) new1.forEach { println(it*it) } }Output:
Example #3Code:
class Third { var var1: Int = 13 var var2: Int by this::var1 } fun main() { val Third = Third() Third.var2 = 42 println("Welcome To My Domain its the third example taht related to the kotlin delegates") println(Third.var1) }Output:
In the final example, we used the delegates pattern with the help of by keyword.
ConclusionIn conclusion, kotlin uses many concepts like interface, classes, anonymous classes here in the delegate pattern without class we can create anonymous objects. The kotlin interface delegation should must know that when will be used and how to configure it on the application logic via code without affecting existing areas.
Recommended ArticlesThis is a guide to Kotlin delegate. Here we discuss the introduction, syntax, and working of delegate in kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –
You're reading How Delegate Works In Kotlin
How Reduce Function Works In Kotlin
Introduction to Kotlin reduce
Web development, programming languages, Software testing & others
SyntaxThe kotlin language has many default methods. Keywords and operators create the application deployment, and it’s faster compared to java type of applications. It’s a lightweight component that prevents the applications from increasing memory sizes.
fun main() { val vars -----some codes which depends on the requirement---- }The above codes are the basic syntax for the kotlin reduce() function used on the main method. We can import the packages based on the classes and methods which will use in the code. The reduce() function reduces the sizes and prints the values on the output console.
How does reduce Function Work in Kotlin?The kotlin language is cross-platform and a Java standard library, but the type is inference. The reduce() is one of the built-in functions that accumulates the values. It may be of any type, like an integer or number, strings starting with the index element, and it applies the code operation from left to the right set of values will be assigned for each set of elements. The values declared by the specific variable types will be array types; the value starts from the index 0.
Using the reduceIndexed() function also returns the array index; if the array is empty, it throws the exception and returns the null value if the array value is empty. The function parameter is a must for the function invoked and each subsequent data element on the group. The data is to be key-value pair formats like a map it associates with the key of each type of group with the formatted results of accumulating the group elements on the stack memory because the method performs the operation that is related to the memory areas for storing the complex values into the single set format values.
Examples of Kotlin reduceGiven below are the examples:
Example #1Code:
import kotlin.collections.* fun main() { val x = listOf(12,34,56,78,90,627, 54,56,65324,65,62145) println("Have a Nice Day users its the first example regarding the reduce() "+y) println("Thank you users for spenting the time please try again "+z) val ab = listOf("First", "Welcome", "To", "My","Domain") val ef = listOf("second", "Please", "Try", "Again","Have", "A", "Nice", "Day", "Users","123","456","789") }Output:
In the above example, we used some collection with the reduce() method to reduce the lines from left to right. Currently, the reduce() method converts the values like integer numbers into the single set of values stored on the variable.
Example #2Code:
import kotlin.collections.* try { val p = intArrayOf(11, 22, 33, 44, 55, 66, 77, 88, 99) println(p.sum()) var x = 0 p.forEach { x += it } println(x) val vars = 11/ 0 println(vars) } catch (ex: ArithmeticException) { println(ex) } finally { println("If above two blocks are not executing means the finally block will execute") } println("This is a Second Example") var w: String = "Welcome To My Domain its a Second Example for to use the reduce() method in Kotlin java library" println("Have a Nice Day users : $w") var u: String? = "Thank you for choosing our application Please try again" println("Its a Second variable $u") u = null println("If the variable is going to be null : $u") }Output:
Example #3Code:
package one val example1: Int = 33 val example2: Int = 53 val sum = example1 + example2 println("The sum is: $sum") val example3 = listOf("first", "second", "third", "four", "five", "six", "seven", "eight", "nine", "ten") val example4 = example3.groupingBy { it.first() } }) val example5 = example4.values.sortedBy { it.first } println(example5) val example6 = listOf("first", "second", "third", "four", "five", "six", "seven", "eight", "nine", "ten") val example7 = example3.groupingBy { it.first() } println(example7) val nums = listOf(44, 45, 43, 22, 11, 72, 61, 83, 94) mp.put(1, "siva") mp.put(2, "raman") mp.put(3, "welcome") mp.put(4, "users") mp.put(5, "have") mp.put(6, "a") mp.put(7, "nice") mp.put(8, "day") val akeys = ArrayList(mp.keys) val avalues = ArrayList(mp.values) println("Your input keys are : $akeys") println("Your input values are: $avalues") val y = listOf("four", "five", "six", "second", "first", "seven", "eight", "nine", "ten") println(res) }Output:
In the final example, we used the collection concepts like list and map and converted the map values to the list collection. Here we used to reduce() and reduceRight() methods for reducing the code lines from left to right and right to left.
ConclusionIn the kotlin language, we used some default methods, keywords, and variables, which regarding the separate packages, include classes and methods. For that, the reduce() and other similar methods are the default methods for reducing the datas into a single set in the collections, util, and other default packages, which depend on the user requirement.
Recommended ArticlesWe hope that this EDUCBA information on “Kotlin reduce” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
How Pyspark To_Date Works In Pyspark?
Introduction to PySpark to_Date
PySpark To_Date is a function in PySpark that is used to convert the String into Date Format in PySpark data model. This to_Date function is used to format a string type column in PySpark into the Date Type column. This is an important and most commonly used method in PySpark as the conversion of date makes the data model easy for data analysis that is based on date format. This to_Date method takes up the column value as the input function and the pattern of the date is then decided as the second argument which converts the date to the first argument. The converted column is of the type pyspark.sql.types.DateType .
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
In this article, we will try to analyze the various ways of using the PYSPARK To_Date operation PySpark.
Syntax:
from pyspark.sql.functions import * df2 = df1.select(to_date(df1.timestamp).alias('to_Date')) df.show()The import function in PySpark is used to import the function needed for conversion.
Df1:- The data frame to be used for conversion
To_date:- The to date function taking the column value as the input parameter with alias value as the new column name.
Df2:- The new data frame selected after conversion.
Screenshot:
Working of To_Date in PySparkLet’s check the creation and working of PySpark To_Date with some coding examples.
ExamplesLet’s start by creating a simple data frame in PySpark.
df1=spark.createDataFrame( data = [ ("1","Arpit","2023-07-24 12:01:19.000"),("2","Anand","2023-07-22 13:02:20.000"),("3","Mike","2023-07-25 03:03:13.001")], schema=["id","Name","timestamp"]) df1.printSchema()Output:
df1.show()Screenshot:
Now we will try to convert the timestamp column using the to_date function in the data frame.
We will start by importing the required functions from it.
from pyspark.sql.functions import *This will import the necessary function out of it that will be used for conversion.
df1.select(to_date(df1.timestamp).alias('to_Date'))We will start by selecting the column value that needs to be converted into date column value. Here the df1.timestamp function will be used for conversion. This will return a new data frame with the alias value used.
Screenshot:
df1.select(to_date(df1.timestamp).alias('to_Date')).collect()We will try to collect the data frame and check the converted date column.
[Row(to_Date=datetime.date(2023, 7, 24)), Row(to_Date=datetime.date(2023, 7, 22)), Row(to_Date=datetime.date(2023, 7, 25))] df2 = df1.select(to_date(df1.timestamp).alias('to_Date'))This will convert the column value to date function and the result is stored in the new data frame. which can be further used for data analysis.
df2.show()Let us try to check this with one more example giving the format of the date before conversion.
df = spark.createDataFrame([('2023-07-19 11:30:00',)], ['date'])This is used for creation of Date frame that has a column value as a date which we will use for conversion in which we can pass the format that can be used for conversion purposes.
df.select(to_date(df.date, 'yyyy-MM-dd HH:mm:ss').alias('date')).collect()This converts the given format into To_Date and collected as result.
Screenshot:
This to date function can also be used with PySpark SQL function using the to_Date function in the PySpark. We just need to pass this function and the conversion is done.
spark.sql("select to_date('03-02-2023','MM-dd-yyyy') converted_date").show()This is the converted date used that can be used and this gives up the idea of how this to_date function can be used using the chúng tôi function.
Screenshot:
spark.sql("select to_date('2023-04-03','yyyy-dd-MM') converted_date").show()Screenshot:
These are some of the Examples of PySpark to_Date in PySpark.
Note:
1. It is used to convert the string function into Date.
2. It takes the format as an argument provided.
3. It accurately considers the date of data by which it changes up that is used precisely for data analysis.
4. It takes date frame column as a parameter for conversion.
ConclusionFrom the above article, we saw the working of TO_DATE in PySpark. From various example and classification, we tried to understand how this TO_DATE FUNCTION ARE USED in PySpark and what are is used in the programming level. The various methods used showed how it eases the pattern for data analysis and a cost-efficient model for the same.
Recommended ArticlesWe hope that this EDUCBA information on “PySpark to_Date” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
How Switch Component Works In React
Introduction to React-Native Switch
React-Native Switch is a component controlled by Boolean which assigns its value to true or false. To update the value prop in respect of the component to reflect user actions, on Value Change callback method of React-Native Switch is used. If there is no update in the valueprop the component won’t be able to give the expected result for user action instead it will continuously provide the supplied value. The props of the Switch are disabled, trackColor, ios_backgroundColor, onValueChange, testID, thumbColor, tintColor, value. The major used props of the Switch are on Value Change (invoked with the change in switch value) and value (switchvalue).
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
import { Switch} from 'react-native' <Switch onValueChange={ (value) =? this.setState({ toggled: value })} value={ this.state.toggled }Syntax to use Render in the Switch:
How Switch Component works in React-Native?The working of switch component in react native is defined in the following steps:
Step 1: For logic, HomeContainer component is used, and in the code below presentational component is created with the help of new file SwitchExample.js.
Step 2: To toggle switch items in SwitchExamplecomponent, the value has been passed from the state and functions. For updating the state Toggle functions are used. Switch component takes two props. When a user presses the switch, the onValueChange prop will trigger the toggle functions. To the state of the HomeContainer component, the value prop is bounded. If Switch is pressed, the state will be updated and one can check the values in the console, before that values bounded to default.
Logic and Presentation of Switch in the ApplicationGiven below is the coding for logic and presentation of switch in the application:
Code:
import React, { Component } from 'react' import {StyleSheet, Switch, View, Text} from 'react-native' export default class SwitchExample extends Component { state = { switchValue: false }; render() { return ( <Switch value={this.state.switchValue} onValueChange ); } } const styles = StyleSheet.create({ container:{ flex:1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#96f2ca', }, textStyle:{ margin: 25, fontSize: 24, fontWeight: 'bold', textAlign: 'center', color: '#3a4a35' } })Output:
Examples of React Native SwitchGiven below are the examples:
Example #1React Native Switch.
In the example below, initially the Switch value is set to “FALSE” and display TEXT with “OFF”. When there is change of the value of Switch to “TRUE” by calling onValueChange the component of TEXT will reset to“ON”.
import React from 'react'; import { Switch ,Text ,View , StyleSheet } from 'react-native'; export default class App extends React.Component{ state = { switchValue: false }; }; render() { return ( <Switch style={{ marginTop: 31 }} onValueChange={this.toggleSwitch} value={this.state.switchValue} ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#edb5ff', }, });Output:
Example #2Using Switch Case Statement in React Native.
Code:
import React, { Component } from 'react'; import { Platform, StyleSheet, View, TextInput, TouchableOpacity, Alert, Text } from 'react-native'; export default class App extends Component { constructor(){ super(); this.state={ TextInput_Data : '' } } case '1': this.ONE(); break; case '2': this.TWO(); break; case '3': this.THREE(); break; case '4': this.FOUR(); break; default: Alert.alert("NUMBER NOT FOUND"); } } Alert.alert("ONE"); Alert.alert("TWO"); } Alert.alert("THREE"); } Alert.alert("FOUR"); } render() { return ( <TextInput placeholder="Enter Value Here" keyboardType = {"numeric"} ); } } const styles = StyleSheet.create({ MainContainer: { flex: 1, paddingTop: (Platform.OS) === 'ios' ?20 : 0, justifyContent: 'center', alignItems: 'center', backgroundColor: '#f6ffa6', marginBottom: 20 }, textInputStyle: { height: 40, width: '90%', textAlign: 'center', borderWidth: 1, borderColor:'#033ea3', borderRadius: 8, marginBottom:15 }, button: { width: '80%', padding: 8, backgroundColor:'#7a53e6', borderRadius:5, justifyContent: 'center', alignItems:'center' }, TextStyle:{ color:'#ffffff', textAlign:'center', } });Output:
Example #3Customisable Switch Component for React Native.
import React, { Component } from 'react'; import { StyleSheet ,Text ,View , Switch , Alert } from 'react-native'; export default class App extends Component { constructor() { super(); this.state = { SwitchOnValueHolder: false } } SwitchOnValueHolder: value }) if (value == true) { Alert.alert("You have truned ON the Switch."); } else { Alert.alert("You have turned OFF the Switch."); } } render() { return ( <Switch ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#afff63', }, text: { fontSize: 19, color: '#000000', }, });Output:
Below image shows the window that will appear when Switch is turned ON and Switch is turned OFF respectively.
When Switch is in ONstate:
When Switch is in OFFstate:
ConclusionHere we got to know that the Switch value can be set to ON when the value prop is set to TRUE and the Switch value can be set to OFF when the valueprop is set to FALSE which is also the default value of valueprop. We have also seen the working of the Switch in React-Native from creating a file then to logic then finally to presentation. We also got to know about how to develop a simple switch, developing switch using a switch case statement and also developing a customizable switch. In React-Native switch can be developed very easily and very efficiently.
Recommended Articles
This is a guide to React-Native Switch. Here we discuss the introduction, how switch component works in react-native and examples. You may also have a look at the following articles to learn more –
How Find_In_Set() Function Works In Mysql?
Introduction to MySQL FIND_IN_SET()
MySQL FIND_IN_SET() function is a built-in MySQL string function responsible for discovering the position of a given specific string provided in a list of strings separated by a comma. The FIND_IN_SET() function accepts two arguments that allow matching the first value with the second one containing a list of values as substrings separated by a comma character.
Start Your Free Data Science Course
Hadoop, Data Science, Statistics & others
Generally, the FIND_IN_SET() function applies to any field in the database table with a sequence of values differentiated by a comma. The user wants to compare those values with a specific single value. It thus returns the index of the matched string within the list.
SyntaxFollowing is the syntax structure that illustrates the use of the FIND_IN_SET() function in the MySQL server:
FIND_IN_SET(string1, stringlist);
The initial parameter named string1 defines the string which you need to find.
The next parameter, “stringlist,” represents the list of strings that must be examined, and commas separate these strings.
According to the value of the function arguments, the MySQL FIND_IN_SET() will return the value as an integer or a NULL:
If either function’s parameters, i.e., string1 or stringlist, have a NULL value, the function results in a NULL value.
The function will return zero if the stringlist is empty or if the string1 parameter is not found in the stringlist.
The function returns a positive integer value if the string1 parameter is available in the stringlist.
But note that if the string1 consists of a comma(,), the FIND_IN_SET() function performs poorly on execution. If the string1 parameter is a constant string and the stringlist parameter represents a SET column type, the MySQL server will optimize using bit arithmetic.
How does the FIND_IN_SET() function works in MySQL?MySQL consists of many databases, and each database comprises different tables. Tables in MySQL store data in various data types supported by MySQL, and the most commonly used types are integers and strings.
When a MySQL user wants to find out if a specific string exits in any of certain sequences of strings divided by a comma(,) symbol aimed for any query execution, then the built-in MySQL string function FIND_IN_SET() can be applied.
This function provides the required value depending on the search results. For example, suppose we are illustrating the following query to show how the function works in MySQL:
We will search a substring h within a list of strings using the statement below,
SELECT FIND_IN_SET("h", "g,h,k,l");We use the SELECT statement with the FIND_IN_SET() function to evaluate and display the return value. The result from the above query is true as the first parameter, ‘h’ is present in the list as the second parameter. So, Upon execution, the function will produce a positive integer, specifically 2. This is because the first value of the FIND_IN_SET() function is found in the second index of the list of values provided in the function’s second parameter, which is ‘g,h,k,l’.
Similarly, if we take the below query, then the function returns 0 as the output value as the value is not in the list:
SELECT FIND_IN_SET("b", "g,h,k,l");Also, when we define the query as follows then, the output is NULL as the second parameter is NULL:
SELECT FIND_IN_SET("h", NULL);Thus, we can define the position of a string within a particular list of substrings provided by the database tables.
Conversely, the MySQL IN operator takes any number of arguments to show if a value matches any value in a set.
Examples of MySQL FIND_IN_SET()Let us demonstrate some examples using the MySQL FIND_IN_SET() as follows:
Example #1Example to fetch data from a table by MySQL FIND_IN_SET() function:
Suppose we have a table named collection created in our database using the query below:
CREATE TABLE IF NOT EXISTS Collection (ColID INT AUTO_INCREMENT PRIMARY KEY, ColName VARCHAR(255) NOT NULL, Subjects VARCHAR(255) NOT NULL);Also, let us enter a few record rows into the Collection table created:
INSERT INTO Collection (ColName, Subjects) VALUES('o-1','Computers, Maths, Science'),('o-2','Networks, Maths, MySQL'),('o-3',' Computers, English, Data Science'),('o-4','Electric, Maths, Science'),('o-5','Computers, MySQL, English'),('o-6','Science, Web Design'),('o-7','Maths, Science'),('o-8','MySQL, Web Design'),('o-9','Computers');Displaying the contents of the table as follows:
SELECT * FROM Collection;Now, we will find the collection that will accept the Maths subject using the MySQL function FIND_IN_SET() shown below:
SELECT ColName, Subjects FROM Collection WHERE FIND_IN_SET('Computers', Subjects);Output:
Looking for a simple example and its output as follows:
SELECT FIND_IN_SET('h', 'g,h,k,l');Output:
The FIND_IN_SET() function provides the position of the first argument ‘h’ as found in the sequence of values as the second argument of the function.
Example #2Example showing Negativity of MySQL FIND_IN_SET() function:
Considering the previous table, the result value of the function will be empty when MySQL returns false. This occurs when the substring specified in the first argument is not found in the list of values provided as the second argument. Thus, we will apply the MySQL NOT operator to negate the MySQL function FIND_IN_SET(). Finally, we will illustrate the query example with FIND_IN_SET() function using the NOT operator also to search the collection that does not match the PHP subject in the table values:
SELECT ColName, Subjects FROM Collection WHERE FIND_IN_SET('PHP', Subjects);As you can see, no output is produced as a collection because, in the list of values from column Subjects, the FIND_IN_SET() function has not found any matched substring as given in the first argument.
Example #3Difference between IN operator and FIND_IN_SET():
The IN operator defines whether a substring matches any substring set or list and can accept any number of arguments parted by a comma as follows:
SELECT ColName, Subjects FROM Collection WHERE ColName IN ('o-1', 'o-2', 'o-5', 'o-6');Output:
Similarly, using the FIND_IN_SET() will result in the identical output as IN query but takes only two parameters to show a match of value with a list of values divided by a comma:
SELECT ColName, Subjects FROM Collection WHERE FIND_IN_SET(ColName, 'o-1,o-2,o-5,o-6');Output:
ConclusionMySQL FIND_IN_SET() function allows a server to check if a substring as the first argument is present in the list of values composed of substrings in the second argument parted by a comma.
This function, when the value is searched, returns the results based on those values as a positive integer as position(if the value exists in the list), zero(if value not found) or NULL(if any argument is NULL), which can be helpful for MySQL operations at the admin level.
Recommended ArticlesWe hope that this EDUCBA information on “MySQL FIND_IN_SET()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
How Nullif Function Works In Postgresql?
Definition of PostgreSQL NULLIF
PostgreSQL nullif is a common conditional expression used to handle null values or expressions in PostgreSQL. nullif is also used with the coalesce function to handle the null values. PostgreSQL nullif function returns a null value if provided expressions are equal. If two expressions provided are equal, then it provides a null value; as a result, otherwise, it will return the first expression as a result.
Start Your Free Data Science Course
Syntax:
Below is the syntax of the nullif function as follows.
Select (Argument1 (First value which is used to handle null values), Argument2 (Second value which is used to handle null values)) SELECT Column1, …, ColumnN COALESCE ( NULLIF (Column_name, ''), ) FROM table_name;Parameter:
Select: In PostgreSQL, you can use the NULLIF function with the SELECT statement to fetch data from a table while handling null values or expressions. We can use multiple columns or a single column at one time to fetch data from the table.
Coalesce: Coalesce states that function name in PostgreSQL, which returns as a first non-null value. Coalesce function is essential and useful in PostgreSQL.
We have used coalesce function with nullif function in PostgreSQL.
Argument 1 to Argument 2: Argument is nothing but an integer or character value that we have passing with nullif function. If we have passing two-argument and both contain a different value, then the nullif function will return the first value in a result. If we have to pass both the same values, then it will return a null value as a result.
Column 1 to Column N: This is the table’s column name. If we want to fetch data from a table using nullif function in PostgreSQL, we pass multiple columns simultaneously. Also, we have given the column name with the nullif function in PostgreSQL.
From: In PostgreSQL, you can retrieve data from the keyword FROM with the table name in a SELECT query.
Table name: Table name used with nullif function to fetch data from a table.
Nullif: It is used to handle null values in PostgreSQL; nullif is also used with the coalesce function to handle the null values. nullif function returns a null value if provided expressions are equal; if provided two expressions are equal, then it provides a null value; otherwise, it will return the first expression as a result.
How does NULLIF Function work in PostgreSQL?Below is the working of nullif function in PostgreSQL.
We can use the coalesce function with nullif function in PostgreSQL. Coalesce states that the function name in PostgreSQL which returns as first non-null value as a result. Coalesce function is essential and useful in PostgreSQL.
In PostgreSQL, you can use the common conditional expression NULLIF to handle null values or expressions.
If we have passing two nullif function arguments and the first contains a null value, then the nullif function will return the first value in a result. If we pass both the same value, it will return a null value in a result.
We have used the nullif function in PostgreSQL to prevent the division error by zero.
In PostgreSQL, you can use the nullif function to prevent errors that may occur when comparing two values.
ExamplesBelow is an example of nullif function.
We have using a discount table to describe an example of the nullif function as follows.
Below is the data description of the discount table, which we have used to describe an example of nullif function.
Example #1 testing=# select * from discount;Output:
Example #2In the below example, we have passing values like 50 and 50. The nullif function will return null values because both the arguments which we have passing are the same.
testing=# select nullif (50, 50);In the above example, we pass the same argument with the nullif function so that it will return the null value as a result.
Example #3In the below example, we have passing values as 50 and 100. Nullif function will return the first value, i.e., 50 because both the arguments which we have passing are different.
testing=# select nullif (50, 100);Output:
In the above example, we have a different passing argument with the nullif function so that it will return the first value as a result.
Example #4 testing=# select nullif ('A', 'P');Output:
In the above example, we have a passing different argument with the nullif function so that it will return the first value as a result.
Example #5In the below example, we have to retrieve data from a discount table using the nullif function.
testing=# SELECT cust_id, product_name, COALESCE ( NULLIF (Product_price, '')) AS Product_price FROM discount;Output:
Recommended ArticlesWe hope that this EDUCBA information on “PostgreSQL NULLIF” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Update the detailed information about How Delegate Works In Kotlin on the Minhminhbmm.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!