Learn MySQL for Developing Web Application

Learn to build web applications with PHP and MySQL, Start your own blog, e-commerce site. In this tutorial you will learn queries of MySQL and MySQLi.

SQL Expressions


An expression is a combination of one or more values, operators and SQL functions that evaluate to a value. These SQL EXPRESSIONs are like formulae and they are written in query language. You can also use them to query the database for a specific set of data.

Syntax

Consider the basic syntax of the SELECT statement as follows −

SELECT column1, column2, columnN
FROM table_name
WHERE [CONDITION|EXPRESSION];

There are different types of SQL expressions, which are mentioned below −

  • Boolean
  • Numeric
  • Date

Let us now discuss each of these in detail.


Boolean Expressions

SQL Boolean Expressions fetch the data based on matching a single value. Following is the syntax −

SELECT column1, column2, columnN
FROM table_name
WHERE SINGLE VALUE MATCHING EXPRESSION;

Consider the EMPLOYEES table having the following records −

SQL> SELECT * FROM EMPLOYEES;
ID NAME AGE ADDRESS SALARY
1 Ravi 30 Delhi 18000
2 Pawan 26 Pune 20000
3 Jignesh 28 Surat 22000
4 Vikram 25 Mumbai 25000
5 Shilpa 24 Kolkata 12000
6 Hardik 28 Chennai 20000
7 rows in set (0.00 sec)

The following table is a simple example showing the usage of various SQL Boolean Expressions −

SQL> SELECT * FROM EMPLOYEES WHERE SALARY = 20000;
ID NAME AGE ADDRESS SALARY
6 Hardik 28 Chennai 20000
1 row in set (0.00 sec)

Numeric Expression

These expressions are used to perform any mathematical operation in any query. Following is the syntax −

SELECT numerical_expression as OPERATION_NAME
[FROM table_name
WHERE CONDITION] ;

Here, the numerical_expression is used for a mathematical expression or any formula. Following is a simple example showing the usage of SQL Numeric Expressions −

SQL> SELECT (15 + 6) AS ADDITION
ADDITION
21
1 row in set (0.00 sec)

There are several built-in functions like avg(), sum(), count(), etc., to perform what is known as the aggregate data calculations against a table or a specific table column.

SQL> SELECT COUNT(*) AS "RECORDS" FROM EMPLOYEES;
RECORDS
6
1 row in set (0.00 sec)

Date Expressions

Date Expressions return current system date and time values −

SQL> SELECT CURRENT_TIMESTAMP;
Current_Timestamp
2017-7-12 12:21:25
1 row in set (0.00 sec)

Another date expression is as shown below −

SQL> SELECT GETDATE();
GETDATE
2017-7-12 12:25:29.122
1 row in set (0.00 sec)