Having and Alias Clause in MySQL


Having Clause

We know that the WHERE clause is used to restrict the records in a query. But if we want to restrict the records by using the Aggregate function then we have to use the HAVING clause. The HAVING clause restricts the records after they have been grouped.

img-1.gif

We add an ordinary WHERE clause to the SQL statement.

Example :
 The following example shows the list of all Clients name who got the salary more than 126 on average.

img-2.gif

Alias Clause :

An alias is a good thing to do if we have very long or complex table names or column names. An alias is creating using the term AS followed by a case-sensitive string. Alias can be used in a query select list to give a column a different name in the returned results. You can give a table or a column another name by using an alias. An alias name could be anything, but usually it is short.

To sort the output by alias:

img-3.gif

Aliasing the function in select statement:

Query :

SELECT first_name, start_date, CURDATE(),
(YEAR(CURDATE())-YEAR(start_date)) - (RIGHT(CURDATE(),5)<RIGHT(start_date,5))
AS YearServed
FROM employee ORDER BY YearServed;

img-4.gif

mysql> SELECT concat(First_Name, " ",Last_Name) AS Name FROM employee;

img-5.gif

When we have to join the tables, it's often the case that the tables contain columns with the same names. If we refer to such a column in the query, it's doubtful which table the column reference applies to. This uncertainly usually can be addressed by qualifying column names with table names. However, if we join a table to itself, even the table name is uncertain and it's necessary to use aliases to authorize table references.

Query : In SELECT query, output column names, by default, are the same as the column or expression selected. To rename a column, provide an alias following the column in the output list:

Output :

img-6.gif

Up Next
    Ebook Download
    View all
    Learn
    View all