Select From Where Select From Where Select From Select From Where Select From Select From Select From Where IS NOT Null Order BY Desc Where
Select From Where Select From Where Select From Select From Where Select From Select From Select From Where IS NOT Null Order BY Desc Where
SELECT max(sal) FROM emp WHERE sal< (SELECT max(sal) FROM emp)
SELECT min(sal) FROM (SELECT sal FROM emp WHERE sal IS NOT NULL ORDER BY sal
DESC) WHERE rownum<=&rownum;
select salary from emp e1 where (n-1)=(select count(*)
from emp where salary > e1.salary )
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further
classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
INNER JOIN
Inner join shows matches only when they exist in both tables. Example in the below SQL
there are two tables Customers and Orders and the inner join in made on
Customers.Customerid and Orders.Customerid. So this SQL will only give you result with
customers who have orders. If the customer does not have order, it will not display that
record.
Left join will display all records in left table of the SQL statement. In SQL below customers
with or without orders will be displayed. Order data for customers without orders appears as
NULL values. For example, you want to determine the amount ordered by each customer
and you need to see who has not ordered anything as well. You can also see the LEFT
OUTER JOIN as a mirror image of the RIGHT OUTER JOIN (Is covered in the next section) if
you switch the side of each table.
Right join will display all records in right table of the SQL statement. In SQL below all orders
with or without matching customer records will be displayed. Customer data for orders
without customers appears as NULL values. For example, you want to determine if there are
any orders in the data with undefined CustomerID values (say, after a conversion or
something like it). You can also see the RIGHT OUTER JOIN as a mirror image of the LEFT
OUTER JOIN if you switch the side of each table.
Q: How can you compare a part of the name rather than the entire name?
A: SELECT * FROM people WHERE empname LIKE '%ab%'
Would return a recordset with records consisting empname the sequence 'ab' in
empname .
Q: What is the INSERT statement?
A: The INSERT statement lets you insert information into a database.
Truncating: (Data alone deleted), Performs an automatic commit, Faster than delete
Q: What's the difference between a primary key and a unique key?
A: Both primary key and unique enforce uniqueness of the column on which they are
defined. But by default primary key creates a clustered index on the column, where are
unique creates a nonclustered index by default. Another major difference is that, primary
key doesn't allow NULLs, but unique key allows one NULL only.
Q: What are cursors? Explain different types of cursors. What are the
disadvantages of cursors? How can you avoid cursors?
A: Cursors allow row-by-row prcessing of the resultsets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for
more information.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a
network roundtrip, where as a normal SELECT query makes only one rowundtrip,
however large the resultset is. Cursors are also costly because they require more
resources and temporary storage (results in more IO operations). Furthere, there are
restrictions on the SELECT statements that can be used with some types of cursors.
Most of the times, set based operations can be used instead of cursors.
Q: What are triggers? How to invoke a trigger on demand?
A: Triggers are special kind of stored procedures that get executed automatically when an
INSERT, UPDATE or DELETE operation takes place on a table.
Triggers can't be invoked on demand. They get triggered only when an associated action
(INSERT, UPDATE, DELETE) happens on the table on which they are defined.
Triggers are generally used to implement business rules, auditing. Triggers can also be
used to extend the referential integrity checks, but wherever possible, use constraints for
this purpose, instead of triggers, as constraints are much faster.
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further
classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
Q: What is a self join?
A: Self join is just like any other join, except that two instances of the same table will be
joined in the query.
The SQL SELECT INTO statement is used to select data from a SQL database table and to insert it
to a different table at the same time.
If we want to make an exact copy of the data in our Customers table, we need the following SQL
SELECT INTO statement:
SELECT *
INTO Customers_copy
FROM Customers
The SQL DISTINCT clause is used together with the SQL SELECT keyword, to return a dataset with
unique entries for certain database table column.
We will use our Customers database table to illustrate the usage of SQL DISTINCT.
For example if we want to select all distinct surnames from our Customers table, we will use the
following SQL DISTINCT statement:
The SQL INSERT INTO syntax has 2 main forms and the result of either of them is adding a new
row into the database table.
The first syntax form of the INSERT INTO SQL clause doesn't specify the column names where the
data will be inserted, but just their values:
The second form of the SQL INSERT INTO command, specifies both the columns and the values to
be inserted in them:
As you might already have guessed, the number of the columns in the second INSERT INTO syntax
form must match the number of values into the SQL statement, otherwise you will get an error.
If we want to insert a new row into our Customers table, we are going to use one of the following 2
SQL statements:
INSERT INTO Customers
VALUES ('Peter', 'Hunt', 'peter.hunt@tgmail.net', '1/1/1974', '626 888-8888')
The SQL IN clause allows you to specify discrete values in your SQL WHERE search criteria.
SQL aliases can be used with database tables and with database table columns, depending on task
you are performing.
SQL column aliases are used to make the output of your SQL queries easy to read and more
meaningful:
In the example above we created SQL alias SumHoursPerEmployee and the result of this SQL query
will be the following:
Employee SumHoursPerEmployee
John Smith 25
Allan Babel 24
Tina Crown 27
The SQL GROUP BY statement is used along with the SQL aggregate functions like SUM to provide
means of grouping the result dataset by certain database table column(s).
The best way to explain how and when to use the SQL GROUP BY statement is by example, and
that’s what we are going to do.
Consider the following database table called EmployeeHours storing the daily hours for each
employee of a factious company:
Employee Date Hours
John Smith 5/6/2004 8
Allan Babel 5/6/2004 8
Tina Crown 5/6/2004 8
John Smith 5/7/2004 9
Allan Babel 5/7/2004 8
Tina Crown 5/7/2004 10
John Smith 5/8/2004 8
Allan Babel 5/8/2004 8
Tina Crown 5/8/2004 9
If the manager of the company wants to get the simple sum of all hours worked by all employees,
he needs to execute the following SQL statement:
But what if the manager wants to get the sum of all hours for each of his employees?
To do that he need to modify his SQL query and use the SQL GROUP BYstatement:
Employee Hours
John Smith 25
Allan Babel 24
Tina Crown 27
As you can see we have only one entry for each employee, because we are grouping by the
Employee column.
The SQL GROUP BY clause can be used with other SQL aggregate functions, for example SQL AVG:
Employee
Hours
John Smith
8.33
Allan Babel
8
Tina Crown
9
The SQL HAVING clause is used to restrict conditionally the output of a SQL statement, by a SQL
aggregate function used in your SELECT list of columns.
You can't specify criteria in a SQL WHERE clause against a column in the SELECT list for which SQL
aggregate function is used. For example the following SQL statement will generate an error:
The SQL HAVING clause is used to do exactly this, to specify a condition for an aggregate function
which is used in your query:
The above SQL statement will select all employees and the sum of their respective hours, as long
as this sum is greater than 24. The result of the SQL HAVING clause can be seen below:
Employee Hours
John Smith 25
Tina Crown 27
SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database.
Wildcard Description
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist] Any single character not in charlist
or
[!charlist]
Next, we want to select the persons living in a city that contains the pattern "nes" from the "Persons"
table.
Next, we want to select the persons with a last name that starts with "S", followed by any character,
followed by "end", followed by any character, followed by "on" from the "Persons" table.
Next, we want to select the persons with a last name that do not start with "b" or "s" or "p" from the
"Persons" table.
he IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
IN Operator Example
The "Persons" table:
Now we want to select the persons with a last name equal to "Hansen" or "Pettersen" from the table
above.
The BETWEEN operator is used in a WHERE clause to select a range of data between
two values.
Now we want to select the persons with a last name alphabetically between "Hansen" and "Pettersen"
from the table above.
In some databases, persons with the LastName of "Hansen" or "Pettersen" will not be listed, because
the BETWEEN operator only selects fields that are between and excluding the test values.
In other databases, persons with the LastName of "Hansen" or "Pettersen" will be listed, because the
BETWEEN operator selects fields that are between and including the test values.
And in other databases, persons with the LastName of "Hansen" will be listed, but "Pettersen" will not
be listed (like the example above), because the BETWEEN operator selects fields between the test
values, including the first test value and excluding the last test value.
Therefore: Check how your database treats the BETWEEN operator.
Example 2
To display the persons outside the range in the previous example, use NOT BETWEEN:
SQL joins are used to query data from two or more tables, based on a relationship
between certain columns in these tables.
SQL JOIN
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a
relationship between certain columns in these tables.
A primary key is a column (or a combination of columns) with a unique value for each row. Each
primary key value must be unique within the table. The purpose is to bind data together, across
tables, without repeating all of the data in every table.
Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two rows
can have the same P_Id. The P_Id distinguishes two persons even if they have the same name.
Note that the "O_Id" column is the primary key in the "Orders" table and that the "P_Id" column
refers to the persons in the "Persons" table without using their names.
Notice that the relationship between the two tables above is the "P_Id" column.
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left
table
FULL JOIN: Return rows when there is a match in one of the tables
Indexes
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the
indexes also need an update). So you should only create indexes on columns (and tables) that will be
frequently searched against.
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the
syntax for creating indexes in your database.
If you want to create an index on a combination of columns, you can list the column names within the
parentheses, separated by commas:
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
To change the data type of a column in a table, use the following syntax:
Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data type
specifies what type of data the column can hold. For a complete reference of all the data types
available in MS Access, MySQL, and SQL Server, go to our complete Data Types reference.
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two-digit or
four-digit format.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or
more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the
data were coming from one single table.
Note: A view always shows up-to-date data! The database engine recreates the data, using the view's
SQL statement, every time a user queries a view.
The view "Current Product List" lists all active products (products that are not discontinued) from the
"Products" table. The view is created with the following SQL:
Another view in the Northwind sample database selects every product in the "Products" table with a
unit price higher than the average unit price:
Another view in the Northwind database calculates the total sale for each category in 1997. Note that
this view selects its data from another view called "Product Sales for 1997":
We can also add a condition to the query. Now we want to see the total sale only for the category
"Beverages":
Now we want to add the "Category" column to the "Current Product List" view. We will update the
view with the following SQL:
Unicode strings:
Binary types:
Number types:
Date types:
or
or
SELECT column_name
FROM table_name AS table_alias
BETWEEN SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE CREATE DATABASE database_name
CREATE TABLE CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name2 data_type,
...
)
CREATE INDEX CREATE INDEX index_name
ON table_name (column_name)
or
or
or
or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
SELECT TOP SELECT TOP number|percent column_name(s)
FROM table_name
TRUNCATE TABLE TRUNCATE TABLE table_name
UNION SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
UNION ALL SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
UPDATE UPDATE table_name
SET column1=value, column2=value,...
WHERE some_column=some_value
WHERE SELECT column_name(s)
FROM table_name
WHERE column_name operator value