SQL is a computer programming language used for querying relational databases. Data retrieval from data base is done through appropriate and efficient use of SQL.
SQL is a computer programming language used for querying relational databases. Data retrieval from data base is done through appropriate and efficient use of SQL.
SQL is a computer programming language used for querying relational databases. Data retrieval from data base is done through appropriate and efficient use of SQL.
Retrieving data using the SQL Select StatementSQL is a comprehensive database lan
guage. SQL, pronounced Sequel or simply S-Q-L, is a computer programming languag
e used for querying relational databases following a nonprocedural approach. Whe n you extract information from a database using SQL, this is termed querying the database.A relational database is implemented through the use of a Relational D atabase Management System (RDBMS). An RDBMS performs all the basic functions of the DBMS software mentioned above along with a multitude of other functions that make the relational model easier to understand and to implement. RDBMS users ma nipulate data through the use of a special data manipulation language. Database structures are defined through the use of a data definition language. The comman ds that system users execute in order to store and retrieve data can be entered at a terminal with an RDBMS interface by typing the commands, or entered through use of some type of graphical interface. The DBMS then processes the commands.C apabilities of the SELECT StatementData retrieval from data base is done through appropriate and efficient use of SQL. Three concepts from relational theory enc ompass the capability of the SELECT statement: projection, selection, and joinin g.Projection: A project operation selects only certain columns (fields) from a t able. The result table has a subset of the available columns and can include any thing from a single column to all available columns.Selection: A select operatio n selects a subset of rows (records) in a table (relation) that satisfy a select ion condition. The ability to select rows from out of complete result set is cal led Selection. It involves conditional filtering and data staging. The subset ca n range from no rows, if none of the rows satisfy the selection condition, to al l rows in a table.Joining: A join operation combines data from two or more table s based on one or more common column values. A join operation enables an informa tion system user to process the relationships that exist between tables. The joi n operation is very powerful because it allows system users to investigate relat ionships among data elements that might not be anticipated at the time that a da tabase is designed.Consider the above table structures. Fetching first_name name , department_id and salary for a single employee from EMPLOYEES table is Project ion. Fetching employee details whose salary is less than 5000, from EMPLOYEES ta ble is Selection. Fetching employee's first name, department name by joining EMP LOYEES and DEPARTMENTS is Joining.Basic SELECT statementThe basic syntax for a S ELECT statement is presented below.SELECT [DISTINCT | ALL] {* | select_list} FROM {table_name [alias] | view_name} [{table_name [alias] | view_name}]... [WHERE condition] [GROUP BY condition_list] [HAVING condition] [ORDER BY {column_name | column_# [ ASC | DESC ] } ...The SELECT clause is manda tory and carries out the relational project operation.The FROM clause is also ma ndatory. It identifies one or more tables and/or views from which to retrieve th e column data displayed in a result table.The WHERE clause is optional and carri es out the relational select operation. It specifies which rows are to be select ed.The GROUP BY clause is optional. It organizes data into groups by one or more column names listed in the SELECT clause.The optional HAVING clause sets condit ions regarding which groups to include in a result table. The groups are specifi ed by the GROUP BY clause.The ORDER BY clause is optional. It sorts query result s by one or more columns in ascending or descending order.Arithmetic expressions and NULL values in the SELECT statementAn arithmetic expression can be creaeted using the column names, operators and constant values to embed an expression in a SELECT statement. The operator applicable to a column depends on column's dat a type. For example, arithmetic operators will not fit for character literal val ues. For example,SELECT employee_id, sal * 12 ANNUAL_SAL FROM employees;The above query contains the arithmetic expression (sal * 12) to calculate annual salary of each employee.
DEBARUN.12341 23 hour(s) ago
Arithmetic operatorsOperators act upon the columns (known as operands) to result into a different result. In case of multiple operators in an expression, the or der of evaulation is decided by the operator precedence. Here are the elementary rules of precedence -Multiplication and division occur before multiplication an d division.Operators on the same priority are evaluated from left to right.Use p aretheses to override the default behavior of the operators.Below table shows th e precedence of the operators, in such cases. Precedence Level Operator Symbol O perationDescription Operator Precedence Addition + Lowest Subtraction Lowest Multiplication * Medium Division / Medium Brackets ( ) Highest Examine the below queries (a), (b), and (c)SQL> SELECT 2*35 FROM DUAL;SQL> SELECT salary + 1500 FROM employees;SQL> SELECT first _name, salary, salary + (commission_pct* salary) FROM employees;Query (a) multip lies two numbers, while (b) shows addition of $1500 to salaries of all employees . Query (c) shows the addition of commission component to employee's salary. As per the precedence, first commission would be calculated on the salary, and then added to the salary.Column AliasAn alias is used to rename a column or an expre ssion during display. The alias to a column or an expression appears as the head ing in the output of a query. It is useful in providing a meaningful heading to long expressions in the SELECT query. By default, the alias appears in uppercase in the query output without spaces. To override this behavior, alias must be en closed within double quotes to preserve the case and spaces in the alias name.SE LECT price * 2 as DOUBLE_PRICE, price * 10 "Double Price" FROM products; DOUBLE_PRICE Double Price ----------------------39.9 39.9 60 60 51.98 51.98Concatenation operatorsConcatenation operator can be used to join t wo string values or expressions in a SELECT query. The double vertical bar symbo l is used as string concatenation operator. It is applicable only for character and string column values resulting into a new character expression. ExampleSQL> SELECT 'ORACLE'||' CERTIFICATION' FROM dual;The above query shows concatenation of two character literals values.LiteralsAny hard coded value, which is not stor ed in database, in the SELECT clause, is known s Literal. It can be number, char acter, or date value. Character and date values must be enclosed within quotes. Consider the below SQL queries.examples of using literals of different data type s in SQL queries.The query below uses two character literals to join them togeth er.SQL> SELECT 'ORACLE'||' CERTIFICATION' FROM DUALThe query below uses characte r literals to pretty print the employee's salary.SQL> SELECT first_name ||'earns '|| salary||' as of '|||sysdate FROM employeesQuote OperatorThe quote operator is used to specify the quotation mark delimiter of your own. You can chose a convenient delimiter, depedning on t he data.SELECT department_name|| ' Department' ||q'['s Manager Id: ]'|| manager_ id FROM departments;NULLIf a column doesn't has a definite value, it is considered as NULL. NULL value denotes unknown or unavailable. It is not zero for numeric v alues, not blank space for character values.Columns with NULL value can be selec ted in a SELECT query and can be the part of an arithmetic expression. Any arith metic expression using NULL values results into NULL. For this reason, columns w ith NULL value must be handled differently by specifying their alternate values using Oracle supplied functions like NVL or NULLIF.SQL> SELECT NULL + 1000 NUM FROM DUAL; NUM
--------
DEBARUN.12341 23 hour(s) ago
DISTINCT KeywordIf the data is expected to have duplicate results, use DISTINCT keyword to eliminate duplicates and diplay only the unique results in the query output. Only the selected columns are validated for duplication and the rows wil l be logically eliminated from the query output. To be noted, the DISTINCT keywo rd must appear just after the SELECT clause.The simple query below demonstrates the use of DISTINCT to display unique department ids from EMPLOYEES table.SQL> S ELECT DISTINCT DEPARTMENT_ID FROM employees; DEPARTMENT_ID --------------10 20 30 40DESCRIBE command The structural metadata of a table may be obtained by querying the database for the list of columns that comprise it using the DESCRIBE command. It will list the used column names, their null property and data type. Syntax:DESC[RIBE] [SCHEMA].object nameFor example,DESC EMPLOYEEwill display the EMPLOYEE table structure i.e. columns, their data types, precision and nullable property.
DEBARUN.12341 22 hour(s) ago
Restricting and Sorting Data The essential capabilities of SELECT statement are Selection, Projection and Joi ning. Displaying specific columns from a table is known as a project operation. We will now focus on displaying specific rows of output. This is known as a select operation. Specific rows can be selected by adding a WHERE clause to a SELECT query. As a m atter of fact, the WHERE clause appears just after the FROM clause in SELECT query hierarchy. The sequence has to be maintained in all scenarios. If violated, Oracle raises an exception. Syntax:SELECT *|{[DISTINCT] column| expression [alias],..} FROM table [WHERE condition(s)]In the syntax,WHERE clause is the keyword[condition] contain s column names, expressions, constants, literals and a comparison operator.Suppose that your manager is working on the quarterly budge t for your organization. As part of this activity, it is necessary to produce a listing of each employee's essential details, but only f or employees that are paid at least $25,000 annually. The SQL query below accomplishes this task. Note the use of the WHERE clause sh own in bold text.SELECT Employee_ID, Last_Name, First_Name, Salary FROM employees WHERE Salary >= 25000;
EMPLOYEE_ID LAST_NAME FIRST_NAME SALARY
---------- --------------- --------------- ----------88303 Jones Quincey $30,550.00 88404 Barlow William $27,500.00 88505 Smith Susan $32,500.00 3 rows selected Points to be noted -A SELECT clause can contain only one WHERE c lause. However, multiple filter conditions can be appended to WHERE clause using AND o r OR operator.The columns, literals or expressions in a predicate clause must be of s imilar or interconvertible data types.Column alias cannot be used in the WHERE clause. Character literals must be enclosed within single quotation marks and are case s ensitive. Date literals must be enclosed within single quotation marks and are format sens itive. Default format is DD-MON-RR.Comparison OperatorsComparison operators are used in predicates to compare one term or operand with another term. SQL offers comprehensive set of equality, inequality and miscellaneous operators. They can be used depending on the data and filter condition logic in the SELECT query. When you use comparison operators in a WHE RE clause, the arguments (objects or values you are comparing) on both sides of the operat or must be either a column name, or a specific value. If a specific value is used, then the value must be either a numeric value or a literal string. If the value is a character string or date , you must enter the value within single quotation marks (' ').Oracle has nine comparison operat ors to be used in equality or inequality conditions.Operator Meaning = equal to < less than > greater than >= greater than or equal to <= less than or equal to != not equal to <> not equal to !> not greater than !< not less than Other Oracle operators are BETWEEN..AND, IN, LIKE, and IS NULL.
DEBARUN.12341 22 hour(s) ago
The BETWEEN Operator The BETWEEN operator can be used to compare a column value within a definite ran ge. The specified range must have a lower and upper limit where both are inclusive d uring comparison. Its use is similar to composite inequality operator (<= and >=). It can be used
with numeric, character and date type values.
For example, the WHERE condition SALARY BETWEEN 1500 AND 2500 in a SELECT query will list those employees whose salary is between 1500 and 2500.