SQL Filtering and Subqueries
SQL Filtering and Subqueries
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
• We can order by columns not present in the select statement, as long as they're present in the table
• The order by can also be a custom expression that can be calculated for each row, it need not be a static column in the table, order by can also be
a number (1,2,3...) which indicates the column on which we need to sort (this positive number should be <= number of columns selected after
SELECT)
This indicates sort by the 1st column after select which in this case is name
This gives error as enough number of columns are not present after select
This sorts by dept
Sorting by any other value (-1, -2, -100, 'adasd', '') sorts the output by the primary key
The clause id='10' is executed for each row in the backend and a boolean mask of [True, False, True, True …] is generated
Then all the rows which have the True mask are returned
(similar to how pandas work in filtering)
To get nothing
• MySQL is not case sensitive with strings but other SQLs can be
•
• BETWEEN:
○ Both start and end are included
○ Can also work on strings:
• LIKE:
○ You can use LIKE with numbers/floats along with strings
○ You can't use like with multiple strings (as we can do with IN operator)
○ Like/= operators can't operator on NULL operator
• Inner queries
After IN, the selected column's name need not be the same as that before IN
It only checks for the values
• CASE
Syntax:
CASE
WHEN <bool_condition_1> THEN <value_to_be_present_when_bool_condition_1_is_true>
WHEN <bool_condition_2> THEN <value_to_be_present_when_bool_condition_2_is_true>
WHEN <bool_condition_3> THEN <value_to_be_present_when_bool_condition_3_is_true>
...
ELSE <value_to_be_present_when_all_bool_conditions_are_false>
END
If we don't mention an explicit ELSE statement, SQL will insert NULLs in place of ELSE
This Case statement will be applied to each row of the table and corresponding output will be generated
It is like IF-ELSE statement in Python