I have this mysql code:
SELECT firstname, lastname, age, gender from persons WHERE id = 1;
Display:
> firstname: Marlon
>
> lastname: Null
>
> age: 26
>
> gender: male
What I want to do is:
SELECT IF NULL DONT SELECT(firstname), IF NULL DONT SELECT(lastname), IF NULL DONT SELECT(age), IF NULL DONT SELECT(gender) from persons WHERE id = 1;
Display:
> firstname: Marlon
>
> age: 26
>
> gender: male
lastname didn't display because its null
Below is the syntax to filter the rows without a null value in a specified column. Syntax: SELECT * FROM <table_name> WHERE <column_name> IS NOT NULL; Example: SELECT * FROM demo_orders WHERE ORDER_DATE IS NOT NULL; --Will output the rows consisting of non null order_date values.
MySQL IS NOT NULL condition is used to check the NOT NULL value in the expression. It is used with SELECT, INSERT, UPDATE and DELETE statements. Syntax: expression IS NOT NULL.
To display records without NULL in a column, use the operator IS NOT NULL. You only need the name of the column (or an expression) and the operator IS NOT NULL (in our example, the price IS NOT NULL ).
The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
Certainly you can't do that; rather you can use COALESCE()
or IFNULL()
function to provide a default value in case of NULL
like
SELECT firstname,
COALESCE(lastname,'N/A'),
age,
gender from persons WHERE id = 1;
(OR) if you want to remove that record completely then use a WHERE
condition like
SELECT firstname, lastname, age, gender from persons
WHERE id = 1 AND lastname IS NOT NULL;
even there is no way to hide column but yes you can avoid null value in output. So there can be below 2 ways-
Method 1: You can keep field blank where it is null.
SELECT IFNULL(firstname,'') AS firstname,
IFNULL(lastname,'') AS lastname,
IFNULL(age,'') AS age,
IFNULL(gender,'') AS gender
FROM persons WHERE id = 1;
Method2: You can get all values in single column using concatenate function.
SELECT CONCAT
(
IFNULL(firstname,''),' ',
IFNULL(lastname,''),' ',
IFNULL(age,''),' ',
IFNULL(gender,'')
)
FROM persons WHERE id = 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With