SQL Expressions With Examples

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

SQL Expressions

SQL expression can be classified into following categories.

  1. Boolean
  2. Numeric
  3. Date

Let us try to understand the types of expression in detail with sample programs.

SQL Boolean Expression

SQL Boolean Expression fetches data based on the condition that is mentioned as part of the SQL query. It should fetch just single value when the query is executed. Its syntax is given below.

Let us try to understand Boolean expression using a sample table with some data.

EmpId EmpName EmpAge EmpSalary
1 John 32 2000
2 Smith 25 2500
3 Henry 29 3000

We will consider the Employee table mentioned above as an example.

Example Query:

The query above will result in single value which is “John” for our query. SQL Boolean expressions should be used with primary keys to make suer you always get only one results. This is required incase of nested SQL select queries.

Above query will return all the posts name and id where author name is Pankaj. Here nested SQL query should always return only one row otherwise you will get error message as Subquery returns more than 1 row.

SQL Numeric Expression

SQL Numeric Expression is used for performing mathematical operation in SQL query. Its syntax is as follows:

NUMERICAL_EXPRESSION is the mathematical formula for function which will be used in the SQL query.

Let’s try to understand Numeric expression using an example.

The query above will result as 3 because the COUNT(*) function will provide the total count of the rows based on the condition in WHERE clause. For example select count(*) from employee where empsalary > 2400; will return 2.

There are other functions also like sum(), avg(), min(), max() etc. These functions are used for mathematical operations. Let’s see some more example code snippets for SQL numeric expressions.

SQL Date Expression

SQL Date Expression results in datetime value.

Let’s try to understand Date expression with some sql statements.

The above queries will result in current time of the system. Note that every relational database vendor has specific methods to get current date and timestamp values, so there is a slight chance that one function in a database doesn’t work in another database.

That’s all for SQL expressions, we will use these a lot in later sql tutorials and programs.

Further Reading: SQL Data Types.

Reference: Oracle Documentation

By admin

Leave a Reply

%d bloggers like this: