Home » PL/SQL Variables
![](http://charunivedita.online/777/templates/cheerup2/res/banner1.gif)
PL/SQL Variables
Summary : in this tutorial, you will learn about PL/SQL variables that help you manipulate data in PL/SQL programs.
In PL/SQL, a variable is a meaningful name of a temporary storage location that supports a particular data type in a program. Before using a variable, you need to declare it first in the declaration section of a PL/SQL block .
PL/SQL variables naming rules
Like other programming languages, a variable in PL/SQL must follow the naming rules as follows:
- The variable name must be less than 31 characters. Try to make it as meaningful as possible within 31 characters.
- The variable name must begin with an ASCII letter. It can be either lowercase or uppercase. Notice that PL/SQL is case-insensitive, which means v_data and V_DATA refer to the same variable.
- Followed by the first character are any number, underscore ( _ ), and dollar sign ( $ ) characters. Once again, do not make your variables hard to read and difficult to understand.
PL/SQL variables naming convention
It is highly recommended that you should follow the naming conventions listed in the following table to make the variables obvious in PL/SQL programs:
v_ | VARCHAR2 |
n_ | NUMBER |
t_ | TABLE |
r_ | ROW |
d_ | DATE |
b_ | BOOLEAN |
Each organization has its own development naming convention guidelines. Make sure that you comply with your organization’s naming convention guidelines.
For example, if you want to declare a variable that holds the first name of the employee with the VARCHAR2 data type, the variable name should be v_first_name .
PL/SQL Variables Declaration
To declare a variable, you use a variable name followed by the data type and terminated by a semicolon ( ; ). You can also explicitly add a length constraint to the data type within parentheses. The following illustrates some examples of declaring variables in a PL/SQL anonymous block :
PL/SQL variable anchors
In PL/SQL program, one of the most common tasks is to select values from columns in a table into a set of variables. In case the data types of columns of the table changes, you have to change the PL/SQL program to make the types of the variables compatible with the new changes.
PL/SQL provides you with a very useful feature called variable anchors . It refers to the use of the %TYPE keyword to declare a variable with the data type is associated with a column’s data type of a particular column in a table.
Let’s take a look at the employees table in HR sample database provided by Oracle:
The v_first_name variable has a data type that is the same as the data type of the first_name column in the emloyees table . In case the data type of the first_name column changes, the type of the v_first_name variable automatically inherits the new data type of the column.
PL/SQL variable assignment
In PL/SQL, to assign a value or a variable to another, you use the assignment operator ( := ) which is a colon( : ) followed by the equal sign( = ).
Please see the code listing below to get a better understanding:
In the example above, we assigned Mary to v_first_name variable, Jane to v_last_name variable, and result of the to_date function to d_hire_date variable.
You can use INTO of the SELECT statement to assign a value to a variable. The INTO clause moves the values from the SELECT query’s column list into corresponding PL/SQL variables.
Initializing variables
When you declare a variable, its value is uninitialized and hence is NULL . You can initialize variable a value in declaration section by using variable assignment.
See the following example:
In PL/SQL, NULL means an unknown value so it has some special characteristics as follows:
- NULL is not equal to anything, even itself NULL .
- NULL is not greater than or less than anything else, even NULL .
- You cannot use logical operator equal ( = ) or ( <> ) with NULL . You must use the SQL IS NULL or IS NOT NULL to test the NULL values.
In this tutorial, we have shown you how to declare, assign and initialize PL/SQL variables. We also walked you through how to declare PL/SQL variables using variable anchors to make your code more flexible and adaptable to the changes in columns of the database tables.
- Getting started with plsql
- Assignments model and language
- Assignments model in PL/SQL
- Bulk collect
- Collections and Records
- Exception Handling
- IF-THEN-ELSE Statement
- Object Types
- PLSQL procedure
plsql Assignments model and language Assignments model in PL/SQL
Fastest entity framework extensions.
All programming languages allow us to assign values to variables. Usually, a value is assigned to variable, standing on left side. The prototype of the overall assignment operations in any contemporary programming language looks like this:
This will assign right operand to the left operand. In PL/SQL this operation looks like this:
Left operand must be always a variable . Right operand can be value, variable or function:
When the code block is executed in SQL*Plus the following output is printed in console:
There is a feature in PL/SQL that allow us to assign "from right to the left". It's possible to do in SELECT INTO statement. Prototype of this instrunction you will find below:
This code will assign character literal to a local variable:
Asignment "from right to the left" is not a standard , but it's valuable feature for programmers and users. Generally it's used when programmer is using cursors in PL/SQL - this technique is used, when we want to return a single scalar value or set of columns in the one line of cursor from SQL cursor.
Further Reading:
- Assigning Values to Variables
Got any plsql Question?
![pl sql assignment statement pdf](https://riptutorial.com/Images/icon-pdf-2.png)
- Advertise with us
- Cookie Policy
- Privacy Policy
Get monthly updates about new articles, cheatsheets, and tricks.
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
Declaring a variable and setting its value from a SELECT query in Oracle
In SQL Server we can use this:
How can I do the same in Oracle? I'm currently attempting the following:
Why this is not working ?
![pl sql assignment statement enter image description here](https://i.sstatic.net/dq4Wo.png)
- Any idea how this can work for types as objects? – Avias Commented Nov 22, 2013 at 15:01
5 Answers 5
SELECT INTO
Make sure that the query only returns a single row:
By default, a SELECT INTO statement must return only one row. Otherwise, PL/SQL raises the predefined exception TOO_MANY_ROWS and the values of the variables in the INTO clause are undefined. Make sure your WHERE clause is specific enough to only match one row If no rows are returned, PL/SQL raises NO_DATA_FOUND. You can guard against this exception by selecting the result of an aggregate function, such as COUNT(*) or AVG(), where practical. These functions are guaranteed to return a single value, even if no rows match the condition. A SELECT ... BULK COLLECT INTO statement can return multiple rows. You must set up collection variables to hold the results. You can declare associative arrays or nested tables that grow as needed to hold the entire result set. The implicit cursor SQL and its attributes %NOTFOUND, %FOUND, %ROWCOUNT, and %ISOPEN provide information about the execution of a SELECT INTO statement.
- DECLARE COMPID VARCHAR2(20); SELECT companyid INTO COMPID from sasapplication where appid='90' and rownum=1; Can you tell why this sql is throwing error – Imran Qadir Baksh - Baloch Commented Sep 26, 2011 at 10:53
- 2 It should be noted that SELECT my_column INTO the_variable FROM my_table will inherently bring back too many rows if the table has more than one row. While obvious to some, it should simply indicate that a WHERE condition should be supplied, and also that a the_variable := is not necessary, that the statement you gave automatically assigns the value to the variable. I was tripped up and still using that part and getting all kinds of other errors before I removed that from my query. – vapcguy Commented Aug 12, 2016 at 15:13
Not entirely sure what you are after but in PL/SQL you would simply
- As @Thilo states, there is more to consider around just this specific synatx. A little more info on what you're trying to achieve would enable us to tailor a better method for populating your variable. – Ollie Commented Sep 26, 2011 at 10:52
One Additional point:
When you are converting from tsql to plsql you have to worry about no_data_found exception
In tsql if no data found then the variable will be null but no exception
![pl sql assignment statement Praveen's user avatar](https://i.sstatic.net/4wqJf.png?s=64)
ORA-01422: exact fetch returns more than requested number of rows
if you don't specify the exact record by using where condition, you will get the above exception
For storing a single row output into a variable from the select into query :
declare v_username varchare(20); SELECT username into v_username FROM users WHERE user_id = '7';
this will store the value of a single record into the variable v_username.
For storing multiple rows output into a variable from the select into query :
you have to use listagg function. listagg concatenate the resultant rows of a coloumn into a single coloumn and also to differentiate them you can use a special symbol. use the query as below SELECT listagg(username || ',' ) within group (order by username) into v_username FROM users;
![pl sql assignment statement Vincent Lal's user avatar](https://lh3.googleusercontent.com/-lGarIA_-R6g/AAAAAAAAAAI/AAAAAAAAB40/s8ltgTq2ndQ/photo.jpg?sz=64)
Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Sign up or log in
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
Not the answer you're looking for? Browse other questions tagged oracle plsql or ask your own question .
- The Overflow Blog
- Battling ticket bots and untangling taxes at the frontiers of e-commerce
- Ryan Dahl explains why Deno had to evolve with version 2.0
- Featured on Meta
- We've made changes to our Terms of Service & Privacy Policy - July 2024
- Bringing clarity to status tag usage on meta sites
- Feedback requested: How do you use tag hover descriptions for curating and do...
Hot Network Questions
- How to stop Windows from changing date modified when copying files from network?
- What does it mean to formalise a philosophy or philosophical claim?
- A natural automorphism of a finite group with two generators?
- Has any spacecraft ever been severely damaged by a micrometeriote?
- How common is it for external contractors to manage internal teams, and how can we navigate this situation?
- Reference Request: Preservation of étale maps under rigid analytic GAGA
- Seven different digits are placed in a row. The products of the first 3, middle 3 and last 3 are all equal. What is the middle digit?
- Are "lie low" and "keep a low profile" interchangeable?
- Electric moped PWM MOSFETs failure
- Move line matching string to top of the file
- Why is the identity of the actor voicing Spider-Man kept secret even in the commentary?
- Why do only 2 USB cameras work while 4 USB cameras cannot stream at once?
- What prevents applications from misusing private keys?
- Shape functions on the triangle using vertex values and derivatives
- Did the French janitor at the University of Hanoi receive a higher base pay than a Vietnamese professor?
- Capacitor package selection for DC-DC convertor
- Is sudoku only one puzzle?
- For applying to a STEM research position at a U.S. research university, should a resume include a photo?
- What did Scott Lang mean by "living as a tenant of the state"?
- Could a gas giant still be low on the horizon from the equator of a tidally locked moon?
- 'best poster' and 'best talk' prizes - can we do better determining winners?
- Fitting the 9th piece into the pizza box
- White to play and mate in 3 moves..what are the moves?
- If a body in free fall, according to general relativity is weightless, that is, not experiencing force, how does the object gain kinetic energy?
8i | 9i | 10g | 11g | 12c | 13c | 18c | 19c | 21c | 23ai | Misc | PL/SQL | SQL | RAC | WebLogic | Linux
Home » Articles » Misc » Here
Introduction to PL/SQL
PL/SQL is a procedural extension of SQL, making it extremely simple to write procedural code that includes SQL as if it were a single language. This article gives a brief overview of some of the important points you should consider when first trying to learn PL/SQL.
What is so great about PL/SQL anyway?
Pl/sql architecture, variables and constants, using sql in pl/sql, branching and conditional control, looping statements, procedures, functions and packages, object types, collections, error handling, my utopian development environment.
Related articles.
- PL/SQL: Stop Making the Same Performance Mistakes
- PL/SQL Articles
PL/SQL is a procedural extension of SQL, making it extremely simple to write procedural code that includes SQL as if it were a single language. In comparison, most other programming languages require mapping data types, preparing statements and processing result sets, all of which require knowledge of specific APIs.
The data types in PL/SQL are a super-set of those in the database, so you rarely need to perform data type conversions when using PL/SQL. Ask your average Java or .NET programmer how they find handling date values coming from a database. They can only wish for the simplicity of PL/SQL.
When coding business logic in middle tier applications, a single business transaction may be made up of multiple interactions between the application server and the database. This adds a significant overhead associated with network traffic. In comparison, building all the business logic as PL/SQL in the database means client code needs only a single database call per transaction, reducing the network overhead significantly.
![pl sql assignment statement PL/SQL to Improve Performance](https://oracle-base.com/articles/misc/images/plsql/plsql-to-improve-performance.png)
Oracle is a multi-platform database, making PL/SQL and incredibly portable language. If your business logic is located in the database, you are protecting yourself from operating system lock-in.
Programming languages go in and out of fashion continually. Over the last 35+ years Oracle databases have remained part of the enterprise landscape. Suggesting that any language is a safer bet than PL/SQL is rather naive. Placing your business logic in the database makes changing your client layer much simpler if you like to follow fashion.
Centralizing application logic enables a higher degree of security and productivity. The use of Application Program Interfaces (APIs) can abstract complex data structures and security implementations from client application developers, leaving them free to do what they do best.
The PL/SQL language is actually made up of two distinct languages. Procedural code is executed by the PL/SQL engine, while SQL is sent to the SQL statement executor.
![pl sql assignment statement PL/SQL Architecture](https://oracle-base.com/articles/misc/images/plsql/plsql-architecture.png)
For the most part, the tight binding between these two languages make PL/SQL look like a single language to most developers.
Overview of PL/SQL Elements
Blocks are the organizational unit for all PL/SQL code, whether it is in the form of an anonymous block, procedure, function, trigger or type. A PL/SQL block is made up of three sections (declaration, executable and exception), of which only the executable section is mandatory.
Based on this definition, the simplest valid block is shown below, but it doesn't do anything.
The optional declaration section allows variables, types, procedures and functions do be defined for use within the block. The scope of these declarations is limited to the code within the block itself, or any nested blocks or procedure calls. The limited scope of variable declarations is shown by the following two examples. In the first, a variable is declared in the outer block and is referenced successfully in a nested block. In the second, a variable is declared in a nested block and referenced from the outer block, resulting in an error as the variable is out of scope.
The main work is done in the mandatory executable section of the block, while the optional exception section is where all error processing is placed. The following two examples demonstrate the usage of exception handlers for trapping error messages. In the first, there is no exception handler so a query returning no rows results in an error. In the second the same error is trapped by the exception handler, allowing the code to complete successfully.
Variables and constants must be declared for use in procedural and SQL code, although the datatypes available in SQL are only a subset of those available in PL/SQL. All variables and constants must be declared before they are referenced. The declarations of variables and constants are similar, but constant definitions must contain the CONSTANT keyword and must be assigned a value as part of the definition. Subsequent attempts to assign a value to a constant will result in an error. The following example shows some basic variable and constant definitions, along with a subsequent assignment of a value to a constant resulting in an error.
In addition to standard variable declarations used within SQL, PL/SQL allows variable datatypes to match the datatypes of existing columns, rows or cursors using the %TYPE and %ROWTYPE qualifiers, making code maintenance much easier. The following code shows each of these definitions in practice.
The %TYPE qualifier signifies that the variable datatype should match that of the specified table column, while the %ROWTYPE qualifier signifies that the variable datatype should be a record structure that matches the specified table or cursor structure. Notice that the record structures use the dot notation (variable.column) to reference the individual column data within the record structure.
Values can be assigned to variables directly using the ":=" assignment operator, via a SELECT ... INTO statement or when used as OUT or IN OUT parameter from a procedure. All three assignment methods are shown in the example below.
The SQL language is fully integrated into PL/SQL, so much so that they are often mistaken as being a single language by newcomers. It is possible to manuallly code the retrieval of data using explicit cursors, or let Oracle do the hard work and use implicit cursors. Examples of both explicit implicit cursors are presented below, all of which rely on the following table definition table.
The SELECT ... INTO statement allows data from one or more columns of a specific row to be retrieved into variables or record structures using an implicit cursor.
The previous example can be recoded to use an explicit cursor a shown below. Notice that the cursor is now defined in the declaration section and is explicitly opened and closed, making the code larger and a little ugly.
When a query returns multiple rows is can be processed within a loop. The following example uses a cursor FOR-LOOP to cycle through multiple rows of an implicit cursor. Notice there is no need for a variable definition as "cur_rec" acts as a pointer to the current record of the cursor.
The explicit cursor version of the previous example is displayed below. Once again the cursor management is all done manually, but this time the exit from the loop must be managed manually also.
In most situations the implicit cursors provide a faster and cleaner solution to data retrieval than their explicit equivalents.
The IF-THEN-ELSE and CASE statements allow code to decide on the correct course of action for the current circumstances. In the following example the IF-THEN-ELSE statement is used to decide if today is a weekend day.
First, the expression between the IF and the THEN is evaluated. If that expression equates to TRUE the code between the THEN and the ELSE is performed. If the expression equates to FALSE the code between the ELSE and the END IF is performed. The IF-THEN-ELSE statement can be extended to cope with multiple decisions by using the ELSIF keyword. The example below uses this extended form to produce a different message for Saturday and Sunday.
SQL CASE expressions were introduced in the later releases of Oracle 8i, but Oracle 9i included support for CASE statements in PL/SQL for the first time. The CASE statement is the natural replacement for large IF-THEN-ELSIF-ELSE statements. The following code gives an example of a matched CASE statement.
The WHEN clauses of a matched CASE statement simply state the value to be compared. If the value of the variable specified after the CASE keyword matches this comparison value the code after the THEN keyword is performed.
A searched CASE statement has a slightly different format, with each WHEN clause containing a full expression, as shown below.
Loops allow sections of code to be processed multiple times. In its most basic form a loop consists of the LOOP and END LOOP statement, but this form is of little use as the loop will run forever.
Typically you would expect to define an end condition for the loop using the EXIT WHEN statement along with a Boolean expression. When the expression equates to true the loop stops. The example below uses this syntax to pint out numbers from 1 to 5.
The placement of the EXIT WHEN statement can affect the processing inside the loop. For example, placing it at the start of the loop means the code within the loop may be executed "0 to many" times, like a while-do loop in other language. Placing the EXIT WHEN at the end of the loop means the code within the loop may be executed "1 to many" times, like a do-while loop in other languages.
The FOR-LOOP statement allows code within the loop to be repeated a specified number of times based on the lower and upper bounds specified in the statement. The example below shows how the previous example could be recorded to use a FOR-LOOP statement.
The WHILE-LOOP statement allows code within the loop to be repeated until a specified expression equates to TRUE. The following example shows how the previous examples can be re-coded to use a WHILE-LOOP statement.
In addition to these loops a special cursor FOR-LOOP is available as seen previously.
The GOTO statement allows a program to branch unconditionally to a predefined label. The following example uses the GOTO statement to repeat the functionality of the examples in the previous section.
In this example the GOTO has been made conditional by surrounding it with an IF statement. When the GOTO is called the program execution immediately jumps to the appropriate label, defined using double-angled brackets.
Procedures and functions allow code to be named and stored in the database, making code reuse simpler and more efficient. Procedures and functions still retain the block format, but the DECLARE keyword is replaced by PROCEDURE or FUNCTION definitions, which are similar except for the additional return type definition for a function. The following procedure displays numbers between upper and lower bounds defined by two parameters, then shows the output when it's run.
The following function returns the difference between upper and lower bounds defined by two parameters.
Packages allow related code, along with supporting types, variables and cursors, to be grouped together. The package is made up of a specification that defines the external interface of the package, and a body that contains all the implementation code. The following code shows how the previous procedure and function could be grouped into a package.
Once the package specification and body are compiled they can be executed as before, provided the procedure and function names are prefixed with the package name.
Since the package specification defines the interface to the package, the implementation within the package body can be modified without invalidating any dependent code, thus breaking complex dependency chains. A call to any element in the package causes the whole package to be loaded into memory, improving performance compared to loading several individual procedures and functions.
Record types are composite data structures, or groups of data elements, each with its own definition. Records can be used to mimic the row structures of tables and cursors, or as a convenient was to pass data between subprograms without listing large number of parameters.
When a record type must match a particular table or cursor structure it can be defined using the %ROWTYPE attribute, removing the need to define each column within the record manually. Alternatively, the record can be specified manually. The following code provides an example of how records can be declared and used in PL/SQL.
Notice how the records can be assigned to each other directly, and how all elements within a record can be initialized with a single assignment of a NULL value.
Oracle implements Objects through the use of TYPE declarations, defined in a similar way to packages. Unlike packages where the instance of the package is limited to the current session, an instance of an object type can be stored in the database for later use. The definition of the type contains a comma separated list of attributes/properties, defined in the same way as package variables, and member functions/procedures. If a type contains member functions/procedures, the procedural work for these elements is defined in the TYPE BODY .
To see how objects can be used let's assume we want to create one to represent a person. In this case, a person is defined by three attributes (first_name, last_name, date_of_birth). We would also like to be able to return the age of the person, so this is included as a member function (get_age).
Next the type body is created to implement the get_age member function.
Once the object is defined it can be used to define a column in a database table.
To insert data into the PEOPLE table we must use the t_person() constructor. This can be done as part of a regular DML statement, or using PL/SQL.
Once the data is loaded it can be queried using the dot notation.
The query below shows this in action.
Oracle uses collections in PL/SQL the same way other languages use arrays. You can read more about the types of collections available here .
Database triggers are stored programs associated with a specific table, view or system events, such that when the specific event occurs the associated code is executed. Triggers can be used to validate data entry, log specific events, perform maintenance tasks or perform additional application logic. The following example shows how a table trigger could be used to keep an audit of update actions.
From this you can see that the trigger fired when the price of the record was updated, allowing us to audit the action.
The following trigger sets the current_schema parameter for each session logging on as the APP_LOGON user, making the default schema that of the SCHEMA_OWNER user.
You can read more about database triggers here .
When PL/SQL detects an error normal execution stops and an exception is raised, which can be captured and processed within the block by the exception handler if it is present. If the block does not contain an exception handler section the exception propagates outward to each successive block until a suitable exception handler is found, or the exception is presented to the client application.
Oracle provides many predefined exceptions for common error conditions, like NO_DATA_FOUND when a SELECT ... INTO statement returns no rows. The following example shows how exceptions are trapped using the appropriate exception handler. Assume we want to return the username associated with a specific user_id value, we might do the following.
That works fine for user_id values that exist, but look what happens if we use one that doesn't.
This is not a very user friendly message, so we can trap this error and produce something more meaningful to the users.
It is possible to declare your own named exceptions for application specific errors, or associate them with Oracle "ORA-" messages, which are executed using the RAISE statement. The example below builds on the previous example using a user-defined named exception to signal an application specific error.
The code still handles users that don't exist, but now it also raises an exception if the user returned is either SYS or SYSTEM.
We can raise errors and give them a friendly message using the RAISE_APPLICATION_ERROR procedure. The first parameter is a user-defined error number that has to be between -20000 and -20999. Notice the example below uses RAISE_APPLICATION_ERROR , rather than a user-defined named exception. The output includes the error number we specified, but notice we have to trap it with the OTHERS exception handler.
If we want to associate a named exception with the error number, we can use PRAGMA EXCEPTION_INIT as show below. This allows us to trap the error in a named exception handler, rather than having to trap it in the OTHERS handler.
I wrote a blog post about this many years ago. You can read it here . I think it's worth just spending a little time reiterating some of the main points here. It may not be to everyone's liking, but I've always found it to be the most secure and flexible approach I've come across.
I believe the use of PL/SQL Application Program Interfaces (APIs) should be compulsory. Ideally, client application developers should have no access to tables, but instead access data via PL/SQL APIs, or possibly views if absolutely necessary. The diagram below shows this relationship.
![pl sql assignment statement Physical Organisation](https://oracle-base.com/images/plsql/physical-organisation.png)
In reality the organisation is likely to be a little more complicated. Maybe something like the example below.
![pl sql assignment statement Physical Organisation 2](https://oracle-base.com/images/plsql/physical-organisation-2.png)
This has a number of beneficial effects, including:
- Security and auditing mechanisms can be implemented and maintained at the database level, with little or no impact on the client application layer.
- It removes the need for triggers as all inserts, updates and deletes are wrapped in APIs. Instead of writing triggers you simply add the code into the API.
- It prevents people who don't understand SQL writing inefficient queries. All SQL should be written by PL/SQL developers or DBAs, reducing the likelihood of bad queries.
- The underlying structure of the database is hidden from the client application developers, so it hides complexity and structural changes can be made without client applications being changed.
- The API implementation can be altered and tuned without affecting the client application layer. Reducing the need for redeployments of applications.
- The same APIs are available to all applications that access the database. Resulting in reduced duplication of effort.
- These API can be presented as web services using XML or JSON. See ORDS .
This sounds a little extreme, but this approach has paid dividends for me again and again. Let's elaborate on these points to explain why this approach is so successful.
It's a sad fact that auditing and security are often only brought into focus after something bad has happened. Having the ability to revise and refine these features is a massive bonus. If this means you have to re-factor your whole application you are going to have problems. If on the other hand it can be revised in your API layer you are on to a winner.
Over-reliance on database triggers is a bad thing in my opinion. It seems every company I've worked for has at one time or another used triggers to patch a “hole” or implement some business functionality in their application. Every time I see this my heart sinks. Invariably these triggers get disabled by accident and bits of functionality go AWOL, or people forget they exist and recode some of their functionality elsewhere in the application. It's far easier to wrap the transactional processing in an API that includes all necessary functionality, thereby removing the need for table triggers entirely.
Many client application developers have to be able to work with several database engines, and as a result are not always highly proficient at coding against Oracle databases. Added to that, some development architectures such as J2EE positively discourage developers from working directly with the database. You wouldn't ask an inexperienced person to fix your car, so why would you ask one to write SQL for you? Abstracting the SQL in an API leaves the client application developers to do what they do best, while your PL/SQL programmers can write the most efficient SQL and PL/SQL possible.
During the lifetime of an application many changes can occur in the physical implementation of the database. It's nice to think that the design will be perfected before application development starts, but in reality this seldom seems to be the case. The use of APIs abstracts the developers from the physical implementation of the database, allowing change without impacting on the application.
In the same way, it is not possible to foresee all possible performance problems during the coding phase of an application. Many times developers will write and test code with unrealistic data, only to find the code that was working perfectly in a development environment works badly in a production environment. If the data manipulation layer is coded as an API it can be tuned without re-coding sections of the application, after all the implementation has changed, not the interface.
A problem I see time and time again is that companies invest heavily in coding their business logic into a middle tier layer on an application server, then want to perform data loads either directly into the database, or via a tool that will not link to their middle tier application. As a result they have to re-code sections of their business logic into PL/SQL or some other client language. Remember, it's not just the duplication of effort during the coding, but also the subsequent maintenance. Since every language worth using can speak to Oracle via OCI, JDBC, ODBC or web services, it makes sense to keep your logic in the database and let every application or data load use the same programming investment.
Of course, you may not always have full control of your development environment, but it's worth bearing these points in mind.
Additional functionality that may be useful to develop your API layer is listed below.
- Pipelined Table Functions
- Using Ref Cursors To Return Recordsets
- Implicit Statement Results
- Proxy User Authentication and Connect Through in Oracle Databases
For more information see:
Hope this helps. Regards Tim...
Back to the Top.
Created: 2013-03-10 Updated: 2024-04-02
Home | Articles | Scripts | Blog | Certification | Videos | Misc | About
About Tim Hall Copyright & Disclaimer
- ▼PL/SQL Exercises with Solution
- Introduction to PL/SQL
- Fundamentals
- Control Statement
- String Functions
- Exception Handling
- Object-Oriented Programming
- ..More to come..
PL/SQL Exercises with Solution
Introduction.
The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with SQL and Oracle . Exercises are designed to enhance your ability to write well-structured PL/SQL programs. Hope, these exercises help you to improve your PL/SQL query skills. Currently following sections are available, we are working hard to add more exercises. Happy Coding!
- PL/SQL Fundamentals [ 16 Exercises ]
- PL/SQL DataType [ 8 Exercises ]
- PL/SQL Control Statement [ 30 Exercises ]
- PL/SQL String Functions [ 12 Exercises ]
- PL/SQL While Loop [ 21 Exercises ]
- PL/SQL Cursor [ 50 exercises ]
- PL/SQL Trigger [ 11 exercises ]
- PL/SQL Exception Handling [ 16 exercises ]
- PL/SQL Package [ 17 exercises ]
- PL/SQL Object-Oriented Programming [ 6 exercises ]
PL/SQL Fundamentals:
PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's procedural extension for SQL and the Oracle relational database. It enables users to combine SQL statements with procedural constructs, providing capabilities such as variables, loops, conditional statements, and exception handling. PL/SQL facilitates the development of powerful and efficient database applications by allowing developers to encapsulate business logic within the database itself, enhancing performance, security, and maintainability.
Data Types:
- Scalar Data Types:
- INTEGER: Stores whole numbers within a specified range.
- NUMBER: Represents numeric values with optional precision and scale.
- VARCHAR2 / CHAR: Used for storing character strings of variable or fixed length, respectively.
- BOOLEAN: Holds Boolean values (TRUE, FALSE, or NULL).
- DATE / TIMESTAMP: Stores date and time values with optional time zone information.
- BINARY_INTEGER: Similar to INTEGER but limited to smaller values.
- Composite Data Types:
- %TYPE: This pseudo-type is used to declare variables that have the same data type as a specified database column or variable.
- %ROWTYPE: Represents a complete row of data in a table or cursor result set.
- RECORD: Allows you to define a user-defined data structure with multiple fields of different data types.
- Collection Data Types:
- Nested Tables: Unordered collections of elements of the same data type.
- VARRAY (Variable-size Array): Arrays of a fixed maximum size, storing elements of the same data type.
- Associative Arrays (Index-by Tables): Collections of key-value pairs where the key is unique and can be of any scalar data type.
- LOB Data Types:
- CLOB (Character Large Object): Stores large blocks of character data, such as text documents.
- BLOB (Binary Large Object): Holds large blocks of binary data, such as images or multimedia files.
- BFILE: Represents binary files stored outside the database.
- REF CURSOR: A special data type used to hold the result set returned by a query. It allows dynamic SQL queries to be executed and processed within PL/SQL programs.
Control Statement:
PL/SQL (Procedural Language/Structured Query Language) provides various control structures that allow developers to control the flow of execution within their code. These control statements help in making decisions, looping through code blocks, and handling exceptions. Here's a brief description of PL/SQL control statements:
- IF-THEN-ELSE Statement:
- The IF-THEN-ELSE statement allows developers to execute a block of code conditionally based on a specified condition.
- If the condition evaluates to true, the code inside the THEN block is executed; otherwise, the code inside the ELSE block is executed.
- CASE Statement:
- The CASE statement evaluates a set of conditions and executes the corresponding code block based on the first condition that evaluates to true.
- It is similar to a switch-case statement in other programming languages.
- LOOP Statements:
- PL/SQL provides various loop statements such as LOOP, WHILE, and FOR loops to iterate over a block of code until a certain condition is met.
- The LOOP statement creates an infinite loop that continues until explicitly terminated using an EXIT statement.
- The WHILE loop executes a block of code repeatedly as long as a specified condition remains true.
- The FOR loop iterates over a range of values or a collection and executes the loop body for each iteration.
- EXIT Statements:
- EXIT statements are used to exit a loop prematurely based on a specified condition.
- They are commonly used within loops to terminate the loop when a certain condition is met.
- GOTO Statement:
- The GOTO statement allows developers to transfer control to a specified label within the same block, subprogram, or package.
- While it provides flexibility, its usage is generally discouraged due to the potential for creating unreadable and unmaintainable code.
- Exception Handling:
- PL/SQL includes exception handling mechanisms to gracefully handle errors and unexpected conditions that may arise during program execution.
- Exception handling blocks such as BEGIN, EXCEPTION, and END allow developers to catch and handle exceptions, ensuring that programs can recover from errors gracefully.
String Functions:
PL/SQL provides a variety of built-in string functions that enable developers to manipulate strings efficiently within their code. These string functions offer capabilities such as concatenation, substring extraction, case conversion, searching, and replacing parts of strings. Here's a brief description of some commonly used PL/SQL string functions:
CONCAT: This function is used to concatenate two or more strings together, producing a single string as the output. Example: CONCAT('Hello', ' ', 'World') returns 'Hello World'.
SUBSTR: SUBSTR function is used to extract a substring from a string. It takes three arguments: the source string, the starting position, and the length of the substring.
These are just a few examples of PL/SQL string functions. By utilizing these functions effectively, developers can perform various string operations efficiently within their PL/SQL code.
While loop :
In PL/SQL, the WHILE loop is a control structure used to repeatedly execute a block of code as long as a specified condition evaluates to true. It consists of the WHILE keyword followed by a condition. The code within the loop is executed repeatedly until the condition becomes false. The loop continues until the condition evaluates to false, at which point control exits the loop and moves to the next statement following the loop block.
Cursors are used in PL/SQL to retrieve and process multiple rows returned by a SQL query. PL/SQL supports both implicit and explicit cursors. Implicit cursors are automatically created for SQL statements like SELECT INTO, while explicit cursors are declared explicitly using the CURSOR keyword.
Triggers are special types of stored procedures that are automatically executed in response to specific events occurring in the database. These events may include INSERT, UPDATE, or DELETE operations on tables. Triggers are useful for enforcing data integrity rules and implementing complex business logic.
Exception Handling :
Exception handling in PL/SQL allows developers to handle runtime errors gracefully. PL/SQL provides built-in exceptions and allows users to define custom exceptions using the EXCEPTION keyword. Exception handling blocks consist of BEGIN, EXCEPTION, and END keywords.
Packages are schema objects that group logically related PL/SQL types, variables, constants, cursors, exceptions, procedures, and functions into a single unit. They provide modularity, encapsulation, and namespace management, making code maintenance easier.
Object Oriented Programming:
PL/SQL (Procedural Language/Structured Query Language) is primarily a procedural language used for writing stored procedures, functions, and triggers within Oracle databases. However, it also supports some aspects of object-oriented programming (OOP) through its object-oriented features. Here's a description of PL/SQL's object-oriented programming capabilities:
- User-Defined Types (UDTs):
- PL/SQL allows users to define their own abstract data types using the CREATE TYPE statement. These user-defined types can encapsulate both data and methods, similar to classes in object-oriented programming languages.
- UDTs can have attributes (data members) and methods (procedures and functions) associated with them.
- Object Types:
- Object types in PL/SQL are similar to classes in object-oriented programming languages. They encapsulate data and behavior, allowing users to model real-world entities as objects.
- An object type consists of attributes (data members) and methods (procedures and functions) that operate on those attributes.
- Objects of a particular type can be instantiated, allowing users to create instances (objects) based on the defined type.
- Object Views:
- Object views provide a way to present relational data as objects, allowing users to interact with relational data using object-oriented concepts.
- They map relational tables to object types, enabling applications to access and manipulate relational data as objects.
- Inheritance:
- PL/SQL supports inheritance, allowing object types to inherit attributes and methods from parent types. This promotes code reuse and facilitates modeling of hierarchical relationships between objects.
- Subtypes can extend or override the attributes and methods of their parent types.
- Encapsulation:
- Encapsulation is a key principle of object-oriented programming, and PL/SQL allows users to encapsulate data and behavior within object types.
- By encapsulating data and methods, users can enforce data abstraction and control access to the internal state of objects.
- Polymorphism:
- Polymorphism refers to the ability of objects to exhibit different behaviors based on their data types or class hierarchy. While PL/SQL does not support dynamic polymorphism like languages such as Java or C++, it does support method overloading and overriding within object types.
Follow us on Facebook and Twitter for latest update.
- Weekly Trends and Language Statistics
![pl sql assignment statement PL/SQL Tutorial](https://www.tutorialspoint.com/plsql/images/plsql-mini-logo.jpg)
- PL/SQL Tutorial
- PL/SQL - Home
- PL/SQL - Overview
- PL/SQL - Environment
PL/SQL - Basic Syntax
- PL/SQL - Data Types
- PL/SQL - Variables
- PL/SQL - Constants and Literals
- PL/SQL - Operators
- PL/SQL - Conditions
- PL/SQL - Loops
- PL/SQL - Strings
- PL/SQL - Arrays
- PL/SQL - Procedures
- PL/SQL - Functions
- PL/SQL - Cursors
- PL/SQL - Records
- PL/SQL - Exceptions
- PL/SQL - Triggers
- PL/SQL - Packages
- PL/SQL - Collections
- PL/SQL - Transactions
- PL/SQL - Date & Time
- PL/SQL - DBMS Output
- PL/SQL - Object Oriented
- PL/SQL Useful Resources
- PL/SQL - Questions and Answers
- PL/SQL - Quick Guide
- PL/SQL - Useful Resources
- PL/SQL - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
In this chapter, we will discuss the Basic Syntax of PL/SQL which is a block-structured language; this means that the PL/SQL programs are divided and written in logical blocks of code. Each block consists of three sub-parts −
S.No | Sections & Description |
---|---|
1 |
This section starts with the keyword . It is an optional section and defines all variables, cursors, subprograms, and other elements to be used in the program. |
2 |
This section is enclosed between the keywords and and it is a mandatory section. It consists of the executable PL/SQL statements of the program. It should have at least one executable line of code, which may be just a to indicate that nothing should be executed. |
3 |
This section starts with the keyword . This optional section contains that handle errors in the program. |
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL blocks using BEGIN and END . Following is the basic structure of a PL/SQL block −
The 'Hello World' Example
The end; line signals the end of the PL/SQL block. To run the code from the SQL command line, you may need to type / at the beginning of the first blank line after the last line of the code. When the above code is executed at the SQL prompt, it produces the following result −
The PL/SQL Identifiers
By default, identifiers are not case-sensitive . So you can use integer or INTEGER to represent a numeric value. You cannot use a reserved keyword as an identifier.
The PL/SQL Delimiters
A delimiter is a symbol with a special meaning. Following is the list of delimiters in PL/SQL −
Delimiter | Description |
---|---|
Addition, subtraction/negation, multiplication, division | |
Attribute indicator | |
Character string delimiter | |
Component selector | |
Expression or list delimiter | |
Host variable indicator | |
Item separator | |
Quoted identifier delimiter | |
Relational operator | |
Remote access indicator | |
Statement terminator | |
Assignment operator | |
Association operator | |
Concatenation operator | |
Exponentiation operator | |
Label delimiter (begin and end) | |
Multi-line comment delimiter (begin and end) | |
Single-line comment indicator | |
Range operator | |
Relational operators | |
Different versions of NOT EQUAL |
The PL/SQL Comments
Program comments are explanatory statements that can be included in the PL/SQL code that you write and helps anyone reading its source code. All programming languages allow some form of comments.
The PL/SQL supports single-line and multi-line comments. All characters available inside any comment are ignored by the PL/SQL compiler. The PL/SQL single-line comments start with the delimiter -- (double hyphen) and multi-line comments are enclosed by /* and */.
When the above code is executed at the SQL prompt, it produces the following result −
PL/SQL Program Units
A PL/SQL unit is any one of the following −
- PL/SQL block
- Package body
Each of these units will be discussed in the following chapters.
Home » PL/SQL Tutorial » PL/SQL CASE Statement
PL/SQL CASE Statement
Summary : in this tutorial, you will learn how to use the PL/SQL CASE statement to control the flow of a program.
The CASE statement chooses one sequence of statements to execute out of many possible sequences.
The CASE statement has two types: simple CASE statement and searched CASE statement. Both types of CASE statements support an optional ELSE clause.
Simple PL/SQL CASE statement
A simple CASE statement evaluates a single expression and compares the result with some values.
The simple CASE statement has the following structure:
Let’s examine the syntax of the simple CASE statement in detail:
1) selector
The selector is an expression that is evaluated once. The result of the selector is used to select one of the several alternatives e.g., selector_value_1 and selector_value_2 .
2) WHEN selector_value THEN statements
The selector values i.e., selector_value_1 , selector_value_2 , etc., are evaluated sequentially. If the result of a selector value equals the result of the selector , then the associated sequence of statements executes and the CASE statement ends. In addition, the subsequent selector values are not evaluated.
3) ELSE else_statements
If no values in WHERE clauses match the result of the selector in the CASE clause, the sequence of statements in the ELSE clause executes.
Because the ELSE clause is optional, you can skip it. However, if you do so, PL/SQL will implicitly use the following:
In other words, PL/SQL raises a CASE_NOT_FOUND error if you don’t specify an ELSE clause and the result of the CASE expression does not match any value in the WHEN clauses.
Note that this behavior of the CASE statement is different from the IF THEN statement . When the IF THEN statement has no ELSE clause and the condition is not met, PL/SQL does nothing instead raising an error.
Simple CASE statement example
The following example compares single value ( c_grade ) with many possible values ‘A’, ‘B’,’C’,’D’, and ‘F’:
Searched CASE statement
The searched CASE statement evaluates multiple Boolean expressions and executes the sequence of statements associated with the first condition that evaluates to TRUE .
The searched CASE statement has the following structure:
The searched CASE statement follows the rules below:
- The conditions in the WHEN clauses are evaluated in order, from top to bottom.
- The sequence of statements associated with the WHEN clause whose condition evaluates to TRUE is executed. If more than one condition evaluates to TRUE, only the first one executes.
- If no condition evaluates to TRUE, the else_statements in the ELSE clause executes. If you skip the ELSE clause and no expressions are TRUE, a CASE_NOT_FOUND exception is raised.
Searched CASE statement example
The following example illustrates how to use the searched CASE statement to calculate sales commission based on sales revenue.
In this example, the sales revenue was set to 150,000. The first expression evaluated to FALSE:
But the second expression evaluates to TRUE and the sale commission was set to 15%:
PL/SQL stops evaluating the subsequent condition once it finds the first condition that evaluates to TRUE. Therefore, in this example, PL/SQL will never evaluate the last two conditions in the CASE statement. The ELSE statement clause will also never execute.
Simple or searched CASE statement
As a rule of thumb, use a searched CASE statement when you want to execute a sequence of statements based on the results of multiple Boolean expressions and use a simple CASE statement when you want to execute a sequence of statements based on the result of a single expression.
PL/SQL CASE statement vs. CASE expression
PL/SQL also has CASE expression which is similar to the CASE statement.
A CASE expression evaluates a list of conditions and returns one of multiple possible result expressions.
The result of a CASE expression is a single value whereas the result of a CASE statement is the execution of a sequence of statements.
In this tutorial, you have learned how to use the PL/SQL CASE statement to control the flow of a program.
🚀 Think you’ve got what it takes for a career in Data? Find out in just one minute!
![pl sql assignment statement](https://datascientest.com/wp-content/uploads/2022/03/logo-2021.png)
In the realm of relational databases, Oracle stands out not only for the robustness of its management systems but also for the advanced tools it provides developers to optimize, automate, and secure data operations. Among these tools is PL/SQL (Procedural Language/Structured Query Language), a powerful programming language designed to seamlessly integrate with SQL, the standard query language for relational databases.
PL/SQL extends the capabilities of SQL by adding procedural features such as loops, conditions, and exceptions, allowing developers to create scripts for database management.
This language, essential for any developer working with Oracle, aims to combine database management commands with a procedural programming language . It provides more comprehensive programming solutions for creating critical applications running on the Oracle database.
Why learn PL/SQL?
PL/SQL is a crucial programming language for developers using databases. It presents numerous advantages:
- Integration with Oracle Database: PL/SQL is designed to work optimally with Oracle Database, allowing for smooth and efficient interactions with stored data.
- Integration with SQL: PL/SQL is an extension of the SQL language that enables writing complex SQL queries, managing transactions, and manipulating data directly within the same programming environment.
- Ease of use: If you are already familiar with SQL, you will find PL/SQL syntax quite intuitive. The transition from SQL to PL/SQL is natural for those with SQL experience, making it easier to learn this language.
- Enhanced security: PL/SQL includes robust security features, controlling data access. You can protect sensitive data by limiting direct access to tables and creating additional layers of security.
- Automation of repetitive tasks: PL/SQL includes features (procedures, functions, triggers) that automate database management processes. This reduces the need for manually executing repetitive tasks and minimizes human errors.
- Portability: PL/SQL code blocks can be moved between different Oracle databases without modification.
The various applications of PL/SQL
PL/SQL offers multiple applications in database management. Thanks to its flexibility and power, it is used for various use cases such as:
- Application development: PL/SQL is used for developing web applications based on Oracle databases.
- Automation of administrative tasks: PL/SQL enables the automation of routine database administration tasks, thereby improving the efficiency and reliability of processes.
- Database security: PL/SQL helps protect the integrity of the database.
- Analysis and reporting: PL/SQL is used to generate customized reports that meet specific data management needs. PL/SQL also allows creating data for dashboards and visualization tools.
![pl sql assignment statement](https://datascientest.com/en/files/2024/07/PL_SQL_datascientest1.jpg)
The basics of PL/SQL syntax
- Declarative section ( DECLARE ): This section is used to declare variables, constants, cursors, and other PL/SQL objects. It is optional.
- Executable section ( BEGIN ): This section contains the instructions that will be executed. It is mandatory.
- Exception section ( EXCEPTION ): This section is used to handle errors that may occur during the execution of instructions in the BEGIN section. It is optional.
1. Variables and data types:
Variables in PL/SQL must be declared in the DECLARE section. The data types used for variables are similar to those in SQL, with extensions specific to PL/SQL.
VARCHAR2 : Used for character strings.
NUMBER : Used for numbers.
DATE : Used for dates and times.
v_employee_name VARCHAR2(50);
v_salary NUMBER(10, 2);
v_hire_date DATE;
v_employee_name := ‘Jane Doe’;
v_salary := 60000;
v_hire_date := SYSDATE;
DBMS_OUTPUT.PUT_LINE(‘Employee: ‘ || v_employee_name || ‘hired on: ‘ || v_hire_date);
2. Conditional structures:
Conditional structures allow testing conditions and executing code blocks based on the results of these tests.
The IF-THEN-ELSE conditional structure allows executing statements if a condition is true, and optionally other statements if it is false.
IF v_salary > 50000 THEN
DBMS_OUTPUT.PUT_LINE(‘High salary’);
ELSIF v_salary > 30000 THEN
DBMS_OUTPUT.PUT_LINE(‘Medium salary’);
DBMS_OUTPUT.PUT_LINE(‘Low salary’);
PL/SQL supports several types of loops, allowing repeated execution of instructions.
FOR loop : Executes a block of instructions a defined number of times.
FOR i IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(‘Iteration: ‘ || i);
WHILE loop : Executes a block of instructions as long as a condition is true.
![pl sql assignment statement](https://datascientest.com/en/files/2024/07/PL_SQL_datascientest2.jpg)
v_counter NUMBER := 1;
WHILE v_counter <= 10 LOOP
DBMS_OUTPUT.PUT_LINE(‘Counter: ‘ || v_counter);
v_counter := v_counter + 1;
LOOP : Executes a block of instructions indefinitely until an exit condition is met.
EXIT WHEN v_counter > 10;
4. Procedures:
Stored procedures are PL/SQL subprograms that can be reused to perform specific tasks.
Here is an example of a procedure to increase employees’ salaries based on their performance:
CREATE OR REPLACE PROCEDURE adjust_salary (emp_id NUMBER, increment NUMBER) AS BEGIN
UPDATE employees
SET salary = salary + increment
WHERE employee_id = emp_id; COMMIT;
This procedure takes an employee ID and an increment amount as input, then updates the specified employee’s salary.
To call this procedure, simply do:
adjust_salary(1001, 5000);
5. Functions:
Functions are PL/SQL subprograms that can return a single value.
Here is an example of a function that calculates the average salary of employees:
CREATE OR REPLACE FUNCTION calculate_average_salary RETURN NUMBER AS avg_salary NUMBER;
SELECT AVG(salary) INTO avg_salary FROM employees;
RETURN avg_salary;
This function calculates the average salary of employees and returns the result.
![pl sql assignment statement](https://datascientest.com/en/files/2024/07/PL_SQL_datascientest3.jpg)
6. Exception handling:
Exception handling is an essential part of PL/SQL, allowing errors to be managed elegantly and ensuring application stability.
Exceptions are handled in the EXCEPTION section of a PL/SQL block. There are predefined exceptions such as NO_DATA_FOUND and TOO_MANY_ROWS , as well as the possibility to define custom exceptions.
SELECT name INTO v_employee_name FROM employees WHERE employee_id = 9999;
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘No data found for the specified employee ID.’);
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE(‘Multiple rows found for the specified employee ID.’);
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(‘An unexpected error occurred: ‘ || SQLERRM);
![](http://charunivedita.online/777/templates/cheerup2/res/banner1.gif)
7. Triggers:
Triggers are PL/SQL blocks that execute automatically in response to specific events on a table, such as insertion, update, or deletion of rows.
Here is an example of a trigger that records modification history on a critical table:
CREATE OR REPLACE TRIGGER audit_trigger
AFTER INSERT OR UPDATE OR DELETE ON employees
FOR EACH ROW
IF INSERTING THEN
INSERT INTO audit_log (action, employee_id, action_time)
VALUES (‘INSERT’, :NEW.employee_id, SYSDATE);
ELSIF UPDATING THEN
VALUES (‘UPDATE’, :NEW.employee_id, SYSDATE);
ELSIF DELETING THEN
VALUES (‘DELETE’, :OLD.employee_id, SYSDATE);
This trigger tracks all changes made to the `employees` table by recording the actions in an `audit_log` table .
PL/SQL is a powerful language that extends the capabilities of SQL with procedural features. It offers significant advantages in terms of performance, error management, security, and portability. With its control structures, stored procedures, functions, and triggers, PL/SQL facilitates the creation of robust and performant applications . By understanding and applying these concepts, developers can fully leverage the features offered by Oracle Database to develop effective and reliable solutions.
To learn more about the SQL language and train for careers in Data, join DataScientest .
![pl sql assignment statement](https://datascientest.com/en/files/2024/07/C2_MESSAGE.png)
DataScientest News
Sign up for our Newsletter to receive our guides, tutorials, events, and the latest news directly in your inbox.
You are not available?
![pl sql assignment statement](https://datascientest.com/en/files/2022/02/icone-newsletter.png)
Related articles
![pl sql assignment statement](https://datascientest.com/en/files/2024/07/image1-4-768x512-1.png)
How to become a Data Analyst? Training, job, salary
![pl sql assignment statement](https://datascientest.com/en/files/2024/07/carreer-opportunities-datascientest.jpg)
Top 10 Careers for the Modern Workforce
![pl sql assignment statement](https://datascientest.com/en/files/2024/07/PL_SQL_datascientest.png)
MySQL: Find out everything about this RDBMS
![pl sql assignment statement](https://datascientest.com/en/files/2020/08/new-logo.png)
Get monthly insider insights from experts directly in your mailbox
- SQL Cheat Sheet
- SQL Interview Questions
- MySQL Interview Questions
- PL/SQL Interview Questions
- Learn SQL and Database
PL/SQL WHERE Clause
The WHERE clause in PL/SQL is essential for filtering records based on specified conditions. It is used in SELECT, UPDATE, and DELETE statements to limit the rows affected or retrieved, allowing precise control over data manipulation and retrieval.
In this article, We will learn about the WHERE Clause in PL/SQL by understanding various examples and so on.
- In PL/SQL , the WHERE clause is a powerful tool used to filter records that meet specific conditions.
- It is often used in SELECT , UPDATE , DELETE , and other SQL statements to restrict the rows affected by these operations.
Syntax of the WHERE Clause:
Parameters:
- column1, column2, …: The names of the columns you want to retrieve.
- table_name: The name of the table from which to retrieve the data.
- condition: The condition to filter the rows. Only rows that meet this condition will be included in the result set.
Using the WHERE Clause in PL/SQL
The WHERE clause can be used in various PL/SQL operations to filter records. Below are examples demonstrating its use in SELECT, UPDATE, and DELETE statements.
1. WHERE Clause in SELECT Statement
Let’s say we have a table ‘ employees’ with the following structure:
emp_id | name | department | salary |
---|---|---|---|
1 | Alice | HR | 5000 |
2 | Bob | IT | 6000 |
3 | Carol | Finance | 5500 |
4 | David | IT | 7000 |
name | department | salary |
---|---|---|
Bob | IT | 6000 |
David | IT | 7000 |
Explanation: This query retrieves the names, departments, and salaries of employees who work in the IT department.
2. WHERE Clause in UPDATE Statement
Explanation: This query increases the salary of all employees in the HR department by 10%.
3. WHERE Clause in DELETE Statement
Explanation: This query deletes the record of the employee with emp_id 3 from the employees table.
4. WHERE Clause with Multiple Conditions
The WHERE clause can also include multiple conditions using logical operators such as AND, OR, and NOT.
name | department | salary |
---|---|---|
David | IT | 7000 |
5. WHERE Clause with IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
name | department | salary |
---|---|---|
Bob | IT | 6000 |
Carol | Finance | 5500 |
David | IT | 7000 |
Explanation: This query retrieves the names, departments, and salaries of employees who work in either the IT or Finance departments.
6. WHERE Clause with BETWEEN Operator
The BETWEEN operator is used to filter records within a certain range.
name | department | salary |
---|---|---|
Bob | IT | 6000 |
Carol | Finance | 5500 |
David | IT | 7000 |
Explanation: This query retrieves the names, departments, and salaries of employees whose salary is between 5500 and 7000.
The WHERE clause is an essential component of SQL and PL/SQL for filtering records based on specific conditions. By using the WHERE clause effectively, you can retrieve, update, or delete precise subsets of data, making your database operations more efficient and targeted.
FAQs on PL/SQL WHERE Clause
What is the purpose of the where clause in pl/sql.
The WHERE clause is used to filter records in SQL statements like SELECT, UPDATE, DELETE, and more, based on specific conditions.
Can I use multiple conditions in a WHERE clause?
Yes, you can use multiple conditions in a WHERE clause by combining them with logical operators such as AND, OR, and NOT.
What is the difference between the AND and OR operators in the WHERE clause?
The AND operator requires all conditions to be true for a record to be included in the result set, while the OR operator requires at least one condition to be true.
How does the IN operator work in the WHERE clause?
The IN operator allows you to specify multiple values in a WHERE clause. It filters records that match any of the specified values.
Please Login to comment...
Similar reads, improve your coding skills with practice.
What kind of Experience do you want to share?
- Database PL/SQL Language Reference
- PL/SQL Control Statements
4 PL/SQL Control Statements
PL/SQL has three categories of control statements: conditional selection statements, loop statements and sequential control statements.
PL/SQL categories of control statements are:
Conditional selection statements , which run different statements for different data values.
The conditional selection statements are IF and CASE .
Loop statements , which run the same statements with a series of different data values.
The loop statements are the basic LOOP , FOR LOOP , and WHILE LOOP .
The EXIT statement transfers control to the end of a loop. The CONTINUE statement exits the current iteration of a loop and transfers control to the next iteration. Both EXIT and CONTINUE have an optional WHEN clause, where you can specify a condition.
Sequential control statements , which are not crucial to PL/SQL programming.
The sequential control statements are GOTO , which goes to a specified statement, and NULL , which does nothing.
Conditional Selection Statements
LOOP Statements
Sequential Control Statements
4.1 Conditional Selection Statements
The conditional selection statements , IF and CASE , run different statements for different data values.
The IF statement either runs or skips a sequence of one or more statements, depending on a condition. The IF statement has these forms:
IF THEN ELSE
IF THEN ELSIF
The CASE statement chooses from a sequence of conditions, and runs the corresponding statement. The CASE statement has these forms:
Simple, which evaluates a single expression and compares it to several potential values.
Searched, which evaluates multiple conditions and chooses the first one that is true.
The CASE statement is appropriate when a different action is to be taken for each alternative.
IF THEN Statement
IF THEN ELSE Statement
IF THEN ELSIF Statement
Simple CASE Statement
Searched CASE Statement
4.1.1 IF THEN Statement
The IF THEN statement either runs or skips a sequence of one or more statements, depending on a condition.
The IF THEN statement has this structure:
If the condition is true, the statements run; otherwise, the IF statement does nothing.
For complete syntax, see " IF Statement " .
Avoid clumsy IF statements such as:
Instead, assign the value of the BOOLEAN expression directly to a BOOLEAN variable:
A BOOLEAN variable is either TRUE , FALSE , or NULL . Do not write:
Instead, write:
Example 4-1 IF THEN Statement
In this example, the statements between THEN and END IF run if and only if the value of sales is greater than quota +200.
4.1.2 IF THEN ELSE Statement
The IF THEN ELSE statement has this structure:
If the value of condition is true, the statements run; otherwise, the else_statements run.
IF statements can be nested, as in Example 4-3 .
Example 4-2 IF THEN ELSE Statement
In this example, the statement between THEN and ELSE runs if and only if the value of sales is greater than quota +200; otherwise, the statement between ELSE and END IF runs.
Example 4-3 Nested IF THEN ELSE Statements
4.1.3 IF THEN ELSIF Statement
The IF THEN ELSIF statement has this structure:
The IF THEN ELSIF statement runs the first statements for which condition is true. Remaining conditions are not evaluated. If no condition is true, the else_statements run, if they exist; otherwise, the IF THEN ELSIF statement does nothing.
A single IF THEN ELSIF statement is easier to understand than a logically equivalent nested IF THEN ELSE statement:
Example 4-4 IF THEN ELSIF Statement
In this example, when the value of sales is larger than 50000, both the first and second conditions are true. However, because the first condition is true, bonus is assigned the value 1500, and the second condition is never tested. After bonus is assigned the value 1500, control passes to the DBMS_OUTPUT . PUT_LINE invocation.
Example 4-5 IF THEN ELSIF Statement Simulates Simple CASE Statement
This example uses an IF THEN ELSIF statement with many ELSIF clauses to compare a single value to many possible values. For this purpose, a simple CASE statement is clearer—see Example 4-6 .
4.1.4 Simple CASE Statement
The simple CASE statement has this structure:
The selector is an expression (typically a single variable). Each selector_value can be either a literal or an expression. (For complete syntax, see " CASE Statement " .)
The simple CASE statement runs the first statements for which selector_value equals selector . Remaining conditions are not evaluated. If no selector_value equals selector , the CASE statement runs else_statements if they exist and raises the predefined exception CASE_NOT_FOUND otherwise.
Example 4-6 uses a simple CASE statement to compare a single value to many possible values. The CASE statement in Example 4-6 is logically equivalent to the IF THEN ELSIF statement in Example 4-5 .
As in a simple CASE expression, if the selector in a simple CASE statement has the value NULL , it cannot be matched by WHEN NULL (see Example 2-51 ). Instead, use a searched CASE statement with WHEN condition IS NULL (see Example 2-53 ).
Example 4-6 Simple CASE Statement
4.1.5 Searched CASE Statement
The searched CASE statement has this structure:
The searched CASE statement runs the first statements for which condition is true. Remaining conditions are not evaluated. If no condition is true, the CASE statement runs else_statements if they exist and raises the predefined exception CASE_NOT_FOUND otherwise. (For complete syntax, see " CASE Statement " .)
The searched CASE statement in Example 4-7 is logically equivalent to the simple CASE statement in Example 4-6 .
In both Example 4-7 and Example 4-6 , the ELSE clause can be replaced by an EXCEPTION part. Example 4-8 is logically equivalent to Example 4-7 .
Example 4-7 Searched CASE Statement
Example 4-8 EXCEPTION Instead of ELSE Clause in CASE Statement
4.2 LOOP Statements
Loop statements run the same statements with a series of different values. The loop statements are:
Cursor FOR LOOP
The statements that exit a loop are:
The statements that exit the current iteration of a loop are:
CONTINUE WHEN
EXIT , EXIT WHEN , CONTINUE , and CONTINUE WHEN and can appear anywhere inside a loop, but not outside a loop. Oracle recommends using these statements instead of the " GOTO Statement " , which can exit a loop or the current iteration of a loop by transferring control to a statement outside the loop. (A raised exception also exits a loop. For information about exceptions, see " Overview of Exception Handling " .)
LOOP statements can be labeled, and LOOP statements can be nested. Labels are recommended for nested loops to improve readability. You must ensure that the label in the END LOOP statement matches the label at the beginning of the same loop statement (the compiler does not check).
Basic LOOP Statement
EXIT Statement
EXIT WHEN Statement
CONTINUE Statement
CONTINUE WHEN Statement
FOR LOOP Statement
WHILE LOOP Statement
For information about the cursor FOR LOOP , see " Processing Query Result Sets With Cursor FOR LOOP Statements " .
4.2.1 Basic LOOP Statement
The basic LOOP statement has this structure:
With each iteration of the loop, the statements run and control returns to the top of the loop. To prevent an infinite loop, a statement or raised exception must exit the loop.
" Basic LOOP Statement "
4.2.2 EXIT Statement
The EXIT statement exits the current iteration of a loop unconditionally and transfers control to the end of either the current loop or an enclosing labeled loop.
In Example 4-9 , the EXIT statement inside the basic LOOP statement transfers control unconditionally to the end of the current loop.
" EXIT Statement "
Example 4-9 Basic LOOP Statement with EXIT Statement
4.2.3 EXIT WHEN Statement
The EXIT WHEN statement exits the current iteration of a loop when the condition in its WHEN clause is true, and transfers control to the end of either the current loop or an enclosing labeled loop.
Each time control reaches the EXIT WHEN statement, the condition in its WHEN clause is evaluated. If the condition is not true, the EXIT WHEN statement does nothing. To prevent an infinite loop, a statement inside the loop must make the condition true, as in Example 4-10 .
In Example 4-10 , the EXIT WHEN statement inside the basic LOOP statement transfers control to the end of the current loop when x is greater than 3. Example 4-10 is logically equivalent to Example 4-9 .
In Example 4-11 , one basic LOOP statement is nested inside the other, and both have labels. The inner loop has two EXIT WHEN statements; one that exits the inner loop and one that exits the outer loop.
An EXIT WHEN statement in an inner loop can transfer control to an outer loop only if the outer loop is labeled.
In Example 4-12 , the outer loop is not labeled; therefore, the inner loop cannot transfer control to it.
Example 4-10 Basic LOOP Statement with EXIT WHEN Statement
Example 4-11 Nested, Labeled Basic LOOP Statements with EXIT WHEN Statements
Example 4-12 Nested, Unabeled Basic LOOP Statements with EXIT WHEN Statements
4.2.4 CONTINUE Statement
The CONTINUE statement exits the current iteration of a loop unconditionally and transfers control to the next iteration of either the current loop or an enclosing labeled loop.
In Example 4-13 , the CONTINUE statement inside the basic LOOP statement transfers control unconditionally to the next iteration of the current loop.
" CONTINUE Statement "
Example 4-13 CONTINUE Statement in Basic LOOP Statement
4.2.5 CONTINUE WHEN Statement
The CONTINUE WHEN statement exits the current iteration of a loop when the condition in its WHEN clause is true, and transfers control to the next iteration of either the current loop or an enclosing labeled loop.
Each time control reaches the CONTINUE WHEN statement, the condition in its WHEN clause is evaluated. If the condition is not true, the CONTINUE WHEN statement does nothing.
In Example 4-14 , the CONTINUE WHEN statement inside the basic LOOP statement transfers control to the next iteration of the current loop when x is less than 3. Example 4-14 is logically equivalent to Example 4-13 .
Example 4-14 CONTINUE WHEN Statement in Basic LOOP Statement
4.2.6 FOR LOOP Statement
The FOR LOOP statement runs one or more statements while the loop index is in a specified range. The statement has this structure:
Without REVERSE , the value of index starts at lower_bound and increases by one with each iteration of the loop until it reaches upper_bound . If lower_bound is greater than upper_bound , then the statements never run.
With REVERSE , the value of index starts at upper_bound and decreases by one with each iteration of the loop until it reaches lower_bound . If upper_bound is less than lower_bound , then the statements never run.
An EXIT , EXIT WHEN , CONTINUE , or CONTINUE WHEN in the statements can cause the loop or the current iteration of the loop to end early.
To process the rows of a query result set, use a cursor FOR LOOP , which has a query instead of a range of integers. For details, see " Processing Query Result Sets With Cursor FOR LOOP Statements " .
" FOR LOOP Statement "
In Example 4-15 , index is i , lower_bound is 1, and upper_bound is 3. The loop prints the numbers from 1 to 3.
The FOR LOOP statement in Example 4-16 is the reverse of the one in Example 4-15 : It prints the numbers from 3 to 1.
In some languages, the FOR LOOP has a STEP clause that lets you specify a loop index increment other than 1. To simulate the STEP clause in PL/SQL, multiply each reference to the loop index by the desired increment.
In Example 4-17 , the FOR LOOP effectively increments the index by five.
FOR LOOP Index
Lower Bound and Upper Bound
EXIT WHEN or CONTINUE WHEN Statement in FOR LOOP Statement
Example 4-15 FOR LOOP Statements
Example 4-16 Reverse FOR LOOP Statements
Example 4-17 Simulating STEP Clause in FOR LOOP Statement
4.2.6.1 FOR LOOP Index
The index of a FOR LOOP statement is implicitly declared as a variable of type PLS_INTEGER that is local to the loop. The statements in the loop can read the value of the index, but cannot change it. Statements outside the loop cannot reference the index. After the FOR LOOP statement runs, the index is undefined. (A loop index is sometimes called a loop counter.)
In Example 4-18 , the FOR LOOP statement tries to change the value of its index, causing an error.
In Example 4-19 , a statement outside the FOR LOOP statement references the loop index, causing an error.
If the index of a FOR LOOP statement has the same name as a variable declared in an enclosing block, the local implicit declaration hides the other declaration, as Example 4-20 shows.
Example 4-21 shows how to change Example 4-20 to allow the statement inside the loop to reference the variable declared in the enclosing block.
In Example 4-22 , the indexes of the nested FOR LOOP statements have the same name. The inner loop references the index of the outer loop by qualifying the reference with the label of the outer loop. For clarity only, the inner loop also qualifies the reference to its own index with its own label.
Example 4-18 FOR LOOP Statement Tries to Change Index Value
Example 4-19 Outside Statement References FOR LOOP Statement Index
Example 4-20 FOR LOOP Statement Index with Same Name as Variable
Example 4-21 FOR LOOP Statement References Variable with Same Name as Index
Example 4-22 Nested FOR LOOP Statements with Same Index Name
4.2.6.2 Lower Bound and Upper Bound
The lower and upper bounds of a FOR LOOP statement can be either numeric literals, numeric variables, or numeric expressions. If a bound does not have a numeric value, then PL/SQL raises the predefined exception VALUE_ERROR .
In Example 4-24 , the upper bound of the FOR LOOP statement is a variable whose value is determined at run time.
Example 4-23 FOR LOOP Statement Bounds
Example 4-24 Specifying FOR LOOP Statement Bounds at Run Time
4.2.6.3 EXIT WHEN or CONTINUE WHEN Statement in FOR LOOP Statement
Suppose that you must exit a FOR LOOP statement immediately if a certain condition arises. You can put the condition in an EXIT WHEN statement inside the FOR LOOP statement.
In Example 4-25 , the FOR LOOP statement executes 10 times unless the FETCH statement inside it fails to return a row, in which case it ends immediately.
Now suppose that the FOR LOOP statement that you must exit early is nested inside another FOR LOOP statement. If, when you exit the inner loop early, you also want to exit the outer loop, then label the outer loop and specify its name in the EXIT WHEN statement, as in Example 4-26 .
If you want to exit the inner loop early but complete the current iteration of the outer loop, then label the outer loop and specify its name in the CONTINUE WHEN statement, as in Example 4-27 .
" Overview of Exception Handling " for information about exceptions, which can also cause a loop to end immediately if a certain condition arises
Example 4-25 EXIT WHEN Statement in FOR LOOP Statement
Example 4-26 EXIT WHEN Statement in Inner FOR LOOP Statement
Example 4-27 CONTINUE WHEN Statement in Inner FOR LOOP Statement
4.2.7 WHILE LOOP Statement
The WHILE LOOP statement runs one or more statements while a condition is true. It has this structure:
If the condition is true, the statements run and control returns to the top of the loop, where condition is evaluated again. If the condition is not true, control transfers to the statement after the WHILE LOOP statement. To prevent an infinite loop, a statement inside the loop must make the condition false or null. For complete syntax, see " WHILE LOOP Statement " .
Some languages have a LOOP UNTIL or REPEAT UNTIL structure, which tests a condition at the bottom of the loop instead of at the top, so that the statements run at least once. To simulate this structure in PL/SQL, use a basic LOOP statement with an EXIT WHEN statement:
In Example 4-28 , the statements in the first WHILE LOOP statement never run, and the statements in the second WHILE LOOP statement run once.
Example 4-28 WHILE LOOP Statements
4.3 Sequential Control Statements
Unlike the IF and LOOP statements, the sequential control statements GOTO and NULL are not crucial to PL/SQL programming.
The GOTO statement, which goes to a specified statement, is seldom needed. Occasionally, it simplifies logic enough to warrant its use.
The NULL statement, which does nothing, can improve readability by making the meaning and action of conditional statements clear.
GOTO Statement
NULL Statement
4.3.1 GOTO Statement
The GOTO statement transfers control to a label unconditionally. The label must be unique in its scope and must precede an executable statement or a PL/SQL block. When run, the GOTO statement transfers control to the labeled statement or block. For GOTO statement restrictions, see " GOTO Statement " .
Use GOTO statements sparingly—overusing them results in code that is hard to understand and maintain. Do not use a GOTO statement to transfer control from a deeply nested structure to an exception handler. Instead, raise an exception. For information about the PL/SQL exception-handling mechanism, see PL/SQL Error Handling .
A label can appear only before a block (as in Example 4-21 ) or before a statement (as in Example 4-29 ), not in a statement, as in Example 4-30 .
To correct Example 4-30 , add a NULL statement, as in Example 4-31 .
A GOTO statement can transfer control to an enclosing block from the current block, as in Example 4-32 .
The GOTO statement transfers control to the first enclosing block in which the referenced label appears.
The GOTO statement in Example 4-33 transfers control into an IF statement, causing an error.
Example 4-29 GOTO Statement
Example 4-30 Incorrect Label Placement
Example 4-31 GOTO Statement Goes to Labeled NULL Statement
Example 4-32 GOTO Statement Transfers Control to Enclosing Block
Example 4-33 GOTO Statement Cannot Transfer Control into IF Statement
4.3.2 NULL Statement
The NULL statement only passes control to the next statement. Some languages refer to such an instruction as a no-op (no operation).
Some uses for the NULL statement are:
To provide a target for a GOTO statement, as in Example 4-31 .
To improve readability by making the meaning and action of conditional statements clear, as in Example 4-34
To create placeholders and stub subprograms, as in Example 4-35
To show that you are aware of a possibility, but that no action is necessary, as in Example 4-36
In Example 4-34 , the NULL statement emphasizes that only salespersons receive commissions.
In Example 4-35 , the NULL statement lets you compile this subprogram and fill in the real body later.
Using the NULL statement might raise an unreachable code warning if warnings are enabled. For information about warnings, see " Compile-Time Warnings " .
In Example 4-36 , the NULL statement shows that you have chosen to take no action for grades other than A, B, C, D, and F.
Example 4-34 NULL Statement Showing No Action
Example 4-35 NULL Statement as Placeholder During Subprogram Creation
Example 4-36 NULL Statement in ELSE Clause of Simple CASE Statement
![](http://charunivedita.online/777/templates/cheerup2/res/banner1.gif)
IMAGES
COMMENTS
Assignment statement (PL/SQL) The assignment statement sets a previously-declared variable or formal OUT or IN OUT parameter to the value of an expression. Syntax. ... The following example shows assignment statements in the executable section of a procedure: CREATE OR REPLACE PROCEDURE dept_salary_rpt ( p_deptno IN NUMBER, p_base_annual OUT ...
Assignment Statement. An assignment statement sets the current value of a variable, field, parameter, or element. The statement consists of an assignment target followed by the assignment operator and an expression. ... PL/SQL allows aggregate assignment between entire records if their declarations refer to the same cursor or table. Example 1-2
In PL/SQL, a variable is a meaningful name of a temporary storage location that supports a particular data type in program. ... PL/SQL variable assignment. In PL/SQL, to assign a value or a variable to another, you use the assignment operator ( := ) which is a colon( :) followed by the equal sign( =). ... You can use INTOof the SELECT statement ...
PL/SQL Variables. Summary: in this tutorial, you will learn about PL/SQL variables and how to use them effectively. In PL/SQL, a variable is named storage location that stores a value of a particular data type. The value of the variable changes through the program. Before using a variable, you must declare it in the declaration section of a block.
The prototype of the overall assignment operations in any contemporary programming language looks like this: left_operand assignment_operand right_operand instructions_of_stop. This will assign right operand to the left operand. In PL/SQL this operation looks like this: left_operand := right_operand; Left operand must be always a variable.
The assignment statement sets the value of a data item to a valid value. Previous Next ... Name of a cursor variable declared in a PL/SQL host environment and passed to PL/SQL as a bind variable. Do not put space between the colon (:) and host_cursor_variable.
Assignment Statement. An assignment statement sets the current value of a variable, field, parameter, or element. ... PL/SQL allows aggregate assignment between entire records if their declarations refer to the same cursor or table. The following example copies values from all the fields of one record to another:
By default, a SELECT INTO statement must return only one row. Otherwise, PL/SQL raises the predefined exception TOO_MANY_ROWS and the values of the variables in the INTO clause are undefined. Make sure your WHERE clause is specific enough to only match one row. If no rows are returned, PL/SQL raises NO_DATA_FOUND.
Summary: in this tutorial, you will learn how to develop a PL/SQL function and how to call it in various places such as an assignment statement, a Boolean expression, and an SQL statement.. Creating a PL/SQL function. Similar to a procedure, a PL/SQL function is a reusable program unit stored as a schema object in the Oracle Database.The following illustrates the syntax for creating a function:
PL/SQL. SQL is a single query that is used to perform DML and DDL operations. PL/SQL is a block of codes that used to write the entire program blocks/ procedure/ function, etc. It is declarative, that defines what needs to be done, rather than how things need to be done. PL/SQL is procedural that defines how the things needs to be done.
The PL/SQL language is actually made up of two distinct languages. Procedural code is executed by the PL/SQL engine, while SQL is sent to the SQL statement executor. For the most part, the tight binding between these two languages make PL/SQL look like a single language to most developers. Overview of PL/SQL Elements Blocks
Here's a brief description of PL/SQL control statements: IF-THEN-ELSE Statement: The IF-THEN-ELSE statement allows developers to execute a block of code conditionally based on a specified condition. If the condition evaluates to true, the code inside the THEN block is executed; otherwise, the code inside the ELSE block is executed. ...
However, there are two ways to assign values to all fields in a record at once. First, PL/SQL allows aggregate assignment between entire records if their declarations refer to the same table or cursor. For example, the following assignment is allowed: ... In a SQL statement, Boolean expressions let you specify the rows in a table that are ...
The assignment statement sets a previously-declared variable or formal OUT or IN OUT parameter to the value of an expression. Assignment statement (PL/SQL) ... Parent topic: Basic statements (PL/SQL) Updates to this topic are made in English and are applied to translated versions at a later date. Consequently, the English version of this topic ...
The assignment statement sets a previously-declared variable or formal OUT or IN OUT parameter to the value of an expression. Assignment statement (PL/SQL) DB2 10.5 for Linux, UNIX, and Windows
The PL/SQL Comments. Program comments are explanatory statements that can be included in the PL/SQL code that you write and helps anyone reading its source code. All programming languages allow some form of comments. The PL/SQL supports single-line and multi-line comments. All characters available inside any comment are ignored by the PL/SQL ...
Summary: in this tutorial, you will learn how to use the PL/SQL CASE statement to control the flow of a program. The CASE statement chooses one sequence of statements to execute out of many possible sequences. The CASE statement has two types: simple CASE statement and searched CASE statement. Both types of CASE statements support an optional ...
PL/SQL assignment statement examples. Oracle PL/SQL Tips by Donald BurlesonMarch 18, 2015. Question: I want some examples of the PL/SQL assignment statement. Answer: PL/SQL allow for assignment statements as follows: Text assignment statement: myvar := 'hello'. Numeric assignment statement in PL/SQL: myvar := 1.
PL/SQL uses the database character set to represent: . Stored source text of PL/SQL units. For information about PL/SQL units, see "PL/SQL Units and Compilation Parameters".. Character values of data types CHAR, VARCHAR2, CLOB, and LONG. For information about these data types, see "SQL Data Types".. The database character set can be either single-byte, mapping each supported character to one ...
PL/SQL is a crucial programming language for developers using databases. It presents numerous advantages: Integration with Oracle Database: PL/SQL is designed to work optimally with Oracle Database, allowing for smooth and efficient interactions with stored data. Integration with SQL: PL/SQL is an extension of the SQL language that enables writing complex SQL queries, managing transactions ...
Explanation: This query retrieves the names, departments, and salaries of employees whose salary is between 5500 and 7000. Conclusion. The WHERE clause is an essential component of SQL and PL/SQL for filtering records based on specific conditions. By using the WHERE clause effectively, you can retrieve, update, or delete precise subsets of data, making your database operations more efficient ...
PL/SQL categories of control statements are: Conditional selection statements, which run different statements for different data values. The conditional selection statements are IF and CASE . Loop statements, which run the same statements with a series of different data values. The loop statements are the basic LOOP, FOR LOOP, and WHILE LOOP .
The assignment statement sets a previously-declared variable or formal OUT or IN OUT parameter to the value of an expression. Assignment statement (PL/SQL) - IBM DB2 9.7 for Linux, UNIX, and Windows DB2 Version 9.7 for Linux, UNIX, and Windows