Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Directories
Directories, like folders on a Macintosh, are used to group files together in a hierarchical
structure.
Finding things
• ff --- find files anywhere on the system. This can be extremely useful if you've
forgotten in which directory you put a file, but do remember the name. In fact, if
you use ff -p you don't even need the full name, just the beginning. This can also
be useful for finding other things on the system, e.g. documentation.
• grep string filename(s) --- looks for the string in the files. This can be useful a lot
of purposes, e.g. finding the right file among many, figuring out which is the right
version of something, and even doing serious corpus work. grep comes in several
varieties (grep, egrep, and fgrep) and has a lot of very flexible options. Check
out the man pages if this sounds good to you.
Miscellaneous tools
• webster word --- looks up the word in an electronic version of Webster's
dictionary and returns the definition(s)
• date --- shows the current date and time.
• cal --- shows a calendar of the current month. Use e.g., 'cal 10 1995' to get that for
October 95, or 'cal 1995' to get the whole year.
You can find out more about these commands by looking up their manpages:
man commandname --- shows you the manual page for the command
File Management
emacs: `Using the emacs text editor'
mkdir: `Creating a directory'
cd: `Changing your current working directory'
ls: `Finding out what files you have'
cp: `Making a copy of a file'
mv: `Changing the name of a file'
rm: `Getting rid of unwanted files'
chmod: `Controlling access to your files'
cmp: Comparing two files
wc: Word, line, and character count
compress: Compress a file
Communication
e-mail: `Sending and receiving electronic mail'
talk: Talk to another user
write: Write messages to another user
sftp: Secure file transfer protocol
Information
man: Manual pages
quota -v: Finding out your available disk space quota
ical: `Using the Ical personal organizer'
finger: Getting information about a user
passwd: Changing your password
who: Finding out who's logged on
Printing
lpr: `Printing'
lprm: Removing a print job
lpq: Checking the print queues
Job control
ps: `Finding your processes'
kill: `Killing a process'
nohup: Continuing a job after logout
nice: Changing the priority of a job
&: `What is a background process?'
Cntrl-z: Suspending a process
fg: `Resuming a suspended process'
Next: Selecting a Unix shell
See also: Learning the basic Unix tools
Previous: Unix fundamentals
Site map
Index: Keyword index to help pages
Help: New Mexico Tech Computer Center: Help System
cat
This is one of the most flexible Unix commands. We can use to create, view and
concatenate files. For our first example we create a three-item English-Spanish dictionary
in a file called "dict."
% cat >dict
red rojo
green verde
blue azul
<control-D>
%
<control-D> stands for "hold the control key down, then tap 'd'". The symbol > tells the
computer that what is typed is to be put into the file dict. To view a file we use cat in a
different way:
% cat dict
red rojo
green verde
blue azul
%
If we wish to add text to an existing file we do this:
% cat >>dict
white blanco
black negro
<control-D>
%
Now suppose that we have another file tmp that looks like this:
% cat tmp
cat gato
dog perro
%
Then we can join dict and tmp like this:
% cat dict tmp >dict2
We could check the number of lines in the new file like this:
% wc -l dict2
8
The command wc counts things --- the number of characters, words, and line in a file.
chmod
This command is used to change the permissions of a file or directory. For example to
make a file essay.001 readable by everyone, we do this:
% chmod +x mycommand
Now we can run mycommand as a command.
To check the permissions of a file, use ls -l . For more information on chmod, use man
chmod.
cd
Use cd to change directory. Use pwd to see what directory you are in.
% cd english
% pwd
% /u/ma/jeremy/english
% ls
novel poems
% cd novel
% pwd
% /u/ma/jeremy/english/novel
% ls
ch1 ch2 ch3 journal scrapbook
% cd ..
% pwd
% /u/ma/jeremy/english
% cd poems
% cd
% /u/ma/jeremy
Jeremy began in his home directory, then went to his english subdirectory. He listed this
directory using ls , found that it contained two entries, both of which happen to be
diretories. He cd'd to the diretory novel, and found that he had gotten only as far as
chapter 3 in his writing. Then he used cd .. to jump back one level. If had wanted to jump
back one level, then go to poems he could have said cd ../poems. Finally he used cd with
no argument to jump back to his home directory.
cp
Use cp to copy files or directories.
% cp foo foo.2
This makes a copy of the file foo.
% cp ~/poems/jabber .
This copies the file jabber in the directory poems to the current directory. The symbol "."
stands for the current directory. The symbol "~" stands for the home directory.
date
Use this command to check the date and time.
% date
Fri Jan 6 08:52:42 MST 1995
echo
The echo command echoes its arguments. Here are some examples:
% echo this
this
% echo $EDITOR
/usr/local/bin/emacs
% echo $PRINTER
b129lab1
Things like PRINTER are so-called environment variables. This one stores the name of the
default printer --- the one that print jobs will go to unless you take some action to change
things. The dollar sign before an environment variable is needed to get the value in the
variable. Try the following to verify this:
% echo PRINTER
PRINTER
ftp
Use ftp to connect to a remote machine, then upload or download files. See also: ncftp
Example 1: We'll connect to the machine fubar.net, then change director to mystuff,
then download the file homework11:
% ftp solitude
Connected to fubar.net.
220 fubar.net FTP server (Version wu-2.4(11) Mon Apr 18 17:26:33
MDT 1994) ready.
Name (solitude:carlson): jeremy
331 Password required for jeremy.
Password:
230 User jeremy logged in.
ftp> cd mystuff
250 CWD command successful.
ftp> get homework11
ftp> quit
Example 2: We'll connect to the machine fubar.net, then change director to mystuff,
then upload the file collected-letters:
% ftp solitude
Connected to fubar.net.
220 fubar.net FTP server (Version wu-2.4(11) Mon Apr 18 17:26:33
MDT 1994) ready.
Name (solitude:carlson): jeremy
331 Password required for jeremy.
Password:
230 User jeremy logged in.
ftp> cd mystuff
250 CWD command successful.
ftp> put collected-letters
ftp> quit
The ftp program sends files in ascii (text) format unless you specify binary mode:
ftp> binary
ftp> put foo
ftp> ascii
ftp> get bar
The file foo was transferred in binary mode, the file bar was transferred in ascii mode.
grep
Use this command to search for information in a file or files. For example, suppose that
we have a file dict whose contents are
red rojo
green verde
blue azul
white blanco
black negro
Then we can look up items in our file like this;
% grep red dict
red rojo
% grep blanco dict
white blanco
% grep brown dict
%
Notice that no output was returned by grep brown. This is because "brown" is not in our
dictionary file.
Grep can also be combined with other commands. For example, if one had a file of phone
numbers named "ph", one entry per line, then the following command would give an
alphabetical list of all persons whose name contains the string "Fred".
% man grep
head
% head essay.001
displays the first 10 lines of the file essay.001 To see a specific number of lines, do this:
% head -n 20 essay.001
This displays the first 20 lines of the file.
ls
Use ls to see what files you have. Your files are kept in something called a directory.
% ls
foo letter2
foobar letter3
letter1 maple-assignment1
%
Note that you have six files. There are some useful variants of the ls command:
% ls l*
letter1 letter2 letter3
%
Note what happened: all the files whose name begins with "l" are listed. The asterisk (*)
is the " wildcard" character. It matches any string.
lpr
This is the standard Unix command for printing a file. It stands for the ancient "line
printer." See
% man lpr
for information on how it works. See print for information on our local intelligent print
command.
mkdir
Use this command to create a directory.
% mkdir essays
To get "into" this directory, do
% cd essays
To see what files are in essays, do this:
% ls
There shouldn't be any files there yet, since you just made it. To create files, see cat or
emacs.
more
More is a command used to read text files. For example, we could do this:
% more poems
The effect of this to let you read the file "poems ". It probably will not fit in one screen,
so you need to know how to "turn pages". Here are the basic commands:
mv
% mv foo foobar
ncftp
Use ncftp for anonymous ftp --- that means you don't have to have a password.
% ncftp ftp.fubar.net
Connected to ftp.fubar.net
> get jokes.txt
print
This is a moderately intelligent print command.
% print foo
% print notes.ps
% print manuscript.dvi
In each case print does the right thing, regardless of whether the file is a text file (like
foo ), a postcript file (like notes.ps, or a dvi file (like manuscript.dvi. In these
examples the file is printed on the default printer. To see what this is, do
% print
and read the message displayed. To print on a specific printer, do this:
% print foo jwb321
% print notes.ps jwb321
% print manuscript.dvi jwb321
To change the default printer, do this:
% setenv PRINTER jwb321
pwd
Use this command to find out what directory you are working in.
% pwd
/u/ma/jeremy
% cd homework
% pwd
/u/ma/jeremy/homework
% ls
assign-1 assign-2 assign-3
% cd
% pwd
/u/ma/jeremy
%
Jeremy began by working in his "home" directory. Then he cd 'd into his homework
subdirectory. Cd means " change directory". He used pwd to check to make sure he was
in the right place, then used ls to see if all his homework files were there. (They were).
Then he cd'd back to his home directory.
rm
Use rm to remove files from your directory.
% rm foo
remove foo? y
% rm letter*
remove letter1? y
remove letter2? y
remove letter3? n
%
The first command removed a single file. The second command was intended to remove
all files beginning with the string "letter." However, our user (Jeremy?) decided not to
remove letter3.
rmdir
Use this command to remove a directory. For example, to remove a directory called
"essays", do this:
% rmdir essays
A directory must be empty before it can be removed. To empty a directory, use rm.
rsh
Use this command if you want to work on a computer different from the one you are
currently working on. One reason to do this is that the remote machine might be faster.
For example, the command
% rsh solitude
connects you to the machine solitude. This is one of our public workstations and is
fairly fast.
setenv
% echo $PRINTER
labprinter
% setenv PRINTER myprinter
% echo $PRINTER
myprinter
sort
Use this commmand to sort a file. For example, suppose we have a file dict with
contents
red rojo
green verde
blue azul
white blanco
black negro
Then we can do this:
% sort dict
black negro
blue azul
green verde
red rojo
white blanco
Here the output of sort went to the screen. To store the output in file we do this:
% sort dict >dict.sorted
You can check the contents of the file dict.sorted using cat , more , or emacs .
tail
% tail essay.001
displays the last 10 lines of the file essay.001 To see a specific number of lines, do this:
% tail -n 20 essay.001
This displays the last 20 lines of the file.
tar
Use create compressed archives of directories and files, and also to extract directories and
files from an archive. Example:
telnet
Use this command to log in to another machine from the machine you are currently
working on. For example, to log in to the machine "solitude", do this:
% telnet solitude
wc
Use this command to count the number of characters, words, and lines in a file. Suppose,
for example, that we have a file dict with contents
red rojo
green verde
blue azul
white blanco
black negro
Then we can do this
% wc dict
5 10 56 tmp
% wc -l dict
5 tmp
% wc -w dict
10 tmp
% wc -c dict
56 tmp
dummy
Under construction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5. What structure can you implement for the database to speed up table reads?
- Follow the rules of DB tuning we have to: 1] properly use indexes ( different
types of indexes) 2] properly locate different DB objects across different
tablespaces, files and so on.3] create a special space (tablespace) to locate some of
the data with special datatype ( for example CLOB, LOB and …)
6. What are the tradeoffs with having indexes? - 1. Faster selects, slower updates.
2. Extra storage space to store indexes. Updates are slower because in addition to
updating the table you have to update the index.
7. What is a "join"? - ‘join’ used to connect two or more tables logically with or
without common field.
8. What is "normalization"? "Denormalization"? Why do you sometimes want
to denormalize? - Normalizing data means eliminating redundant information
from a table and organizing the data so that future changes to the table are easier.
Denormalization means allowing redundancy in a table. The main benefit of
denormalization is improved performance with simplified data retrieval and
manipulation. This is done by reduction in the number of joins needed for data
processing.
9. What is a "constraint"? - A constraint allows you to apply simple referential
integrity checks to a table. There are four primary types of constraints that are
currently supported by SQL Server: PRIMARY/UNIQUE - enforces uniqueness
of a particular table column. DEFAULT - specifies a default value for a column in
case an insert operation does not provide one. FOREIGN KEY - validates that
every value in a column exists in a column of another table. CHECK - checks that
every value stored in a column is in some specified list. Each type of constraint
performs a specific type of action. Default is not a constraint. NOT NULL is one
more constraint which does not allow values in the specific column to be null.
And also it the only constraint which is not a table level constraint.
10. What types of index data structures can you have? - An index helps to faster
search values in tables. The three most commonly used index-types are: - B-Tree:
builds a tree of possible values with a list of row IDs that have the leaf value.
Needs a lot of space and is the default index type for most databases. - Bitmap:
string of bits for each possible value of the column. Each bit string has one bit for
each row. Needs only few space and is very fast.(however, domain of value
cannot be large, e.g. SEX(m,f); degree(BS,MS,PHD) - Hash: A hashing algorithm
is used to assign a set of characters to represent a text string such as a composite
of keys or partial keys, and compresses the underlying data. Takes longer to build
and is supported by relatively few databases.
11. What is a "primary key"? - A PRIMARY INDEX or PRIMARY KEY is
something which comes mainly from
database theory. From its behavior is almost the same as an UNIQUE INDEX, i.e.
there may only be one of each value in this column. If you call such an INDEX
PRIMARY instead of UNIQUE, you say something about
your table design, which I am not able to explain in few words. Primary Key is a
type of a constraint enforcing uniqueness and data integrity for each row of a
table. All columns participating in a primary key constraint must possess the NOT
NULL property.
12. What is a "functional dependency"? How does it relate to database table
design? - Functional dependency relates to how one object depends upon the
other in the database. for example, procedure/function sp2 may be called by
procedure sp1. Then we say that sp1 has functional dependency on sp2.
13. What is a "trigger"? - Triggers are stored procedures created in order to enforce
integrity rules in a database. A trigger is executed every time a data-modification
operation occurs (i.e., insert, update or delete). Triggers are executed
automatically on occurance of one of the data-modification operations. A trigger
is a database object directly associated with a particular table. It fires whenever a
specific statement/type of statement is issued against that table. The types of
statements are insert,update,delete and query statements. Basically, trigger is a set
of SQL statements A trigger is a solution to the restrictions of a constraint. For
instance: 1.A database column cannot carry PSEUDO columns as criteria where a
trigger can. 2. A database constraint cannot refer old and new values for a row
where a trigger can.
14. Why can a "group by" or "order by" clause be expensive to process? -
Processing of "group by" or "order by" clause often requires creation of
Temporary tables to process the results of the query. Which depending of the
result set can be very expensive.
15. What is "index covering" of a query? - Index covering means that "Data can be
found only using indexes, without touching the tables"
16. What types of join algorithms can you have?
17. What is a SQL view? - An output of a query can be stored as a view. View acts
like small table which meets our criterion. View is a precomplied SQL query
which is used to select data from one or more tables. A view is like a table but it
doesn’t physically take any space. View is a good way to present data in a
particular format if you use that query quite often. View can also be used to
restrict users from accessing the tables directly.
18. What are the different types of joins?
19. Explain normalization with examples.
20. What cursor type do you use to retrieve multiple recordsets?
21. Diffrence between a “where” clause and a “having” clause
22. What is the difference between “procedure” and “function”?
23. How will you copy the structure of a table without copying the data?
24. How to find out the database name from SQL*PLUS command prompt?
25. Tadeoffs with having indexes
26. Talk about “Exception Handling” in PL/SQL?
27. What is the diference between “NULL in C” and “NULL in Oracle?”
28. What is Pro*C? What is OCI?
29. Give some examples of Analytical functions.
30. What is the difference between “translate” and “replace”?
31. What is DYNAMIC SQL method 4?
32. How to remove duplicate records from a table?
33. What is the use of ANALYZing the tables?
34. How to run SQL script from a Unix Shell?
35. What is a “transaction”? Why are they necessary?
36. Explain Normalizationa dn Denormalization with examples.
37. When do you get contraint violtaion? What are the types of constraints?
38. How to convert RAW datatype into TEXT?
39. Difference - Primary Key and Aggregate Key
40. How functional dependency is related to database table design?
41. What is a “trigger”?
42. Why can a “group by” or “order by” clause be expensive to process?
43. What are “HINTS”? What is “index covering” of a query?
44. What is a VIEW? How to get script for a view?
45. What are the Large object types suported by Oracle?
46. What is SQL*Loader?
47. Difference between “VARCHAR” and “VARCHAR2″ datatypes.
48. What is the difference among “dropping a table”, “truncating a table” and
“deleting all records” from a table.
49. Difference between “ORACLE” and “MICROSOFT ACCESS” databases.
50. How to create a database link?
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
The INNER JOIN keyword return rows when there is at least one match in both tables. If
there are rows in "Persons" that do not have matches in "Orders", those rows will NOT be
listed.
Now we want to list all the persons and their orders - if any, from the tables above.
The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there
are no matches in the right table (Orders).
The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if
there are no matches in the left table (Persons).
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Now we want to list all the persons and their orders, and all the orders with their persons.
The FULL JOIN keyword returns all the rows from the left table (Persons), and all the
rows from the right table (Orders). If there are rows in "Persons" that do not have
matches in "Orders", or if there are rows in "Orders" that do not have matches in
"Persons", those rows will be listed as well.
Each table should have a primary key, and each table can have only one primary key.
MySQL:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
Note: If you use the ALTER TABLE statement to add a primary key, the primary key
column(s) must already have been declared to not contain NULL values (when the table
was first created).
Let's illustrate the foreign key with an example. Look at the following two tables:
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the
"Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy link
between tables.
The FOREIGN KEY constraint also prevents that invalid data is inserted into the foreign
key column, because it has to be one of the values contained in the table it points to.
MySQL:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
1.Simple/Inner/Natural Join
2.Equi(contains only = sign) /Non-Equi Joins(other simbles)
3.Outer Joins(Left Outer Join/Right Outer Join)
4.Cross Join
5.Self Join
3.Outer Join
i.Full Outer Join
11.Left Outer Join
iii.Right Outer Join
LEFT -- only unmatched rows from the left side table (table-
1) are retained
RIGHT -- only unmatched rows from the right side table
(table-2) are retained
FULL -- unmatched rows from both tables (table-1 and table-
2) are retained
SELECT assign.project, projects.name, assign.percentage
FROM projects LEFT OUTER JOIN assign
ON projects.id = assign.project ;
select
last_name,
department_name
from
employees e,
departments d
where
e.department_id = d.department_id(+);
select
last_name,
department_name
from
employees e
left outer join
departments d
on
e.department_id = d.department_id;
A right outer join will return all the rows that an inner join returns plus one row for
each of the other rows in the second table that did not have a match in the first
table. It is the same as a left outer join with the tables specified in the opposite
order.
The query that was used as the left outer join example could be rewritten as a right
outer join as follows:
Result
State:city State:state Region:city Region:area
Jacksonville FL Jacksonville South
Miami FL Miami South
Nashville TN NULL NULL
Result
State:city State:state Region:city Region:area
Jacksonville FL Jacksonville South
Miami FL Miami South
NULL NULL New Orleans South
Result
State:city State:state Region:city Region:area
Jacksonville FL Jacksonville South
Miami FL Miami South
Nashville TN NULL NULL
NULL NULL New Orleans South
Important:
These examples use the tables introduced on page Join of two tables.
Outer joins
In most cases, tables are joined according to search conditions that find only the rows
with matching values; this type of join is known as an inner equijoin. In some cases,
however, decision-support analysis requires outer joins, which retrieve both matching and
non-matching rows, or non-equijoins, which express, for example, a greater-than or less-
than relationship.
An outer join operation returns all the rows returned by an inner join plus all the rows
from one table that do not match any row from the other table. An outer join can be left,
right, or full, depending on whether rows from the left, right, or both tables are retained.
The first table listed in the FROM clause is referred to as the left table and the second as
the right table. For all three types of outer join, NULLs are used to represent empty
columns in rows that do not match.
Syntax
As shown in the preceding examples, an outer join between two tables can be specified in
the FROM clause with the OUTER JOIN keywords followed by the ON subclause:
>>-FROM--table_1--+-LEFT--+--OUTER JOIN--table_2---------------->
+-RIGHT-+
'-FULL--'
>--ON--table_1.column--=--table_2.column-----------------------><
sQL Commands:
SQL commands are instructions used to communicate with the database to perform
specific task that work with data. SQL commands can be used not only for searching the
database but also to perform various other functions like, for example, you can create
tables, add data to tables, or modify data, drop the table, set permissions for users. SQL
commands are grouped into four major categories depending on their functionality:
• Data Definition Language (DDL) - These SQL commands are used for creating,
modifying, and dropping the structure of database objects. The commands are
CREATE, ALTER, DROP, RENAME, and TRUNCATE.
• Data Manipulation Language (DML) - These SQL commands are used for
storing, retrieving, modifying, and deleting data. These commands are SELECT,
INSERT, UPDATE, and DELETE.
• Transaction Control Language (TCL) - These SQL commands are used for
managing changes affecting the data. These commands are COMMIT,
ROLLBACK, and SAVEPOINT.
• Data Control Language (DCL) - These SQL commands are used for providing
security to database objects. These commands are GRANT and REVOKE
• table-name is the name of the table from which the information is retrieved.
• column_list includes one or more columns from which data is retrieved.
• The code within the brackets is optional.
NOTE: These database tables are used here for better explanation of SQL commands. In
reality, the tables can have different columns and different data.
For example, consider the table student_details. To select the first name of all the
students the query would be like:
NOTE: The commands are not case sensitive. The above SELECT statement can also be
written as "select first_name from students_details;"
You can also retrieve data from more than one column. For example, to select first name
and last name of all the students.
You can also use clauses like WHERE, GROUP BY, HAVING, ORDER BY with
SELECT statement. We will discuss these commands in coming chapters.
NOTE: In a SQL SELECT statement only SELECT and FROM statements are
mandatory. Other clauses like WHERE, ORDER BY, GROUP BY, HAVING are
optional.
How to use expressions in SQL SELECT Statement?
Expressions combine many arithmetic operators, they can be used in SELECT, WHERE
and ORDER BY Clauses of the SQL SELECT Statement.
Here we will explain how to use expressions in the SQL SELECT Statement. About
using expressions in WHERE and ORDER BY clause, they will be explained in their
respective sections.
The operators are evaluated in a specific order of precedence, when more than one
arithmetic operator is used in an expression. The order of evaluation is: parentheses,
division, multiplication, addition, and subtraction. The evaluation is performed from the
left to the right of the expression.
For example: If we want to display the first and last name of an employee combined
together, the SQL Select Statement would be like
Output:
Output:
emp_name
-------------
Rahul Sharma
Anjali Bhagwat
Stephen Fleming
Shekar Gowda
Priya Chandra
SQL Alias
SQL Aliases are defined for columns and tables. Basically aliases is created to make the
column selected more readable.
For Example: To select the first name of all the students, the query would be like:
In the above query, the column first_name is given a alias as 'name'. So when the result is
displayed the column name appears as 'Name' instead of 'first_name'.
Output:
Name
-------------
Rahul Sharma
Anjali Bhagwat
Stephen Fleming
Shekar Gowda
Priya Chandra
In the above query, alias 's' is defined for the table student_details and the column
first_name is selected from the table.
So SQL offers a feature called WHERE clause, which we can use to restrict the data that
is retrieved. The condition you provide in the WHERE clause filters the rows retrieved
from the table and gives you only those rows which you expected to see. WHERE clause
can be used along with SELECT, DELETE, UPDATE statements.
For Example: To find the name of a student with id 100, the query would be like:
Comparison Operators and Logical Operators are used in WHERE Clause. These
operators are discussed in the next chapter.
NOTE: Aliases defined for the columns in the SELECT statement cannot be used in the
WHERE clause to set conditions. Only aliases created for tables can be used to reference
the columns in the table.
For example: Lets consider the employee table. If you want to display employee name,
current salary, and a 20% increase in the salary for only those products where the
percentage increase in salary is greater than 30000, the SELECT statement can be written
as shown below
Output:
name salary new_salary
---------- ---------
----------------
- -
Hrithik 35000 37000
Harsha 35000 37000
Priya 30000 360000
NOTE: Aliases defined in the SELECT Statement can be used in WHERE Clause.
SQL Operators
There are two type of Operators, namely Comparison Operators and Logical Operators.
These operators are used mainly in the WHERE clause, HAVING clause to filter the data
to be selected.
Comparison Operators:
Comparison operators are used to compare the column data with specific values in a
condition.
Comparison Operators are also used along with the SELECT statement to filter data
based on specific conditions.
Comparison
Description
Operators
= equal to
<>, != is not equal to
< less than
> greater than
greater than or equal
>=
to
<= less than or equal to
Logical Operators:
There are three Logical Operators namely AND, OR and NOT.
Comparision
Description
Operators
column value is similar to specified
LIKE
character(s).
column value is equal to any one of
IN
a specified set of values.
column value is between two
BETWEEN...AND values, including the end values
specified in the range.
IS NULL column value does not exist.
For example: To select all the students whose name begins with 'S'
first_name last_name
------------- -------------
Stephen Fleming
Shekar Gowda
The above select statement searches for all the rows where the first letter of the column
first_name is 'S' and rest of the letters in the name can be any character.
There is another wildcard character you can use with LIKE operator. It is the underscore
character, ' _ ' . In a search string, the underscore signifies a single character.
For example: to display all the names with 'a' second character,
first_name last_name
------------- -------------
Rahul Sharma
NOTE:Each underscore act as a placeholder for only one character. So you can use more
than one underscore. Eg: ' __i% '-this has two underscores towards the left, 'S__j%' - this
has two underscores between character 'S' and 'i'.
For Example: to find the names of the students between age 10 to 15 years, the query
would be like,
SQL IN Operator:
The IN operator is used when you want to compare a column with more than one value. It
is similar to an OR condition.
For example: If you want to find the names of students who are studying either Maths or
Science, the query would be like,
SELECT first_name, last_name, subject
FROM student_details
WHERE subject IN ('Maths', 'Science');
For Example: If you want to find the names of students who do not participate in any
games, the query would be as given below
There would be no output as we have every student participate in a game in the table
student_details, else the names of the students who do not participate in any games would
be displayed
SQL ORDER BY
The ORDER BY clause is used in a SELECT statement to sort results either in ascending
or descending order. Oracle sorts query results in ascending order by default.
For Example: If you want to sort the employee table by salary of the employee, the sql
query would be.
name salary
---------- ----------
Soumya 20000
Ramesh 25000
Priya 30000
Hrithik 35000
Harsha 35000
The query first sorts the result according to name and then displays it.
You can also use more than one column in the ORDER BY clause.
If you want to sort the employee table by the name and salary, the query would be like,
name salary
------------- -------------
Soumya 20000
Ramesh 25000
Priya 30000
Harsha 35000
Hrithik 35000
By default, the ORDER BY Clause sorts data in ascending order. If you want to sort the
data in descending order, you must explicitly specify it as shown below.
The above query sorts only the column 'salary' in descending order and the column 'name'
by ascending order.
If you want to select both name and salary in descending order, the query would be as
given below.
For example: If you want to display employee name, current salary, and a 20% increase
in the salary for only those employees for whom the percentage increase in salary is
greater than 30000 and in descending order of the increased price, the SELECT statement
can be written as shown below
SQL COUNT (): This function returns the number of rows in the table that satisfies the
condition specified in the WHERE condition. If the WHERE condition is not specified,
then the query returns the total number of rows in the table.
For Example: If you want the number of employees in a particular department, the query
would be:
If you want the total number of employees in all the department, the query would take the
form:
For Example: If you want to select all distinct department names from employee table,
the query would be:
To get the count of employees with unique name, the query would be:
SQL MAX(): This function is used to get the maximum value from a column.
To get the maximum salary drawn by an employee, the query would be:
SQL AVG(): This function is used to get the average value of a numeric column.
SQL SUM(): This function is used to get the sum of a numeric column
For Example: If you want to know the total amount of salary spent on each department,
the query would be:
dept salary
-------------
----------------
-
Electrical 25000
Electronics 55000
Aeronautics 35000
InfoTech 30000
NOTE: The group by clause should contain all the columns in the select list expect those
used along with the group functions.
For Example: If you want to select the department that has total salary paid for its
employees more than 25000, the sql query would be like;
dept salary
------------- -------------
Electronics 55000
Aeronautics 35000
InfoTech 30000
When WHERE, GROUP BY and HAVING clauses are used together in a SELECT
statement, the WHERE clause is processed first, then the rows that are returned after the
WHERE clause is executed are grouped based on the GROUP BY clause. Finally, any
conditions on the group functions in the HAVING clause are applied to the grouped rows
before the final output is displayed.
SQL INSERT Statement
The INSERT Statement is used to add new rows of data to a table.
• col1, col2,...colN -- the names of the columns in the table into which you want to
insert data.
While inserting a row, if you are adding value for all the columns of the table you need
not specify the column(s) name in the sql query. But you need to make sure the order of
the values is in the same order as the columns in the table. The sql insert query will be as
follows
For Example: If you want to insert a row to the employee table, the query would be like,
INSERT INTO employee (id, name, dept, age, salary location) VALUES
(105, 'Srinath', 'Aeronautics', 27, 33000);
NOTE:When adding a row, only the characters or date values should be enclosed with
single quotes.
If you are inserting data to all the columns, the column names can be omitted. The above
insert statement can also be written as,
INSERT INTO employee (id, name, dept, age, salary location) SELECT
emp_id, emp_name, dept, age, salary, location
FROM temp_employee;
If you are inserting data to all the columns, the above insert statement can also be written
as,
NOTE:We have assumed the temp_employee table has columns emp_id, emp_name,
dept, age, salary, location in the above given order and the same datatype.
IMPORTANT NOTE:
1) When adding a new row, you should ensure the datatype of the value and the column
matches
2) You follow the integrity constraints, if any, defined for the table.
NOTE:In the Update statement, WHERE clause identifies the rows that get affected. If
you do not include the WHERE clause, column values for all the rows get affected.
For Example: To update the location of an employee, the sql update query would be
like,
UPDATE employee
SET location ='Mysore'
WHERE id = 101;
To change the salaries of all the employees, the query would be,
UPDATE employee
SET salary = salary + (salary * 0.2);
NOTE:The WHERE clause in the sql delete command is optional and it identifies the
rows in the column that gets deleted. If you do not include the WHERE clause all the
rows in the table is deleted, so be careful while writing a DELETE query without
WHERE clause.
For Example: To delete an employee with id 100 from the employee table, the sql delete
query would be like,
To delete all the rows from the employee table, the query would be like,
For Example: To delete all the rows from employee table, the query would be like,
DELETE Statement: This command deletes only the rows from the table based on the
condition given in the where clause or deletes all the rows from the table if no condition
is specified. But it does not free the space containing the table.
TRUNCATE statement: This command is used to delete all the rows from the table and
free the space containing the table.
For Example: To drop the table employee, the query would be like
If a table is dropped, all the relationships with other tables will no longer be valid, the
integrity constraints will be dropped, grant or access privileges on the table will also be
dropped, if want use the table again it has to be recreated with the integrity constraints,
access privileges and the relationships with other tables should be established again. But,
if a table is truncated, the table structure remains the same, therefore any of the above
problems will not exist.
In the above statement, temp_employee table is created with the same number of columns
and datatype as employee table.
For Example: To add a column "experience" to the employee table, the query would be
like
For Example: To drop the column "location" from the employee table, the query would
be like
ALTER TABLE employee DROP location;
For Example: To modify the column salary in the employee table, the query would be
like
If you change the object's name any reference to the old name will be affected. You have
to manually change the old name to the new name in every reference.
For Example: To change the name of the table employee to my_employee, the query
would be like
The constraints available in SQL are Foreign Key, Not Null, Unique, Check.
• column_name1, column_name2 are the names of the columns which define the
primary Key.
• The syntax within the bracket i.e. [CONSTRAINT constraint_name] is optional.
For Example: To create an employee table with Primary Key constraint, the query
would be like.
or
For Example:
2) If the employee table has a 'mgr_id' i.e, manager id as a foreign key which references
primary key 'id' within the same table, the query would be like,
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
mgr_id number(5) REFERENCES employee(id),
salary number(10),
location char(10)
);
For Example: To create a employee table with Null value, the query would be like
For Example: To create an employee table with Unique key, the query would be like,
or
For Example: In the employee table to select the gender of a person, the query would be
like
SQL Joins
SQL Joins are used to relate information in different tables. A Join condition is a part of
the sql query that retrieves rows from two or more tables. A SQL Join condition is used
in the SQL WHERE Clause of select, update, delete statements.
If a sql join condition is omitted or if it is invalid the join operation will result in a
Cartesian product. The Cartesian product returns a number of rows equal to the product
of all rows in all the tables being joined. For example, if the first table has 20 rows and
the second table has 10 rows, the result will be 20 * 10, or 200 rows. This query takes a
long time to execute.
Lets use the below two tables to explain the sql join conditions.
SQL Joins can be classified into Equi join and Non Equi join.
It is a simple sql join condition which uses the equal sign as the comparison operator.
Two types of equi joins are SQL Outer join and SQL Inner join.
For example: You can get the information about a customer who purchased a product
and the quantity of product.
It is a sql join condition which makes use of some comparison operator other than the
equal sign like >, <, >=, <=
For example: If you want to display the product information for each order the query
will be as given below. Since you are retrieving the data from two tables, you need to
identify the common column between these two tables, which is theproduct_id.
The columns must be referenced by the table name in the join condition, because
product_id is a column in both the tables and needs a way to be identified. This avoids
ambiguity in using the columns in the SQL SELECT statement.
The number of join conditions is (n-1), if there are more than two tables joined in a query
where 'n' is the number of tables involved. The rule must be true to avoid Cartesian
product.
We can also use aliases to reference the column name, then the above query would be
like,
The syntax differs for different RDBMS implementation. Few of them represent the join
conditions as "sql left outer join", "sql right outer join".
If you want to display all the product data along with order items data, with null values
displayed for order items if a product has no order item, the sql query for outer join
would be as shown below:
NOTE:If the (+) operator is used in the left side of the join condition it is equivalent to
left outer join. If used on the right side of the join condition it is equivalent to right outer
join.
For example: If you want to find the names of students who are not studying either
Economics, the sql query would be like, (lets use student_details table defined earlier.)
SQL Views
A VIEW is a virtual table, through which a selective portion of the data from one or more
tables can be seen. Views do not contain data of their own. They are used to restrict
access to the database or to hide data complexity. A view is stored as a SELECT
statement in the database. DML operations on a view like INSERT, UPDATE, DELETE
affects the data in the original table upon which the view is based.
For Example: to create a view on the product table the sql query would be like
SQL Subquery
Subquery or Inner query or Nested query is a query in a query. A subquery is usually
added in the WHERE Clause of the sql statement. Most of the time, a subquery is used
when you know how to search for a value using a SELECT statement, but do not know
the exact value.
Subqueries can be used with the following sql statements along with the comparision
operators like =, <, >, >=, <= etc.
• SELECT
• INSERT
• UPDATE
• DELETE
For Example:
1) Usually, a subquery should return only one record, but sometimes it can also return
multiple records when used with operators like IN, NOT IN in the where clause. The
query would be like,
2) Lets consider the student_details table which we have used earlier. If you know the
name of the students who are studying science subject, you can get their id's by using this
query below,
but, if you do not know their names, then to get their id's you need to write the query in
this manner,
Output:
id first_name
-------- -------------
100 Rahul
102 Stephen
In the above sql statement, first the inner query is processed first and then the outer query
is processed.
3) Subquery can be used with INSERT statement to add rows of data from one or more
tables to another table. Lets try to group all the students who study Maths in a table
'maths_group'.
4) A subquery can be used in the SELECT statement as follows. Lets use the product and
order_items table defined in the sql_joins section.
Correlated Subquery
A query is called correlated subquery when both the inner query and the outer query are
interdependent. For every row processed by the inner query, the outer query is processed
as well. The inner query depends on the outer query before it can be processed.
NOTE:
1) You can nest as many queries you want but it is recommended not to nest more than
16 subqueries in oracle.
2) If a subquery is not dependent on the outer query it is called a non-correlated
subquery.
SQL Index
Index in sql is created on existing tables to retrieve the rows quickly.
When there are thousands of records in a table, retrieving information will take a long
time. Therefore indexes are created on columns which are accessed frequently, so that the
information can be retrieved quickly. Indexes can be created on a single column or a
group of columns. When a index is created, it first sorts the data and then it assigns a
ROWID for each row.
In Oracle there are two types of SQL index namely, implicit and explicit.
Implicit Indexes:
They are created when a column is explicity defined with PRIMARY KEY, UNIQUE
KEY Constraint.
Explicit Indexes:
They are created using the "create index.. " syntax.
NOTE:
1) Even though sql indexes are created to access the rows in the table quickly, they slow
down DML operations like INSERT, UPDATE, DELETE on the table, because the
indexes and tables both are updated along when a DML operation is performed. So use
indexes only on columns which are used to search the table frequently.
2) Is is not required to create indexes on table which have less data.
3) In oracle database you can define up to sixteen (16) columns in an INDEX.
1) The sql query becomes faster if you use the actual columns names in SELECT
statement instead of than '*'.
Instead of:
2) HAVING clause is used to filter the rows after all the rows are selected. It is just like a
filter. Do not use HAVING clause for any other purposes.
For Example: Write the query as
SELECT subject, count(subject)
FROM student_details
WHERE subject != 'Science'
AND subject != 'Maths'
GROUP BY subject;
Instead of:
3) Sometimes you may have more than one subqueries in your main query. Try to
minimize the number of subquery block in your query.
For Example: Write the query as
SELECT name
FROM employee
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age)
FROM employee_details)
AND dept = 'Electronics';
Instead of:
SELECT name
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee_details)
AND age = (SELECT MAX(age) FROM employee_details)
AND emp_dept = 'Electronics';
Instead of:
Instead of:
Instead of:
SELECT id, first_name, age FROM student_details WHERE age > 10;
Instead of:
Instead of:
Instead of:
Instead of:
Instead of:
Use non-column expression on one side of the query because it will be processed earlier.
Instead of:
Instead of:
8) Use DECODE to avoid the scanning of same rows or joining the same table
repetitively. DECODE can also be made used in place of GROUP BY or ORDER BY
clause.
For Example: Write the query as
Instead of:
9) To store large binary objects, first place them in the file system and add the file path in
the database.
10) To write queries which provide efficient performance follow the general SQL
standard rules.
JOIN
JOIN works in the same way as the SELECT statement above—it returns a result set with
columns from different tables. The advantage of using an explicit JOIN over an implied
one is greater control over your result set, and possibly improved performance when
many tables are involved.
There are several types of JOIN—LEFT, RIGHT, and FULL OUTER; INNER; and
CROSS. The type you use is determined by the results you want to see. For example,
using a LEFT OUTER JOIN will return all relevant rows from the first table listed, while
potentially dropping rows from the second table listed if they don’t have information that
correlates in the first table.
This differs from an INNER JOIN or an implied JOIN. An INNER JOIN will only return
rows for which there is data in both tables.
Use the following JOIN statement for the first SELECT query above:
SELECT table1.column1, table2.column2 FROM table1 INNER JOIN table2
ON table1.column1 = table2.column1;
Subqueries
Subqueries, or subselect statements, are a way to use a result set as a resource in a query.
These are often used to limit or refine results rather than run multiple queries or
manipulate the data in your application. With a subquery, you can reference tables to
determine inclusion of data or, in some cases, return a column that is the result of a
subselect.
The following example uses two tables. One table actually contains the data I’m
interested in returning, while the other gives a comparison point to determine what data is
actually interesting.
SELECT column1 FROM table1 WHERE EXISTS ( SELECT column1 FROM table2
WHERE table1.column1 = table2.column1 );
One important factor about subqueries is performance. Convenience comes at a price and,
depending on the size, number, and complexity of tables and the statements you use, you
may want to allow your application to handle processing. Each query is processed
separately in full before being used as a resource for your primary query. If possible,
creative use of JOIN statements may provide the same information with less lag time.
JOIN statements and subqueries
For a more detailed explanation of JOINS and concepts that can be used with them, read
the articles "Basic and complex SQL joins made easy" and "Master joins with these
concepts." For more information about subqueries, read "Use SQL subselects to
consolidate queries."
UNION
The UNION statement is another way to return information from multiple tables with a
single query. The UNION statement allows you to perform queries against several tables
and return the results in a consolidated set, as in the following example.
SELECT column1, column2, column3 FROM table1 UNION SELECT column1,
column2, column3 FROM table2;
This will return a result set with three columns containing data from both queries. By
default, the UNION statement will omit duplicates between the tables unless the UNION
ALL keyword is used. UNION is helpful when the returned columns from the different
tables don’t have columns or data that can be compared and joined, or when it prevents
running multiple queries and appending the results in your application code.
If your column names don’t match when you use the UNION statement, use aliases to
give your results meaningful headers:
SELECT column1, column2 as Two, column3 as Three FROM table1 UNION SELECT
column1, column4 as Two, column5 as Three FROM table2;
As with subqueries, UNION statements can create a heavy load on your database server,
but for occasional use they can save a lot of time.
Multiple options
When it comes to database queries, there are usually many ways to approach the same
problem. These are some of the more frequently used methods for consolidating queries
on multiple tables into a single statement. While some of these options may affect
performance, practice will help you know when it’s appropriate to use each type of query.
Data query types
There are four basic types of data queries in SQL:
• SELECT: This statement asks the database to return a specified result set of data;
you use this to retrieve information that is stored in your database.
• INSERT: You use this type of statement to add a new row of data into a table.
• UPDATE: This changes existing data in your database.
• DELETE: This removes rows of data from your database.
Each of these statements has various qualifiers and functions that you can use to define
the data set you would like to affect and that control the way the result set is returned.
The SELECT statement has the most options. There are a variety of alternate query types
used in conjunction with SELECT, such as JOIN and UNION. For now, we’ll just focus
on basic usage.
Alternatively, you can get all the columns from a table by using the wildcard, “*”:
SELECT * FROM table_name;
While this is useful if you’re planning on parsing the result set in your code, you can
further limit it with the handy WHERE clause, which allows you to define a certain
condition for selecting data. The following query will return all columns from all rows
where “column1” contains the value "3."
SELECT * FROM table_name WHERE column1 = 3;
Besides the “=” (equal to) condition, you may use any of the following:
Table A
= Equal
<> Not Equal
> Greater Than
< Less Than
>= Greater Than Or Equal To
<= Less Than Or Equal To
SQL Conditional Statements
Additionally, you can use the statements BETWEEN and LIKE for comparison with the
WHERE clause, and any combination of comparisons with the operators AND and OR.
Note that the OR statement is inclusive. Here’s an example combining all of these
concepts:
SELECT * FROM table_name WHERE ((Age < 18) AND (LastName BETWEEN
‘Anderson’ AND ‘Miller’)) OR Company LIKE ‘%School%’;
In English, this statement reads “Select all columns from table_name where either the
Age column has a value less than 18 and the LastName column has a value alphabetically
between and including ‘Anderson’ and ‘Miller’ or the Company column value contains
the word ‘School’.”
If you’re going to insert all the values in the same order that the columns of the table
exist, you don’t have to specify column names, although for readability this is generally
preferred. In addition, if you list the columns, it is not necessary to include them in the
order they appear in the database, as long as the values you list correlate. You do not
have to list all of the columns if you aren’t entering information for them.
You are free to match WHERE to any column, including one that you are changing. This
is helpful when you’re looking to change one specific value to another:
UPDATE table_name SET FirstName = ‘Shelley’
WHERE FirstName = ‘Shelly’ AND LastName = ‘Doll’;
Once a row has been removed from your database, it is gone, so generally speaking it
may be desirable to include a column called “IsActive,” or something similar, that you
can change to a zero to represent disabled data. You should only use DELETE when you
are absolutely sure you will no longer need the affected information.
Selecting Data
The select statement is used to query the database and retrieve selected data that match
the criteria that you specify. Here is the format of a simple select statement:
select "column1"
[,"column2",etc]
from "tablename"
[where "condition"];
[] = optional
The column names that follow the select keyword determine which columns will be
returned in the results. You can select as many column names that you'd like, or you can
use a "*" to select all columns.
The table name that follows the keyword from specifies the table that will be queried to
retrieve the desired results.
The where clause (optional) specifies which data values or rows will be returned or
displayed, based on the criteria described after the keyword where.
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal to
LIKE *See note below
The LIKE pattern matching operator can also be used in the conditional selection of the
where clause. Like is a very powerful operator that allows you to select only rows that are
"like" what you specify. The percent sign "%" can be used as a wild card to match any
possible character that might appear before or after the characters specified. For example:
This SQL statement will match any first names that start with 'Er'. Strings must be in
single quotes.
This statement will match any last names that end in a 's'.
This will only select rows where the first name equals 'Eric' exactly.
Sample Table: empinfo
first last id age city state
John Jones 99980 45 Payson Arizona
Mary Jones 99982 25 Payson Arizona
Eric Edwards 88232 32 San Diego California
Mary Ann Edwards 88233 32 Phoenix Arizona
Ginger Howell 98002 42 Cottonwood Arizona
Sebastian Smith 92001 23 Gila Bend Arizona
Gus Gray 22322 35 Bagdad Arizona
Mary Ann May 32326 52 Tucson Arizona
Erica Williams 32327 60 Show Low Arizona
Leroy Brown 32380 22 Pinetop Arizona
Elroy Cleaver 32382 22 Globe Arizona
Enter the following sample select statements in the SQL Interpreter Form at the bottom of
this page. Before you press "submit", write down your expected results. Press "submit",
and compare the results.
1. Display the first name and age for everyone that's in the table.
2. Display the first name, last name, and city for everyone that's not from Payson.
3. Display all columns for everyone that is over 40 years old.
4. Display the first and last names for everyone whose last name ends in an "ay".
5. Display all columns for everyone whose first name equals "Mary".
6. Display all columns for everyone whose first name contains "Mary".
Creating Tables
The create table statement is used to create a new table. Here is the format of a simple
create table statement:
Note: You may have as many columns as you'd like, and the constraints are optional.
Example:
To insert records into a table, enter the key words insert into followed by the table name,
followed by an open parenthesis, followed by a list of column names separated by
commas, followed by a closing parenthesis, followed by the keyword values, followed by
the list of values enclosed in parenthesis. The values that you enter will be held in the
rows and they will match up with the column names that you specify. Strings should be
enclosed in single quotes, and numbers should not.
insert into "tablename"
(first_column,...last_column)
values (first_value,...last_value);
In the example below, the column name first will match up with the value 'Luke', and
the column name state will match up with the value 'Georgia'.
Example:
Enter these employees into your table first, and then insert at least 5 more of your own
list of employees in the table.
After they're inserted into the table, enter select statements to:
Create at least 5 of your own select statements based on specific information that you'd
like to retrieve.
Updating Records
The update statement is used to update or change records that match a specified criteria.
This is accomplished by carefully constructing a where clause.
update "tablename"
set "columnname" =
"newvalue"
[,"nextcolumn" =
"newvalue2"...]
where "columnname"
OPERATOR "value"
[and|or "column"
OPERATOR "value"];
[] = optional
[The above example was line wrapped for better viewing on this Web page.]
Examples:
update phone_book
set area_code = 623
where prefix = 979;
update phone_book
set last_name = 'Smith', prefix=555, suffix=9292
where last_name = 'Jones';
update employee
set age = age+1
where first_name='Mary' and last_name='Williams';
1. Jonie Weber just got married to Bob Williams. She has requested that her last
name be updated to Weber-Williams.
2. Dirk Smith's birthday is today, add 1 to his age.
3. All secretaries are now called "Administrative Assistant". Update all titles
accordingly.
4. Everyone that's making under 30000 are to receive a 3500 a year raise.
5. Everyone that's making over 33500 are to receive a 4500 a year raise.
6. All "Programmer II" titles are now promoted to "Programmer III".
7. All "Programmer" titles are now promoted to "Programmer II".
Deleting Records
The delete statement is used to delete records or rows from the table.
delete from "tablename"
where "columnname"
OPERATOR "value"
[and|or "column"
OPERATOR "value"];
[ ] = optional
[The above example was line wrapped for better viewing on this Web page.]
Examples:
Note: if you leave off the where clause, all records will be deleted!
To delete an entire record/row from a table, enter "delete from" followed by the table
name, followed by the where clause which contains the conditions to delete. If you leave
off the where clause, all records will be deleted.
1. Jonie Weber-Williams just quit, remove her record from the table.
2. It's time for budget cuts. Remove all employees who are making over 70000
dollars.
Create at least two of your own delete statements, and then issue a command to delete all
records from the table.
Drop a Table
The drop table command is used to delete a table and all rows in the table.
To delete an entire table including all of its rows, issue the drop table command
followed by the tablename. drop table is different from deleting all of the records in the
table. Deleting all of the records in the table leaves the table including column and
constraint information. Dropping the table removes the table definition as well as all of
its rows.
drop table "tablename"
Example:
What is sql
SQL is a standard computer language for accessing and manipulating database systems.
SQL statements are used to retrieve and update data in a database. SQL works with
database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, and
other database systems.
What is ado
ADO is a programming interface to access data in a database from a web site.
ADO uses SQL to query data in a database.
Can you be precise about sql and What can u do with sql
· SQL stands for Structured Query Language
· SQL allows you to access a database
· SQL is an ANSI standard computer language
· SQL can execute queries against a database
· SQL can retrieve data from a database
· SQL can insert new records in a database
· SQL can delete records from a database
· SQL can update records in a database
Do u know any commands in sql if so tell about them
· SELECT - extracts data from a database table
· UPDATE - updates data in a database table
· DELETE - deletes data from a database table
· INSERT INTO - inserts new data into a database table
Tell some thing about ddl
The Data Definition Language (DDL) part of SQL permits database tables to be created
or deleted. We can also define indexes (keys), specify links between tables, and impose
constraints between database tables.
Tell syntaxes for column name aliases and table name aliases
SELECT column AS column_alias FROM table
Re: Explain basic SQL queries with SELECT from where Order By, Group By-
Having? Answer
#1
Order by clause is used to sort information of a table into
specific order either ascending or descending order.
SELECT country,city
FROM customers
GROUP BY country
ORDER BY city DESC
What is a subselect? Is it different from a nested select?
inner select passes to the where criteria for the outer select.
Group by controls the presentation of the rows, order by controls the presentation of
the columns for the results of the
SELECT statement.
What keyword does an SQL SELECT statement use for a string search?
The LIKE keyword allows for string searches. The % sign is used as a wildcard.
The common aggregate, built-in functions are AVG, SUM, MIN, MAX, COUNT and
DISTINCT.
SUBSTR (NAME, 1 3) refers to the first three characters in the column NAME.
The explain statement provides information about the optimizer's choice of access
path of the SQL.
What is a NULL value? What are the pros and cons of using NULLS?
A NULL value takes up one byte of storage and indicates that a value is not present
as opposed to a space or zero
value. It's the DB2 equivalent of TBD on an organizational chart and often
correctly portrays a business situation.
A synonym is used to reference a table or view by another name. The other name
can then be written in the
Never. New primary key values are not a problem. However, the values of foreign
key inserts must have
the program must dynamically allocate memory to receive the query results.
Any subselect can be rewritten as a join, but not vice versa. Joins are usually more
efficient as join rows can be
select.
What is the difference between IN subselects and EXISTS subselect?
If there is an index on the attributes tested an IN is more efficient since DB2 uses
the index for the IN. (IN for index is
the mnemonic).
A Cartesian product results from a faulty query. It is a row in the results for every
combination in the join tables.
What is a tuple?
Static SQL is compiled and optimized prior to its execution; dynamic is compiled and
optimized during execution.
A). NUMERIC
B). CHARACTER
A,B,C. Not all SQL implementations have a BLOB or a BIT data types.
We have a table with a CHARACTER data type field. We apply a ">" row
comparison between this field and
another CHARACTER field in another table. What will be the results for
records with field value of NULL?
B. FALSE
C. UNKNOWN
D. Error.
usually in three steps which results in first, second and third normal
forms. Which best describes the process to
obtain the third normal form? (Check one that applies the best)
We have a table with multi-valued key. All columns that are dependent on only
one or on some of the keys should be moved in a different table.
If a table has columns not dependent on the primary keys, they need to be
moved in a separate table.
D. All columns in a table should be dependent on the primary key. This will eliminate
transitive dependencies in
which A depends on B, and B depends on C, but we're not sure how C depends
on A.
and the last three defines the subclass of the error. Which of the
following SQLSTATE codes is interpreted as
A). 00xxx
B). 01xxx
C). 02xxx
D). 22xxx
E). 2Axxx
Dynamic SQL are SQL statements that are prepared and executed within a program
while the program is executing.
The SQL source is contained in host variables rather than being hard coded into
the program. The SQL statement may
They are SQL statements that are embedded with in application program and are
prepared during the program