{"id":96210,"date":"2023-03-16T00:26:45","date_gmt":"2023-03-16T00:26:45","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=96210"},"modified":"2023-03-09T01:10:57","modified_gmt":"2023-03-09T01:10:57","slug":"the-select-statement-in-oracle","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/databases\/oracle-databases\/the-select-statement-in-oracle\/","title":{"rendered":"The SELECT Statement in Oracle"},"content":{"rendered":"<p>The <code>SELECT<\/code> statement is used to retrieve information from a database. Following the execution of a <code>SELECT<\/code> statement, a tabular result is held in a result table (called a result set). It allows you to select the table columns depending on a set of criteria.<\/p>\n<p><code>SELECT<\/code> statements might be as straightforward as selecting a few columns from a single table. They can also be complex, with several columns and criteria and multiple tables. In this article, I will introduce the basic <code>SELECT<\/code> statement fetching data from just one table.<\/p>\n<h2>SELECT Syntax:<\/h2>\n<p>The <code>SELECT<\/code> statement contains 4 Parts:<\/p>\n<p><strong>SELECT &gt;&gt; COLUMNS &gt;&gt; FROM &gt;&gt;WHERE<\/strong><\/p>\n<p>The <code>SELECT<\/code> clause defines which table columns are retrieved. The <code>FROM<\/code> clause defines which tables are queried. The <code>WHERE<\/code> clause determines\u00a0which table rows should be selected\u00a0and\u00a0if it is omitted, all table rows are selected.<\/p>\n<p>The basic syntax looks like this:<\/p>\n<pre class=\"\">SELECT Column_Name1, Column_Name2, Column_Name\r\nFROM Table_Name \r\nWHERE Criteria;<\/pre>\n<p>A database consists of one or more tables. Each table is given a distinct name (e.g., &#8220;Employee&#8221;, &#8220;Department&#8221;, &#8220;Address&#8221;). Data records are stored in tables (rows).<\/p>\n<p>Here&#8217;s an example of an <strong>&#8220;<\/strong><code>Employee<\/code><strong>&#8221; <\/strong>table: You can use the following SQL script to create <strong>&#8220;<\/strong><code>Employee<\/code><strong>\u201d <\/strong>and load the data.<\/p>\n<p>SQL script to create the\u00a0 &#8220;<code>Employee<\/code>\u201d table.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">CREATE TABLE Employee (\r\n    Employeeid Varchar(15) Primary Key,\r\n    Name       Varchar(15),\r\n    LastName   Varchar(15),\r\n    FirstName  Varchar(15),\r\n    Department Varchar(15),\r\n    Dob        Date,\r\n    Salary     Number(8,0)\r\n);<\/pre>\n<p>The following <code>INSERT<\/code> statements will load data into the <strong>&#8220;<\/strong><code>Employee<\/code><strong>&#8221; <\/strong>table for the demos in this article.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)\r\nVALUES ('1001', 'Allen Cox', 'Cox', 'Allen', 'IT', TO_DATE('01-July-1982', 'DD-MM-YYYY'),75000);\r\nINSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)\r\nVALUES ('1002', 'Dave Carry', 'Carry', 'Dave', 'Sales', TO_DATE('01-Jan-1992', 'DD-MM-YYYY'),70000);\r\nINSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)\r\nVALUES ('1003', 'Amit Singh','Singh', 'Amit', 'Sales', TO_DATE('20-Oct-1991', 'DD-MM-YYYY'),50000);\r\nINSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)\r\nVALUES ('1004', 'Rhonda Grant', 'Grant', 'Rhonda', 'Marketing', TO_DATE('15-May-1980', 'DD-MM-YYYY'),60000);\r\nINSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)\r\nVALUES ('1005', 'Marvin Cox', 'Cox', 'Marvin', 'Marketing', TO_DATE('15-Jan-1985', 'DD-MM-YYYY'),62000);\r\nINSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)\r\nVALUES ('1006', 'Dave Grant', 'Grant', 'Dave', 'Sales', TO_DATE('05-Oct-1980', 'DD-MM-YYYY'),90000);<\/pre>\n<p>This is how the data in the table looks.<\/p>\n<table>\n<tbody>\n<tr>\n<td>\n<p><strong>EmployeeId<\/strong><\/p>\n<\/td>\n<td>\n<p><strong>Name<\/strong><\/p>\n<\/td>\n<td>\n<p><strong>LastName<\/strong><\/p>\n<\/td>\n<td>\n<p><strong>FirstName<\/strong><\/p>\n<\/td>\n<td>\n<p><strong>Department<\/strong><\/p>\n<\/td>\n<td>\n<p><strong>DOB<\/strong><\/p>\n<\/td>\n<td>\n<p><strong>Salary<\/strong><\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p>1001<\/p>\n<\/td>\n<td>\n<p>Allen Cox<\/p>\n<\/td>\n<td>\n<p>Cox<\/p>\n<\/td>\n<td>\n<p>Allen<\/p>\n<\/td>\n<td>\n<p>IT<\/p>\n<\/td>\n<td>\n<p>01-JUL-82<\/p>\n<\/td>\n<td>\n<p>75000<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p>1002<\/p>\n<\/td>\n<td>\n<p>Dave Carry<\/p>\n<\/td>\n<td>\n<p>Carry<\/p>\n<\/td>\n<td>\n<p>Dave<\/p>\n<\/td>\n<td>\n<p>Sales<\/p>\n<\/td>\n<td>\n<p>01-JAN-92<\/p>\n<\/td>\n<td>\n<p>70000<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p>1003<\/p>\n<\/td>\n<td>\n<p>Amit Singh<\/p>\n<\/td>\n<td>\n<p>Singh<\/p>\n<\/td>\n<td>\n<p>Amit<\/p>\n<\/td>\n<td>\n<p>Sales<\/p>\n<\/td>\n<td>\n<p>20-OCT-91<\/p>\n<\/td>\n<td>\n<p>50000<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p>1005<\/p>\n<\/td>\n<td>\n<p>Marvin Cox<\/p>\n<\/td>\n<td>\n<p>Cox<\/p>\n<\/td>\n<td>\n<p>Marvin<\/p>\n<\/td>\n<td>\n<p>Marketing<\/p>\n<\/td>\n<td>\n<p>15-JAN-85<\/p>\n<\/td>\n<td>\n<p>62000<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p>1006<\/p>\n<\/td>\n<td>\n<p>Dave Grant<\/p>\n<\/td>\n<td>\n<p>Grant<\/p>\n<\/td>\n<td>\n<p>Dave<\/p>\n<\/td>\n<td>\n<p>Sales<\/p>\n<\/td>\n<td>\n<p>05-OCT-80<\/p>\n<\/td>\n<td>\n<p>90000<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Let\u2019s write <code>SELECT<\/code> statements on the above table.<\/p>\n<h1>Retrieve Data from a Single Table<\/h1>\n<p>The <code>SELECT<\/code> statement can retrieve data from single or multiple tables; however, all my examples in this article use a single table to focus on the parts of the <code>SELECT<\/code> statement itself. In a future article, I will cover multiple table queries and how JOIN operators can be used to connect data from multiple tables and then shaped into a single tabular data stream.<\/p>\n<h2>Select all columns<\/h2>\n<p>An asterisk following the word &#8220;<code>SELECT<\/code>&#8221; indicates that all fields that are available should be retrieved (columns).<\/p>\n<p>Using <code>SELECT *<\/code> in SQL queries is great for doing quick ad hoc work, but for code that will be reused in production, this is a poor practice that should be avoided. Instead of <code>SELECT *<\/code>, it is recommended to provide the column names you want in the <code>SELECT<\/code> query. Using column names not only improves efficiency but also makes SQL code easier to understand.<\/p>\n<p>Furthermore, if you use SQL with <code>*<\/code> in an application such as PeopleSoft code or .NET code and add any new columns to the table or reorder the existing columns, your code may break. It is however, what most people use when exploring data.<\/p>\n<p>The following <code>SELECT<\/code> statement gets all the columns and rows from the given table. Note that the <code>FROM<\/code> clause is where you specify the set of data that your query will be using. I will discuss this more when covering <code>JOIN<\/code> operations.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk \">SELECT  *  \r\nFROM Employee;<\/pre>\n<p>This returns:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"602\" height=\"153\" class=\"wp-image-96241\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-table-description-autom-6.png\" alt=\"Graphical user interface, table\n\nDescription automatically generated\" \/><\/p>\n<h2>Selecting one or more columns by name<\/h2>\n<p>Any database object such as a column name can be named using either quoted or unquoted identifiers. Unquoted identifiers are not case-sensitive. Oracle classifies them as uppercase.\u00a0 Case is important when using quoted IDs. By enclosing names in double quotation marks, you can give the following names to different objects in the same namespace.<\/p>\n<ul>\n<li>&#8220;employees&#8221;<\/li>\n<li>&#8220;Employees&#8221;<\/li>\n<li>&#8220;EMPLOYEES&#8221;<\/li>\n<\/ul>\n<p>It is important to note that Oracle reads the following names identically, therefore they cannot be used for various objects in the same namespace:<\/p>\n<ul>\n<li>employees<\/li>\n<li>EMPLOYEES<\/li>\n<li>&#8220;EMPLOYEES&#8221;<\/li>\n<\/ul>\n<p>I prefer object names without quotation marks because they are easier for me to type. This implies that when I create a table, I don&#8217;t use quotation marks so that the columns can be entered in either capital or lowercase characters in a select statement The decision is entirely personal in this case. However, consistency is important. I like uppercase keywords and PASCAL case for things like column and table names, but it is up to you to define your style.<\/p>\n<p>When selecting only certain columns from the table:<\/p>\n<ul>\n<li>Specify each column&#8217;s name when selecting multiple columns.<\/li>\n<li>Column names must be separated by commas.<\/li>\n<\/ul>\n<p><a id=\"post-96210-_Hlk128568186\"><\/a> For example, the following <code>SELECT<\/code> statement retrieves particular columns and rows from the given table.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT EmployeeId, Name, LastName, FirstName \r\nFROM Employee;<\/pre>\n<p>This query, using the table provided, returns:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"357\" height=\"145\" class=\"wp-image-96242\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-text-description-automa-1.png\" alt=\"Graphical user interface, text\n\nDescription automatically generated with medium confidence\" \/><\/p>\n<h1>Sorting data: ORDER BY<\/h1>\n<p>The <code>ORDER BY<\/code> clause is used to sort the result set in ascending or descending order. When you execute a query with no <code>ORDER BY<\/code> clause, the order of the output is not guaranteed to be in any order.\u00a0<\/p>\n<p>For example, assume you wish to sort the data from lowest to highest date of birth.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT  *  \r\nFROM Employee \r\nORDER BY DOB;<\/pre>\n<p>This returns the following, note that the data in the DOB column is sorted when the results are returned:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"588\" height=\"140\" class=\"wp-image-96243\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-table-description-autom-7.png\" alt=\"Graphical user interface, table\n\nDescription automatically generated\" \/><\/p>\n<p>By default, <code>ORDER BY<\/code> sorts the rows in ascending order. Although it is the default, you may optionally add <code>ASC<\/code> to the end of the <code>ORDER BY<\/code> clause to explicitly state the sort is ascending. By adding <code>DESC<\/code> at the end of the <code>ORDER BY <\/code>clause, you can instruct SQL to return results sorted by that column in descending order (For numbers 100 to 1 and letters Z to A).<\/p>\n<p>As a quick example, if you want to sort the data from highest to lowest date of birth, add <code>DESC<\/code> as a suffix to <code>DOB<\/code> in the <code>ORDER BY<\/code> clause.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT *  \r\nFROM Employee \r\nORDER BY DOB DESC;<\/pre>\n<p>Now you can see the <code>DOB<\/code> data goes from most recent to oldest data:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"586\" height=\"136\" class=\"wp-image-96244\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-table-description-autom-8.png\" alt=\"Graphical user interface, table\n\nDescription automatically generated with medium confidence\" \/><\/p>\n<h2>Sorting by Multiple Columns:<\/h2>\n<p>You can use more than one sort of level to order your data. The primary sort order is defined by the first field name, the secondary sort the second, and so on. You simply add more columns to the <code>ORDER BY<\/code> clause. Each column may be ascending or descending, as you wish.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT Column_Name1, Column_Name2, Column_Name3 \r\nFROM Tablename \r\nORDER BY Column_Name1 &lt;desc&gt;, Column_Name2 &lt;desc&gt;, \r\n         Column_Name3 &lt;desc&gt;;<\/pre>\n<p>For example, you may sort your data by salary and then by date of birth within salary:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT * \r\nFROM Employee \r\nORDER BY Salary DESC, DOB DESC;<\/pre>\n<p>There are no duplicated values in our dataset, but this is the output.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"596\" height=\"143\" class=\"wp-image-96245\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-application-description-4.png\" alt=\"Graphical user interface, application\n\nDescription automatically generated\" \/><\/p>\n<h1>Filtering rows from the output<\/h1>\n<p>The SQL <code>SELECT<\/code> statement&#8217;s <code>WHERE<\/code> clause specifies which rows to (or not to) return from your table or view by filtering rows based on a given condition.<\/p>\n<p>When referring to literal character values in the <code>WHERE<\/code> clause, one must put the values in single quotes, for example, <code>DEPARTMENT='Sales';<\/code> Other datatypes have different rules for how they are represented in code. For example, numeric values should not be surrounded by quotations.<\/p>\n<p>This is the basic syntax:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT &lt;Column Name List&gt; \r\nFROM   Tablename \r\nWHERE  &lt;Comparison Expression&gt;\r\nORDER BY Column_Name &lt;desc&gt;;<\/pre>\n<p>The <code>&lt;comparison expression&gt;<\/code> in the <code>WHERE<\/code> clause can most any expression returning a Boolean value. For example, you might compare a column value to a literal (<code>Salary = 10000<\/code>), a column value to another column (<code>CurrentSalary = StartingSalary<\/code>), or even if a column value has a <code>NULL<\/code> value (<code>Salary IS NULL<\/code>). A <code>NULL<\/code> value generally means that a value is unknown, in that you don\u2019t have the value.<\/p>\n<p>For comparing two values, most comparison operators can be used with a <code>WHERE<\/code> clause:<\/p>\n<table>\n<tbody>\n<tr>\n<td>\n<p>Operator<\/p>\n<\/td>\n<td>\n<p>Description<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>IN<\/code><\/p>\n<\/td>\n<td>\n<p>Equal to any item on a list<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>NOT IN<\/code><\/p>\n<\/td>\n<td>\n<p>Not equal to any item on a list<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>AND<\/code><\/p>\n<\/td>\n<td>\n<p>All conditions are true<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>OR<\/code><\/p>\n<\/td>\n<td>\n<p>Any Condition is true<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>=<\/code><\/p>\n<\/td>\n<td>\n<p>Equal<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>&lt;&gt;<\/code><\/p>\n<\/td>\n<td>\n<p>Not equal<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>&gt;<\/code><\/p>\n<\/td>\n<td>\n<p>Greater than<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>&lt;<\/code><\/p>\n<\/td>\n<td>\n<p>Less than<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>&gt;=<\/code><\/p>\n<\/td>\n<td>\n<p>Greater than or equal<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>&lt;=<\/code><\/p>\n<\/td>\n<td>\n<p>Less than or equal<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>BETWEEN<\/code><\/p>\n<\/td>\n<td>\n<p>Between a range<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>LIKE<\/code><\/p>\n<\/td>\n<td>\n<p>Search for a pattern<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p><code>IS [NOT] NULL<\/code><\/p>\n<\/td>\n<td>\n<p>Checks to see if the column value IS NULL<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The <code>WHERE<\/code> clause may also be quite complex depending on the necessary criteria, something that I will cover in a later article.<\/p>\n<h3>WHERE Clause Examples<\/h3>\n<p>In these next subsections, I will give a few examples of <code>WHERE<\/code> clauses using different comparison operators.<\/p>\n<h4>= (Equal) Comparison Operator<\/h4>\n<p>The most common comparison operator is =. It simply is used to compare that two values are equal. For example:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT  *  \r\nFROM Employee \r\nWHERE Department ='Sales';<\/pre>\n<p>This returns the following, where the employee is in the Sales department:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"566\" height=\"85\" class=\"wp-image-96246\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/table-description-automatically-generated-3.png\" alt=\"Table\n\nDescription automatically generated\" \/><\/p>\n<h4>&lt;&gt; Not equal Comparison Operator<\/h4>\n<p>The following query shows all employees from Department Sales.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT  *  \r\nFROM Employee \r\nWHERE DEPARTMENT &lt;&gt; 'Sales';<\/pre>\n<p>This returns:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"583\" height=\"93\" class=\"wp-image-96247\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-application-table-desc-2.png\" alt=\"Graphical user interface, application, table\n\nDescription automatically generated\" \/><\/p>\n<p>There are also comparison operators for &gt; (Greater than), &lt; (Less than), &gt;= (Greater than equal to), &lt;= (Less than equal to), and more that work in a similar way.<\/p>\n<h4>IN Comparison Operator<\/h4>\n<p>The following query returns all <code>Employee<\/code> rows with <code>EmployeeId<\/code> values in the range of &#8216;1001&#8217;,1002, or &#8216;1003&#8217;.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT * \r\nFROM Employee \r\nWHERE EmployeeId IN ('1001',1002,'1003');<\/pre>\n<p>This returns:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"568\" height=\"85\" class=\"wp-image-96248\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-application-description-5.png\" alt=\"Graphical user interface, application\n\nDescription automatically generated\" \/><\/p>\n<p>If you want the rows that are not in a certain range, you need to use <code>NOT IN<\/code>. For example, the following query returns all <code>Employee<\/code> rows with <code>EmployeeId<\/code> values, <strong>not<\/strong> in the range of &#8216;1001&#8217;,1002, or &#8216;1003&#8217;.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT *\r\nFROM Employee \r\nWHERE EmployeeId NOT IN ('1001',1002,'1003');<\/pre>\n<p>This returns the other rows in the table:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"583\" height=\"81\" class=\"wp-image-96249\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-description-automaticall-2.png\" alt=\"Graphical user interface\n\nDescription automatically generated with medium confidence\" \/><\/p>\n<p>Note: be slightly careful with the <code>NOT IN<\/code> operator when <code>NULL<\/code> values could be involved. Column <code>NOT IN (NULL, 1, 2)<\/code> will never return any rows. <code>NULL<\/code> comparisons return <code>NULL<\/code>, and only rows with a <code>TRUE<\/code> comparison will be returned.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"586\" height=\"110\" class=\"wp-image-96250\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-table-description-autom-9.png\" alt=\"Graphical user interface, table\n\nDescription automatically generated\" \/><\/p>\n<h4>AND Boolean Operator<\/h4>\n<p>Boolean operators are used to create more complex filters by tying 2 or more conditions together. For example, say you need to find all employees from the &#8220;Sales&#8221; Department with the last name \u201cGrant\u201d.<\/p>\n<p>The two conditions are equality operations, and then we tie them together with <code>AND<\/code>:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT  *\r\nFROM Employee \r\nWHERE Department ='Sales' \r\n  AND LastName=<code>'Grant'<\/code>;<\/pre>\n<p>The result is:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"573\" height=\"46\" class=\"wp-image-96251\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/word-image-96210-11-1.png\" \/><\/p>\n<h4>OR Operator<\/h4>\n<p>Much like and, but in this case, we want to find where any condition is met. For example, the following query finds all employees from the &#8220;Sales&#8221; Department or last name is &#8220;Grant&#8221;<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT  *  \r\nFROM Employee \r\nWHERE DEPARTMENT='Sales' \r\n   OR LastName= 'Grant';<\/pre>\n<p>This returns:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"586\" height=\"108\" class=\"wp-image-96252\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-table-description-autom-10.png\" alt=\"Graphical user interface, table\n\nDescription automatically generated\" \/><\/p>\n<p>It should be noted that when using <code>AND<\/code> and <code>OR<\/code> Boolean expression you need to take care when combining them. Use parenthesis to group together items. For example, if you want all employees from the &#8220;Sales&#8221; Department with the last name \u201cGrant\u201d as well as all employees not in the &#8220;Sales&#8221; Department, you will use the following:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">WHERE (Department ='Sales' \r\n       AND LastName='Grant')\r\n    OR (Department &lt;&gt; 'Sales')<\/pre>\n<h4>Between Comparison Operator<\/h4>\n<p>The SQL <code>BETWEEN<\/code> operator is used to filter data based on a range of values. It allows you to select rows from a table where a column&#8217;s value falls within a specified range.<\/p>\n<p>Note that the <code>BETWEEN<\/code> operator is inclusive, meaning it includes both the lower and upper bounds in the range. The following query returns all employees whose salaries are between $50000 and $70000.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT  *  \r\nFROM Employee \r\nWHERE Salary BETWEEN 50000 And 70000;<\/pre>\n<p>This returns:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"586\" height=\"110\" class=\"wp-image-96253\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-table-description-autom-11.png\" alt=\"Graphical user interface, table\n\nDescription automatically generated\" \/><\/p>\n<p>In the output you can see that the two rows with 50000 and 70000 are in the output. If you want to exclude the bounds, you need to be specific in your comparison. For example, the previous <code>BETWEEN<\/code> expression could be re-written:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">WHERE Salary &gt;= 50000 AND Salary &lt;=70000;<\/pre>\n<p>If you didn\u2019t want the endpoints, you could rewrite it as:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">WHERE Salary &gt; 50000 AND Salary &lt;70000;<\/pre>\n<p>And you may need to vary that based on exactly what you are trying to achieve. Some people do not like to use <code>BETWEEN<\/code> because it isn\u2019t as expressive as using individual comparison operators.<\/p>\n<h4>The LIKE Comparison Operator<\/h4>\n<p>A very important operator that I want to introduce is the <code>LIKE<\/code> operator. It lets you find more complex matches using simple comparison operators.<\/p>\n<p>The <code>LIKE<\/code> operator does a pattern match comparison, which means it compares a string value to a pattern string that contains wildcard characters.<\/p>\n<p>Wildcards can be defined using a &#8220;%&#8221; or &#8220;_&#8221; symbol both before and after the pattern<\/p>\n<p>In Oracle SQL, the escape character can be used in a <code>LIKE<\/code> statement to escape special characters and match their literal value instead of their special meaning. The escape character is specified using the <code>ESCAPE<\/code> clause, and its default value is the backslash (\\) character. For more information about escape character or wild cards please refer to the <a href=\"https:\/\/docs.oracle.com\/cd\/B13789_01\/server.101\/b10759\/conditions016.htm\">Oracle link<\/a><\/p>\n<p>Note: Oracle also supports a regular expressions <code>LIKE<\/code> operator too. For more information about this, <a href=\"https:\/\/docs.oracle.com\/cd\/B12037_01\/server.101\/b10759\/conditions018.htm\">check out this article<\/a>.<\/p>\n<p>The percent sign (%) represents many, multiple, or zero characters, while the underscore symbol (_) one and only one value.<\/p>\n<p>For example. the SQL query below will return employees\u00a0whose first names begin with the letter &#8216;A&#8217;:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT  *  \r\nFROM Employee \r\nWHERE Name like 'A%';<\/pre>\n<p>This returns the following:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"570\" height=\"61\" class=\"wp-image-96254\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-description-automaticall-3.png\" alt=\"Graphical user interface\n\nDescription automatically generated with low confidence\" \/><\/p>\n<p>The SQL query below will return employees\u00a0whose first names end with the letter &#8216;t&#8217;:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT  *  \r\nFROM Employee \r\nWHERE Name like '%t';<\/pre>\n<p>Which you can see in the results:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"586\" height=\"73\" class=\"wp-image-96255\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/table-description-automatically-generated-with-me-2.png\" alt=\"Table\n\nDescription automatically generated with medium confidence\" \/><\/p>\n<p>The SQL query below will return employees\u00a0whose first names include the letter &#8216;C&#8217;:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT *\r\nFROM Employee \r\nWERE name like '%C%';<\/pre>\n<p>This returns the following:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"568\" height=\"91\" class=\"wp-image-96256\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-application-description-6.png\" alt=\"Graphical user interface, application\n\nDescription automatically generated\" \/><\/p>\n<p>Note: Be cautious when using <code>LIKE<\/code> expressions with leading wildcard values because normal indexes may not be particularly beneficial due to the way indexes are structured and prevent efficient index utilization that uses a leading wildcard. As a result, <code>LIKE<\/code> expressions with leading wildcards (for example, &#8216;%list&#8217;) should be avoided where possible.<\/p>\n<p>Finally, the underscore symbol (_) specifies a single character. Hence, the SQL query below will return employees with the letter &#8220;l&#8221; in the second position in their first names.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT *\r\nFROM   Employee \r\nWHERE  name like '_l%';<\/pre>\n<p>This returns the following:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"558\" height=\"45\" class=\"wp-image-96257\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/word-image-96210-17-1.png\" \/><\/p>\n<h1>Limiting the number of Rows in the output<\/h1>\n<p>It is sometimes a good idea or a requirement to display only a certain number of rows from a query. This can help improve performance when working with large tables containing millions of rows of data.<\/p>\n<p>For instance, you may be creating a search application but just want to display a portion of the results. If your search query returns hundreds of rows but you just want to display ten at a time, you would use limit clauses to narrow down your set of results.<\/p>\n<p>Another example would be if you wanted to show the top 10 or 20 highest-paid people from the employee table when your result set returned a thousand rows. The following clauses can be used with the Select statement to limit the number of rows.<\/p>\n<h2>FETCH FIRST or FETCH NEXT:<\/h2>\n<ul>\n<li>Specify the <code>NEXT<\/code> or <code>FIRST<\/code> row or rows to be returned.<\/li>\n<li>Specify the number of rows to be returned.<\/li>\n<\/ul>\n<p>The integer literal value must be 1 or greater for the fetch first clause. If the literal is missing, the value defaults to 1. This is the base syntax:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT ColumnName1, ColumnName2, ColumnNameN \r\nFROM Tablename \r\nORDER BY ColumnName1 FETCH FIRST\/NEXT number ROWS\/ROWS ONLY;<\/pre>\n<p>The <code>ORDER BY<\/code> clause is not required here, but it may be helpful if you want to control the order in which the data is returned. This is especially important when retrieving large datasets.<\/p>\n<p>The following <code>SELECT<\/code> statement returns the first row from the query of the employee table, sorted by the <code>EmployeeId<\/code> column.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT EmployeeId, Name, LastName, FirstName  \r\nFROM Employee \r\nORDER BY EmployeeId FETCH FIRST 1 ROW ONLY;<\/pre>\n<p>The result is the one row:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"338\" height=\"49\" class=\"wp-image-96258\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/word-image-96210-18-1.png\" \/><\/p>\n<p>Next, the following <code>SELECT<\/code> statement returns the first 3 rows from the employee table, sorted by the <code>EmployeeId<\/code> columns:<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT EmployeeId, Name, LastName, FirstName  \r\nFROM Employee \r\nORDER BY EmployeeId FETCH FIRST 3 ROWS ONLY;<\/pre>\n<p>Which returns:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"341\" height=\"88\" class=\"wp-image-96259\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/table-description-automatically-generated-4.png\" alt=\"Table\n\nDescription automatically generated\" \/><\/p>\n<p>In the next example, the <code>SELECT<\/code> statement returns the next 2 rows and skips the first-row employee table, sorted by the <code>EmployeeId<\/code> columns.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT EmployeeId, Name, LastName, FirstName, Department, Dob, Salary  \r\nFROM Employee \r\nORDER BY EmployeeId FETCH NEXT 2 ROWS ONLY;<\/pre>\n<p>In the result, you can see that this is still just the first 2 rows. The value of this will become more obvious in the next sections.<\/p>\n<h2><img loading=\"lazy\" decoding=\"async\" width=\"583\" height=\"89\" class=\"wp-image-96260\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-application-description-7.png\" alt=\"Graphical user interface, application\n\nDescription automatically generated\" \/><\/h2>\n<h2>OFFSET:<\/h2>\n<p>The OFFSET clause allows you to skip the first N rows in a result set before returning any rows.<\/p>\n<p>The value of the integer literal (or the dynamic parameter?) for the result offset clause must be either 0 (default if no clause is specified) or positive. If the number of rows is more than the number of rows in the main result set, no rows are returned.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT ColumnName1, ColumnName2, ColumnName N \r\nFROM Tablename \r\nORDER BY ColumnName1 OFFSET number ROWS\/ROWS;<\/pre>\n<p>The following <code>SELECT<\/code> statement skips the first two rows and returns the remaining rows sorted by the <code>EmployeeId<\/code> columns.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT EmployeeId, Name, LastName, FirstName, \r\n       Department, Dob, Salary \r\nFROM Employee \r\nORDER BY EmployeeId OFFSET  2 ROWS;<\/pre>\n<p>Now you can see in the following rows that 1001 and 1002 are not in the output, since they were the first two rows based on the sort order:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"598\" height=\"124\" class=\"wp-image-96261\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-application-table-desc-3.png\" alt=\"Graphical user interface, application, table\n\nDescription automatically generated\" \/><\/p>\n<h2>Using OFFSET together with NEXT\/FIRST<\/h2>\n<p>The <code>OFFSET<\/code> clause may be used in combination with the <code>NEXT<\/code> or <code>FIRST<\/code> clauses to restrict the number of rows returned in the result set.<\/p>\n<p>For example, the following SQL skips the first employee, employees are ordered by lowest salary to highest salary, and returns the next two employees.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT EmployeeId, Name, LastName, FirstName, Department, \r\n        Dob, Salary  \r\nFROM Employee \r\nORDER BY SALARY OFFSET  1 Rows FETCH NEXT 2 ROWS ONLY ;<\/pre>\n<h3>Result:<\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"585\" height=\"59\" class=\"wp-image-96262\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/a-picture-containing-application-description-auto-1.png\" alt=\"A picture containing application\n\nDescription automatically generated\" \/><\/p>\n<h1>Eliminate duplicates using DISTINCT:<\/h1>\n<p>The <code>SELECT<\/code> command retrieves data from table columns. But what if we only want unique data? A column in a database frequently has many duplicate values, thus there are instances when you just want to show the unique values.<\/p>\n<p>For example, a business user may require a list of the unique countries of birth of all employees of a company to assess the organization&#8217;s diversity. Because many employees may have the same birth country, we may prefer a separate count of employees by country of birth rather than a total count of employees. In this case, we can use <code>DISTINCT<\/code> keyword with a <code>SELECT<\/code> statement.<\/p>\n<p>The <code>DISTINCT<\/code> keyword specifies that only distinct (unique) data should be returned. Using <code>DISTINCT<\/code> will remove duplicates from the results table.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT DISTINCT  ColumnName \r\nFROM Tablename;<\/pre>\n<p>The following <code>SELECT<\/code> statement retrieves unique <code>Department<\/code> values from the <code>Employee<\/code> table. There are several employees with the same department, and you as a business user may require a distinct list of departments where employees work.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT DISTINCT Department \r\nFROM Employee;<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"99\" height=\"83\" class=\"wp-image-96263\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/graphical-user-interface-text-application-descr-1.png\" alt=\"Graphical user interface, text, application\n\nDescription automatically generated\" \/><\/p>\n<p><em>While it is beyond this introduction to the SELECT statement topic, beware of using DISTINCT to cover duplicated data that you don\u2019t understand. When querying more than one table it often is used to hide issues that are either a problem for the performance or correctness of a query.<\/em><\/p>\n<h1>Grouping Data for Aggregation<\/h1>\n<p>The <code>GROUP BY<\/code> clause in SQL is used to group rows of data in a result set based on the values in one or more columns. The purpose of using the <code>GROUP BY<\/code> clause is to aggregate data and obtain summary information.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT fieldname1, fieldname2, ... fieldname_n,   \r\n       aggregate_function (aggregate_fieldname)  \r\nFROM tables  \r\nWHERE conditions  \r\nGROUP BY fieldname1, fieldname2, ... fieldname_n;<\/pre>\n<p>The <code>aggregate function (aggregate fieldname)<\/code> represents an the aggregate function that you want to apply to the data, such as <code>SUM<\/code>, <code>AVG<\/code>, <code>MIN<\/code>, <code>MAX<\/code>, or <code>COUNT<\/code>. This function will operate on the values in the aggregate fieldname column.<\/p>\n<p>The data will be formed into groups based on the columns in the <code>GROUP BY<\/code> clause. The values that are not in the <code>GROUP BY<\/code> clause then are collapsed into scalar values by the aggregate function. Rows with identical values in the grouping columns are grouped. In the query result, each group is interpreted as a single row and aggregate functions (like SUM, MIN, MAX) can be applied to the results For example, if the grouping had three rows with the same value, you could do <code>COUNT(*)<\/code> as an aggregate function and it would return 3.<\/p>\n<p><code>GROUP BY<\/code> is an optional part of a query. It goes after the <code>WHERE<\/code> clause or the <code>FROM<\/code> clause if the <code>WHERE<\/code> clause is not needed.<\/p>\n<p>For instance, you want to know the total salary of a department. You should use the <code>SUM<\/code> aggregate function and group the data by departments.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT Department ,Sum(Salary) FROM Employee  GROUP BY Department;<\/pre>\n<p>In our data set, this will return:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"198\" height=\"91\" class=\"wp-image-96264\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/table-description-automatically-generated-5.png\" alt=\"Table\n\nDescription automatically generated\" \/><\/p>\n<h2>Filtering Groups of Data<\/h2>\n<p>The <code>HAVING<\/code> clause in SQL is used in conjunction with the <code>GROUP<\/code> <code>BY<\/code> clause to filter groups based on a specific condition. The <code>HAVING<\/code> clause operates on the results of the aggregate function, whereas the <code>WHERE<\/code>&#8221; clause operates on individual rows.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT fieldname1, fieldname2, ... fieldname_n,   \r\n       aggregate_function (aggregate_fieldname)  \r\nFROM tables  \r\nWHERE conditions  \r\nGROUP BY fieldname1, fieldname2, ... fieldname_n \r\nHAVING aggregate_condition;  <\/pre>\n<p>The aggregate condition is the condition that you want to apply to the groups of data, using the results of the aggregate function. For example, you could specify <code>HAVING<\/code> <code>AVG(fieldname2) &gt; value<\/code> to only show the groups where the average of fieldname2 is greater than a certain value.<\/p>\n<p>For an example, the following query returns the average salary for all departments that have an average over 61000 using the <code>HAVING<\/code> clause.<\/p>\n<pre class=\"lang:tsql theme:ssms2012-simple-talk\">SELECT Department, AVG(salary)\r\nFROM Employee\r\nGROUP BY Department HAVING AVG(Salary) &gt; 61000;<\/pre>\n<p>The result is:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"196\" height=\"71\" class=\"wp-image-96265\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2023\/03\/table-description-automatically-generated-with-me-3.png\" alt=\"Table\n\nDescription automatically generated with medium confidence\" \/><\/p>\n<h1>Summary<\/h1>\n<p>In this introduction to the SELECT statement in Oracle, we have looked at how to query a single table, return only certain columns, put that data into a specified order, filter it down to a set of (if desired, distinct) rows, and then group that data and do aggregates.<\/p>\n<p>It is a lot in one introduction, but the SELECT statement is the one statement that pretty much every Oracle user of any level will use. In the future, I will look at querying multiple tables at the same time, as well as how to create and remove data from a database.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The SELECT statement is used to retrieve information from a database. Following the execution of a SELECT statement, a tabular result is held in a result table (called a result set). It allows you to select the table columns depending on a set of criteria. SELECT statements might be as straightforward as selecting a few&#8230;&hellip;<\/p>\n","protected":false},"author":341091,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[53,143533],"tags":[],"coauthors":[158987],"class_list":["post-96210","post","type-post","status-publish","format-standard","hentry","category-featured","category-oracle-databases"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/96210","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/341091"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=96210"}],"version-history":[{"count":12,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/96210\/revisions"}],"predecessor-version":[{"id":96239,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/96210\/revisions\/96239"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=96210"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=96210"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=96210"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=96210"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}