You are on page 1of 97

Files

ls --- lists your files

o

o

o

o

ls -l --- lists your files in 'long format', which contains lots of useful information, e.g. the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified. ls -a --- lists all files, including the ones whose filenames begin in a dot, which you do not always want to see. There are many more options, for example to list files by size, by date, recursively etc. more filename --- shows the first part of a file, just as much as will fit on one

screen. Just hit the space bar to see more or q to quit. You can use /pattern to search for a pattern. emacs filename --- is an editor that lets you create and edit a file. See the emacs

page. mv filename1 filename2 --- moves a file (i.e. gives it a different name, or moves

it into a different directory (see below) cp filename1 filename2 --- copies a file

rm filename --- removes a file. It is wise to use the option rm -i, which will ask

you for confirmation before actually deleting anything. You can make this your default by making an alias in your .cshrc file. diff filename1 filename2 --- compares files, and shows where they differ

wc filename --- tells you how many lines, words, and characters there are in a file

chmod options filename --- lets you change the read, write, and execute

permissions on your files. The default is that only you can look at them and change them, but you may sometimes want to change these permissions. For example, chmod o+r filename will make the file readable for everyone, and chmod o-r filename will make it unreadable for others again. Note that for someone to be able to actually look at the file the directories it is in need to be at least executable. See help protection for more details. File Compression

gzip filename --- compresses files, so that they take up much less space.

Usually text files compress to about half their original size, but it depends very much on the size of the file and the nature of the contents. There are other tools for this purpose, too (e.g. compress), but gzip usually gives the highest compression rate. Gzip produces files with the ending '.gz' appended to the original filename. gunzip filename --- uncompresses files compressed by gzip.

gzcat filename --- lets you look at a gzipped file without actually having

to gunzip it (same as gunzip -c). You can even print it directly, using gzcat filename | lpr printing

lpr filename --- print. Use the -P option to specify the printer name if you want to use a printer other than your default printer. For example, if you want to print double-sided, use 'lpr -Pvalkyr-d', or if you're at CSLI, you

o

may want to use 'lpr -Pcord115-d'. See 'help printers' for more information about printers and their locations. lpq --- check out the printer queue, e.g. to get the number needed for

o

removal, or to see how many other files will be printed before yours will come out lprm jobnumber --- remove something from the printer queue. You can

o

find the job number by using lpq. Theoretically you also have to specify a printer name, but this isn't necessary as long as you use your default printer in the department. genscript --- converts plain text files into postscript for printing, and gives

o

you some options for formatting. Consider making an alias like alias ecop 'genscript -2 -r \!* | lpr -h -Pvalkyr' to print two pages on one piece of paper. dvips filename --- print .dvi files (i.e. files produced by LaTeX). You can use dviselect to print only selected pages. See the LaTeX page for more information about how to save paper when printing drafts.

Directories

Directories, like folders on a Macintosh, are used to group files together in a hierarchical structure.

mkdir dirname --- make a new directory

cd dirname --- change directory. You basically 'go' to another directory, and you will see the files in that directory when you do 'ls'. You always start out in your 'home directory', and you can get back there by typing 'cd' without arguments.

'cd

'

will get you one level up from your current position. You don't have to walk

specifying pathnames. pwd --- tells you where you currently are.

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.

About other people

w --- tells you who's logged in, and what they're doing. Especially useful: the 'idle'

part. This allows you to see whether they're actually sitting there typing away at their keyboards right at the moment. who --- tells you who's logged on, and where they're coming from. Useful if

you're looking for someone who's actually physically in the same building as you, or in some other particular location. finger username --- gives you lots of information about that user, e.g. when they

last read their mail and whether they're logged in. Often people put other practical information, such as phone numbers and addresses, in a file called .plan. This information is also displayed by 'finger'. last -1 username --- tells you when the user last logged on and off and from

where. Without any options, last will give you a list of everyone's logins. talk username --- lets you have a (typed) conversation with another user

write username --- lets you exchange one-line messages with another user

elm --- lets you send e-mail messages to people around the world (and, of course, read them). It's not the only mailer you can use, but the one we recommend. See the elm page, and find out about the departmental mailing lists (which you can also find in /user/linguistics/helpfile).

About your (electronic) self

whoami --- returns your username. Sounds useless, but isn't. You may need to

find out who it is who forgot to log out somewhere, and make sure *you* have logged out. finger & .plan files

of course you can finger yourself, too. That can be useful e.g. as a quick check whether you got new mail. Try to create a useful .plan file soon. Look at other people's .plan files for ideas. The file needs to be readable for everyone in order to be visible through 'finger'. Do 'chmod a+r .plan' if necessary. You should realize that this information is accessible from anywhere in the world, not just to other people on turing. passwd --- lets you change your password, which you should do regularly (at

least once a year). See the LRB guide and/or look at help password. ps -u yourusername --- lists your processes. Contains lots of information about

them, including the process ID, which you need if you have to kill a process. Normally, when you have been kicked out of a dialin session or have otherwise managed to get yourself disconnected abruptly, this list will contain the processes you need to kill. Those may include the shell (tcsh or whatever you're using), and anything you were running, for example emacs or elm. Be careful not to kill your current shell - the one with the number closer to the one of the ps command you're currently running. But if it happens, don't panic. Just try again :) If you're using an X-display you may have to kill some X processes before you can start them again. These will show only when you use ps -efl, because they're root processes. kill PID --- kills (ends) the processes with the ID you gave. This works only for your own processes, of course. Get the ID by using ps. If the process doesn't 'die' properly, use the option -9. But attempt without that option first, because it

doesn't give the process a chance to finish possibly important business before dying. You may need to kill processes for example if your modem connection was interrupted and you didn't get logged out properly, which sometimes happens. quota -v --- show what your disk quota is (i.e. how much space you have to store

files), how much you're actually using, and in case you've exceeded your quota (which you'll be given an automatic warning about by the system) how much time you have left to sort them out (by deleting or gzipping some, or moving them to your own computer). du filename --- shows the disk usage of the files and directories in filename

(without argument the current directory is used). du -s gives only a total. last yourusername --- lists your last logins. Can be a useful memory aid for when you were where, how long you've been working for, and keeping track of your phonebill if you're making a non-local phonecall for dialling in.

Connecting to the outside world

nn --- allows you to read news. It will first let you read the news local to turing,

and then the remote news. If you want to read only the local or remote news, you can use nnl or nnr, respectively. To learn more about nn type nn, then \tty{:man}, then \tty{=.*}, then \tty{Z}, then hit the space bar to step through the manual. Or look at the man page. Or check out the hypertext nn FAQ - probably the easiest and most fun way to go. rlogin hostname --- lets you connect to a remote host

telnet hostname --- also lets you connect to a remote host. Use rlogin whenever

possible. ftp hostname --- lets you download files from a remote host which is set up as an

ftp-server. This is a common method for exchanging academic papers and drafts. If you need to make a paper of yours available in this way, you can (temporarily) put a copy in /user/ftp/pub/TMP. For more permanent solutions, ask Emma. The most important commands within ftp are get for getting files from the remote machine, and put for putting them there (mget and mput let you specify more than one file at once). Sounds straightforward, but be sure not to confuse the two, especially when your physical location doesn't correspond to the direction of the ftp connection you're making. ftp just overwrites files with the same filename. If you're transferring anything other than ASCII text, use binary mode. lynx --- lets you browse the web from an ordinary terminal. Of course you can see only the text, not the pictures. You can type any URL as an argument to the G command. When you're doing this from any Stanford host you can leave out the .stanford.edu part of the URL when connecting to Stanford URLs. Type H at any time to learn more about lynx, and Q to exit.

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

Communication

Information

Printing

Job control

Extract lines from a file using a keyword

COMMAND DESCRIPTION EXAMPLE EXPLANATION

grep string

file

Searches input file(s) for specified string and prints the line with matches.

grep mike

letter

Searches for the string mike in the file named letter and prints any line with mike in it to the screen.

grep -c string file

grep -i string file

Searches and prints only the number of matches to the screen.

grep -c hayes bankletter

Searches the file bankletter for the string hayes and prints the number of matches to the screen.

Searches without regard to letter case.

Searches file1 for hi, Hi, hI, grep -i hi file1 and HI and prints all matches to the screen.

grep -n string file

Prints to the screen preceded by the line number.

grep -n abc alpha

All lines that do not match grep -v lead

grep -v string file

are printed.

pencils

grep -x string file

Only exact matches are printed.

grep -x time meetings

cat --- for creating and displaying short files

chmod --- change permissions

cd --- change directory

cp --- for copying files

Searches alpha for abc and prints the matches’ lines and line numbers to the screen.

Prints all lines in pencils that do not contain the string lead.

Prints only lines in meetings that match time exactly.

date --- display date

echo --- echo argument

ftp --- connect to a remote machine to download or upload files

grep --- search file

head --- display first part of file

ls --- see what files you have

lpr --- standard print command (see also print )

more --- use to read files

mkdir --- create directory

mv --- for moving and renaming files

ncftp --- especially good for downloading files via anonymous ftp.

print --- custom print command (see also lpr )

pwd --- find out what directory you are in

rm --- remove a file

rmdir --- remove directory

rsh --- remote shell

setenv --- set an environment variable

sort --- sort file

tail --- display last part of file

tar --- create an archive, add or extract files

telnet --- log in to another machine

wc --- count characters, words, lines

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 a+r essay.001

To make a file, e.g., a shell script mycommand executable, 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

/poems.

Finally he used cd with

.. back one level, then go to poems he could have said cd ..

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".

% grep Fred ph | sort Alpha, Fred: 333-6565 Beta, Freddie: 656-0099 Frederickson, Molly: 444-0981 Gamma, Fred-George: 111-7676 Zeta, Frederick: 431-0987

The symbol "|" is called "pipe." It pipes the output of the grep command into the input of the sort command.

For more information on grep, consult

% man grep

head

Use this command to look at the head of a file. For example,

% 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:

q --- quit more

spacebar --- read next page

return key --- read next line

b --- go back one page

For still more information, use the command man more.

mv

Use this command to change the name of file and directories.

% mv foo foobar

The file that was named foo is now named 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

The file jokes.txt is downloaded from the machine ftp.fubar.net.

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.

See also: telnet

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

Use this command to look at the tail of a file. For example,

% 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:

% tar -tvzf foo.tar.gz

displays the file names in the compressed archive foo.tar.gz while

% tar -xvzf foo.tar.gz

extracts the files.

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

See also: rsh.

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

This shows that dict has 5 lines, 10 words, and 56 characters.

The word count command has several options, as illustrated below:

% wc -l dict 5 tmp % wc -w dict

 

10

tmp

% wc -c dict

 

56

tmp

dummy

Under construction

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  • 1. What are two methods of retrieving SQL?

  • 3. What is the difference between a "where" clause and a "having" clause? - "Where" is a kind of restiriction statement. You use where clause to restrict all the data from DB.Where clause is using before result retrieving. But Having clause is using after retrieving the data.Having clause is a kind of filtering command.

  • 4. What is the basic form of a SQL statement to read data out of a table? The basic form to read data out of table is ‘SELECT * FROM table_name; ‘ An answer: ‘SELECT * FROM table_name WHERE xyz= ‘whatever’;’ cannot be called basic form because of WHERE clause.

  • 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

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?

QL INNER JOIN Keyword

The INNER JOIN keyword return rows when there is at least one match in both tables.

SQL INNER JOIN Syntax

SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name

PS: INNER JOIN is the same as JOIN.

27. What is the diference between “NULL in C” and “NULL in Oracle?” 28. What is

SQL INNER JOIN Example

The "Persons" table:

P_Id
P_Id
LastName
LastName
FirstName
FirstName
Address
Address
City
City
3 2 1
3
2
1

Hansen

Ola

Timoteivn 10

Sandnes

Svendson

Tove

Borgvn 23

Sandnes

Pettersen

Kari

Storgt 20

Stavanger

The "Orders" table:

O_Id 1 2 3 4 5
O_Id
1
2
3
4
5
1 1 3 3 34764 24562 22456 44678 77895 15 OrderNo P_Id
1
1
3
3
34764
24562
22456
44678
77895
15
OrderNo
P_Id

Now we want to list all the persons with any orders.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

The result-set will look like this:

LastName

FirstName

OrderNo

Hansen

Ola

22456

Hansen

Ola

24562

Pettersen

Kari

77895

Pettersen

Kari

44678

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.

SQL LEFT JOIN Keyword

SQL LEFT JOIN Keyword

The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).

SQL LEFT JOIN Syntax

SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name

PS: In some databases LEFT JOIN is called LEFT OUTER JOIN.

SQL LEFT JOIN Syntax SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name PS: In some

SQL LEFT JOIN Example

The "Persons" table:

3 Pettersen 2 Svendson 1 Hansen LastName P_Id
3 Pettersen
2 Svendson
1 Hansen
LastName
P_Id
3 Pettersen 2 Svendson 1 Hansen LastName P_Id FirstName Address City Ola Timoteivn 10 Sandnes Tove
3 Pettersen 2 Svendson 1 Hansen LastName P_Id FirstName Address City Ola Timoteivn 10 Sandnes Tove
3 Pettersen 2 Svendson 1 Hansen LastName P_Id FirstName Address City Ola Timoteivn 10 Sandnes Tove
3 Pettersen 2 Svendson 1 Hansen LastName P_Id FirstName Address City Ola Timoteivn 10 Sandnes Tove

FirstName

Address

City

Ola

Timoteivn 10

Sandnes

Tove

Borgvn 23

Sandnes

Kari

Storgt 20

Stavanger

The "Orders" table:

OrderNo O_Id 1 77895 2 44678 3 22456 4 24562 5 34764
OrderNo
O_Id
1 77895
2 44678
3 22456
4 24562
5 34764
15 P_Id 3 3 1 1
15
P_Id
3
3
1
1

Now we want to list all the persons and their orders - if any, from the tables above.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons LEFT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

The result-set will look like this:

LastName

FirstName

OrderNo

Hansen

Ola

22456

Hansen

Ola

24562

Pettersen

Kari

77895

Pettersen

Kari

44678

Svendson

Tove

 

The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no matches in the right table (Orders).

SQL RIGHT JOIN Keyword

SQL RIGHT JOIN Keyword

The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches in the left table (table_name1).

SQL RIGHT JOIN Syntax

SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name

PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

Pettersen Kari 77895 Pettersen Kari 44678 Svendson Tove The LEFT JOIN keyword returns all the rows« Previous Next Chapter » SQL RIGHT JOIN Keyword The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches in the left table (table_name1). SQL RIGHT JOIN Syntax SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN. SQL RIGHT JOIN Example The "Persons" table: P_Id LastName FirstName 1 Ola Hansen 2 Tove Svendson 3 Kari Pettersen Address City Timoteivn 10 Sandnes Borgvn 23 Sandnes Storgt 20 Stavanger The "Orders" table: OrderNo O_Id 1 77895 2 44678 3 22456 4 24562 5 34764 15 P_Id 3 3 1 1 " id="pdf-obj-21-46" src="pdf-obj-21-46.jpg">

SQL RIGHT JOIN Example

The "Persons" table:

P_Id
P_Id

LastName

FirstName

  • 1 Ola

Hansen

  • 2 Tove

Svendson

  • 3 Kari

Pettersen

P_Id LastName FirstName 1 Ola Hansen 2 Tove Svendson 3 Kari Pettersen Address City Timoteivn 10
P_Id LastName FirstName 1 Ola Hansen 2 Tove Svendson 3 Kari Pettersen Address City Timoteivn 10
P_Id LastName FirstName 1 Ola Hansen 2 Tove Svendson 3 Kari Pettersen Address City Timoteivn 10
P_Id LastName FirstName 1 Ola Hansen 2 Tove Svendson 3 Kari Pettersen Address City Timoteivn 10

Address

City

Timoteivn 10

Sandnes

Borgvn 23

Sandnes

Storgt 20

Stavanger

The "Orders" table:

OrderNo O_Id 1 77895 2 44678 3 22456 4 24562 5 34764
OrderNo
O_Id
1 77895
2 44678
3 22456
4 24562
5 34764
15 P_Id 3 3 1 1
15
P_Id
3
3
1
1

Now we want to list all the orders with containing persons - if any, from the tables above.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons RIGHT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

The result-set will look like this:

LastName

FirstName

OrderNo

Hansen

Ola

22456

Hansen

Ola

24562

Pettersen

Kari

77895

Pettersen

Kari

44678

   

34764

The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no matches in the left table (Persons).

SQL FULL JOIN Keyword

The FULL JOIN keyword return rows when there is a match in one of the tables.

SQL FULL JOIN Syntax

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 orders with containing persons - if any, from the

SQL FULL JOIN Example

The "Persons" table:

P_Id
P_Id

LastName

FirstName

  • 1 Ola

Hansen

  • 2 Tove

Svendson

  • 3 Kari

Pettersen

P_Id LastName FirstName 1 Ola Hansen 2 Tove Svendson 3 Kari Pettersen Address City Timoteivn 10
P_Id LastName FirstName 1 Ola Hansen 2 Tove Svendson 3 Kari Pettersen Address City Timoteivn 10
P_Id LastName FirstName 1 Ola Hansen 2 Tove Svendson 3 Kari Pettersen Address City Timoteivn 10
P_Id LastName FirstName 1 Ola Hansen 2 Tove Svendson 3 Kari Pettersen Address City Timoteivn 10

Address

City

Timoteivn 10

Sandnes

Borgvn 23

Sandnes

Storgt 20

Stavanger

The "Orders" table:

O_Id 1 2 3 4 5
O_Id
1
2
3
4
5
1 1 3 3 34764 24562 22456 44678 77895 15 OrderNo P_Id
1
1
3
3
34764
24562
22456
44678
77895
15
OrderNo
P_Id

Now we want to list all the persons and their orders, and all the orders with their persons.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons FULL JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

The result-set will look like this:

LastName

FirstName

OrderNo

Hansen

Ola

22456

Hansen

Ola

24562

Pettersen

Kari

77895

Pettersen

Kari

44678

Svendson

Tove

 
   

34764

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.

SQL PRIMARY KEY Constraint

SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values.

A primary key column cannot contain NULL values.

Each table should have a primary key, and each table can have only one primary key.

A primary key column cannot contain NULL values. Each table should have a primary key, and

SQL PRIMARY KEY Constraint on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created:

MySQL:

CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (P_Id) )

SQL Server / Oracle / MS Access:

CREATE TABLE Persons ( P_Id int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

)

) SQL PRIMARY KEY Constraint on ALTER TABLE To create a PRIMARY KEY constraint on the« Previous Next Chapter » SQL FOREIGN KEY Constraint A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Let's illustrate the foreign key with an example. Look at the following two tables: The "Persons" table: P_Id 1 LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes " id="pdf-obj-25-4" src="pdf-obj-25-4.jpg">

SQL PRIMARY KEY Constraint on ALTER TABLE

To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons ADD PRIMARY KEY (P_Id)

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

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).

) SQL PRIMARY KEY Constraint on ALTER TABLE To create a PRIMARY KEY constraint on the« Previous Next Chapter » SQL FOREIGN KEY Constraint A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Let's illustrate the foreign key with an example. Look at the following two tables: The "Persons" table: P_Id 1 LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes " id="pdf-obj-25-23" src="pdf-obj-25-23.jpg">

To DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:

SQL FOREIGN KEY Constraint

SQL FOREIGN KEY Constraint

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

Let's illustrate the foreign key with an example. Look at the following two tables:

The "Persons" table:

P_Id 1
P_Id
1

LastName

FirstName

Address

City

Hansen

Ola

Timoteivn 10

Sandnes

2 3
2
3

Svendson

Tove

Borgvn 23

Sandnes

Pettersen

Kari

Storgt 20

Stavanger

The "Orders" table:

O_Id

OrderNo
OrderNo
P_Id
P_Id
 
  • 1 3

77895

 
  • 2 3

44678

  • 3 2

22456

  • 4 1

24562

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.

2 3 Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger The "Orders" table: O_Id

SQL FOREIGN KEY Constraint on CREATE TABLE

The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:

MySQL:

CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) )

SQL Server / Oracle / MS Access:

CREATE TABLE Orders

( O_Id int NOT NULL PRIMARY KEY, OrderNo int NOT NULL, P_Id int FOREIGN KEY REFERENCES Persons(P_Id) )

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) )

( O_Id int NOT NULL PRIMARY KEY, OrderNo int NOT NULL, P_Id int FOREIGN KEY REFERENCES

SQL FOREIGN KEY Constraint on ALTER TABLE

To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)

( O_Id int NOT NULL PRIMARY KEY, OrderNo int NOT NULL, P_Id int FOREIGN KEY REFERENCES

To DROP a FOREIGN KEY Constraint

To drop a FOREIGN KEY constraint, use the following SQL:

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

Types of joins ? Answer # 9

1.Cross Join - is a join without a join contition SELECT * FROM table-1 CROSS JOIN table-2

2.Inner Join - return only matched records i.Equi-Join ii.Non-Equi Join * Inner joins or equi joins are the most common type of joins, they use equality "=" of common attributes to join tables. SELECT projects.name AS "Project Name", teachers.name FROM teachers, projects WHERE teachers.id = projects.teacher;

* Like an inner join, but with an operator different from "=" in the condition, e.g., not equal "<>". SELECT projects.name AS "Project Name", teachers.name FROM teachers, projects WHERE teachers.id != projects.teacher;

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 ;

4.Self Join - With table aliases you can join a table to itself. SELECT DISTINCT * FROM assign a, assign b WHERE a.stud = 2 AND b.stud = 4 AND a.project = b.project;

5.Multi Join - The number of tables involved in a join are not restricted. SELECT DISTINCT assign.project, projects.name AS "Project", assign.percentage, stud.name AS "Student" FROM projects, assign, stud WHERE projects.id = 1 AND projects.id = assign.project

AND assign.stud = stud.id ;

Left outer join: Oracle8i

select last_name, department_name from employees e, departments d where e.department_id = d.department_id(+);

Left outer join: Oracle9i

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:

SELECT EMPNO, LASTNAME, PROJNO FROM CORPDATA.PROJECT RIGHT OUTER JOIN CORPDATA.EMPLOYEE ON EMPNO = RESPEMP WHERE LASTNAME > 'S'

Outer join of two tables

Example query (left outer join)

select * from state left outer join region on state.city = region.city;

Result

State:city

State:state

Region:city

Region:area

Jacksonville

FL

Jacksonville

South

Miami

FL

Miami

South

Nashville

TN

NULL

NULL

Example query (right outer join)

 

select * from state right outer join region on state.city = region.city;

 

Result

State:city

State:state

Region:city

Region:area

Jacksonville

FL

Jacksonville

South

Miami

FL

Miami

South

NULL

NULL

New Orleans

South

Example query (full outer join)

 

select * from state full outer join region on state.city = region.city;

 

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-----------------------><

   

s

QL 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,
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
SQL SELECT Statement
The most commonly used SQL command is SELECT statement. The SQL SELECT
statement is used to query or retrieve data from a table in the database. A query may
retrieve information from specified columns or from all of the columns in the table. To
create a simple SQL SELECT Statement, you must specify the column(s) name and the table name.
create a simple SQL SELECT Statement, you must specify the column(s) name and the
table name. The whole query is called SQL SELECT Statement.
Syntax of SQL SELECT Statement:
SELECT column_list FROM table-name
[WHERE Clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause];
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.

database table student_details;

id

 

first_name

last_name

age

subject

 

games

 
 
  • 100 Rahul

 

Sharma

   
  • 10 Science

 

Cricket

 
  • 101 Anjali

Bhagwat

  • 12 Maths

Football

  • 102 Stephen

Fleming

  • 09 Science

Cricket

 
  • 103 Shekar

 

Gowda

  • 18 Maths

Badminton

  • 104 Priya

Chandra

  • 15 Economics

Chess

 

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:

 

SELECT first_name FROM student_details;

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.

 

SELECT first_name, last_name FROM student_details;

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

 

SELECT first_name || ' ' || last_name FROM employee;

Output: first_name || ' ' || last_name --------------------------------- Rahul Sharma Anjali Bhagwat Stephen Fleming Shekar Gowda
Output:
first_name || ' ' || last_name
---------------------------------
Rahul Sharma
Anjali Bhagwat
Stephen Fleming
Shekar Gowda
Priya Chandra
You can also provide aliases as below.
SELECT first_name || ' ' || last_name AS emp_name FROM employee;
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
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:
Aliases for columns:
SELECT first_name AS Name FROM student_details;
or
SELECT first_name Name FROM student_details;
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 Aliases for tables:
Output:
Name
-------------
Rahul Sharma
Anjali Bhagwat
Stephen Fleming
Shekar Gowda
Priya Chandra
Aliases for tables:
SELECT s.first_name FROM student_details s;
In the above query, alias 's' is defined for the table student_details and the column
first_name is selected from the table.
Aliases is more useful when
There are more than one tables involved in a query,
Functions are used in the query,
The column names are big or not readable,
More than one columns are combined together
SQL WHERE Clause
The WHERE Clause is used when you want to retrieve specific information from a table
excluding other irrelevant data. For example, when you want to see the information about
students in class 10th only then you do need the information about the students in other

class. Retrieving information about all the students would increase the processing time

 

for the query.

 
 

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.

 

Syntax of SQL WHERE Clause:

WHERE {column or expression} comparison-operator value

Syntax for a WHERE clause with Select statement is:

SELECT column_list FROM table-name

 

WHERE condition;

 
 

column or expression - Is the column of a table or a expression

comparison-operator - operators like = < > etc.

 

value - Any user value or a column name for comparison

 

For Example: To find the name of a student with id 100, the query would be like:

SELECT first_name, last_name FROM student_details WHERE id = 100; Comparison Operators and Logical Operators are used
SELECT first_name, last_name FROM student_details
WHERE id = 100;
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.

How to use expressions in the WHERE Clause?

Expressions can also be used in the WHERE clause of the SELECT statement.

For example: Lets consider the employee table. If you want to display employee name, current salary,
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
SELECT name, salary, salary*1.2 AS new_salary FROM employee
WHERE salary*1.2 > 30000;
Output:
name salary new_salary ---------- --------- ---------------- - - Hrithik 35000 37000 Harsha 35000 37000 Priya 30000
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.

 

The below table describes each comparison operator.

Comparison Description Operators = <>, != < > >= <= equal to is not equal to
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.

Logical operators are discussed in detail in the next section.

SQL Logical Operators

There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at
There are three Logical Operators namely, AND, OR, and NOT. These operators
compare two conditions at a time to determine whether a row can be selected for the
output. When retrieving data using a SELECT statement, you can use logical operators in
the WHERE clause, which allows you to combine more than one condition.
SQL Comparison Keywords
There are other comparison keywords available in sql which are used to enhance the
search capabilities of a sql query. They are "IN", "BETWEEN
"LIKE".
AND",
"IS NULL",
Comparision
Description
Operators
LIKE
column value is similar to specified
character(s).
IN
column value is equal to any one of
a specified set of values.
BETWEEN
...
AND
IS NULL
column value is between two
values, including the end values
specified in the range.
column value does not exist.

SQL LIKE Operator

The LIKE operator is used to list all rows in a table whose column values match a

 

specified pattern. It is useful when you want to search rows to match a specific pattern, or when you do not know the entire value. For this purpose we use a wildcard character '%'.

For example: To select all the students whose name begins with 'S'

SELECT first_name, last_name FROM student_details WHERE first_name LIKE 'S%'; The output would be similar to: first_name
SELECT first_name, last_name
FROM student_details
WHERE first_name LIKE 'S%';
The output would be similar to:
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,
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,
SELECT first_name, last_name
FROM student_details
WHERE first_name LIKE '_a%';

The output would be similar to:

first_name last_name ------------- ------------- Rahul Sharma
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'.

 

SQL BETWEEN

...

AND Operator

The operator BETWEEN and AND, are used to compare data for a range of values.

For Example: to find the names of the students between age 10 to 15 years, the
For Example: to find the names of the students between age 10 to 15 years, the query
would be like,
SELECT first_name, last_name, age
FROM student_details
WHERE age BETWEEN 10 AND 15;

The output would be similar to:

first_name last_name age ------------- ------------- ------ Rahul Sharma 10 Anajali Bhagwat 12 Shekar Gowda 15
first_name last_name
age
------------- ------------- ------
Rahul
Sharma
10
Anajali
Bhagwat
12
Shekar
Gowda
15

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');

The output would be similar to:

first_name ------------- Anajali Shekar Rahul Stephen
first_name
-------------
Anajali
Shekar
Rahul
Stephen
last_name subject --------- ------------- - Bhagwat Maths Gowda Maths Sharma Science Fleming Science
last_name subject
---------
-------------
-
Bhagwat
Maths
Gowda
Maths
Sharma
Science
Fleming
Science

You can include more subjects in the list like ('maths','science','history')

NOTE:The data used to compare is case sensitive.

SQL IS NULL Operator

A column value is NULL if it does not exist. The IS NULL operator is used to display all

the rows for columns that do not have a value.

 
 

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

 
SELECT first_name, last_name FROM student_details WHERE games IS NULL There would be no output as we
SELECT first_name, last_name
FROM student_details
WHERE games IS NULL
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
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.
Syntax for using SQL ORDER BY clause to sort data is:
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2,
columnN] [DESC]];

database table "employee";

id

name

 

dept

 

age

salary

 

location

 
 
  • 100 Ramesh

Electrical

 

24

   
  • 25000 Bangalore

 
  • 101 Hrithik

Electronics

28

  • 35000 Bangalore

  • 102 Harsha

Aeronautics

28

  • 35000 Mysore

 
  • 103 Soumya

Electronics

22

  • 20000 Bangalore

 
  • 104 Priya

 

InfoTech

 

25

  • 30000 Mangalore

 

For Example: If you want to sort the employee table by salary of the employee, the sql

query would be.

 

SELECT name, salary FROM employee ORDER BY salary;

The output would be like

 

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,

SELECT name, salary FROM employee ORDER BY name, salary;

The output would be like:

name salary ------------- ------------- Soumya 20000 Ramesh 25000 Priya 30000 Harsha 35000 Hrithik 35000 NOTE:The columns
name
salary
-------------
-------------
Soumya
20000
Ramesh
25000
Priya
30000
Harsha
35000
Hrithik
35000
NOTE:The columns specified in ORDER BY clause should be one of the columns
selected in the SELECT column list.
You can represent the columns in the ORDER BY clause by specifying the position of a
You can represent the columns in the ORDER BY clause by specifying the position of a
column in the SELECT list, instead of writing the column name.
The above query can also be written as given below,
SELECT name, salary FROM employee ORDER BY 1, 2;
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.
SELECT name, salary FROM employee ORDER BY name, salary DESC; The above query sorts only the
SELECT name, salary
FROM employee
ORDER BY name, salary DESC;
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.
SELECT name, salary
FROM employee
ORDER BY name DESC, salary DESC;

How to use expressions in the ORDER BY Clause?

Expressions in the ORDER BY clause of a SELECT statement.

For example: If you want to display employee name, current salary, and a 20% increase in
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
SELECT name, salary, salary*1.2 AS new_salary
FROM employee
WHERE salary*1.2 > 30000
ORDER BY new_salary DESC;

The output for the above query is as follows.

name salary new_salary ---------- ---------- ------------- Hrithik 35000 37000 Harsha 35000 37000 Priya 30000 36000
name
salary
new_salary
---------- ---------- -------------
Hrithik 35000
37000
Harsha 35000
37000
Priya 30000 36000

NOTE:Aliases defined in the SELECT Statement can be used in ORDER BY Clause.

SQL GROUP Functions

Group functions are built-in SQL functions that operate on groups of rows and return one

value for the entire group. These functions are: COUNT, MAX, MIN, AVG, SUM,

 

DISTINCT

 
 

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
For Example: If you want the number of employees in a particular department, the query
would be:
SELECT COUNT (*) FROM employee
WHERE dept = 'Electronics';
The output would be '2' rows.
If you want the total number of employees in all the department, the query would take the
form:

SELECT COUNT (*) FROM employee;

The output would be '5' rows.

SQL DISTINCT(): This function is used to select the distinct rows.

For Example: If you want to select all distinct department names from employee table,

the query would be:

 

SELECT DISTINCT dept FROM employee;

To get the count of employees with unique name, the query would be:

SELECT COUNT (DISTINCT name) FROM employee;

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:

SELECT MAX (salary) FROM employee;

SQL MIN(): This function is used to get the minimum value from a column.

To get the minimum salary drawn by an employee, he query would be:

SELECT MIN (salary) FROM employee;

SQL AVG(): This function is used to get the average value of a numeric column.

To get the average salary, the query would be

SELECT AVG (salary) FROM employee;

SQL SUM(): This function is used to get the sum of a numeric column

To get the total salary given out to the employees,

SELECT SUM (salary) FROM employee;

SQL GROUP BY Clause

The SQL GROUP BY Clause is used along with the group functions to retrieve data grouped
The SQL GROUP BY Clause is used along with the group functions to retrieve data
grouped according to one or more columns.
For Example: If you want to know the total amount of salary spent on each department,
the query would be:
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept;

The output would be like:

dept
dept
----------------
----------------
Electrical Electronics Aeronautics InfoTech
Electrical
Electronics
Aeronautics
InfoTech
 

salary

 

-------------

-

25000

 

55000

35000

30000

NOTE: The group by clause should contain all the columns in the select list expect those
NOTE: The group by clause should contain all the columns in the select list expect those
used along with the group functions.
SELECT location, dept, SUM (salary)
FROM employee
GROUP BY location, dept;

The output would be like:

location

 

dept

 

salary

-------------

---------------

-----------

Bangalore

Electrical

 

25000

 

Bangalore

Electronics

55000

Mysore

 

Aeronautics

35000

Mangalore

InfoTech

 

30000

SQL HAVING Clause

Having clause is used to filter data based on the group functions. This is similar to

 

WHERE condition but is used with group functions. Group functions cannot be used in

WHERE Clause but can be used in HAVING clause.

 
 

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;

 
SELECT dept, SUM (salary) FROM employee GROUP BY dept HAVING SUM (salary) > 25000 The output
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept
HAVING SUM (salary) > 25000
The output 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.

We can insert data to a table in two ways,

1) Inserting the data directly to a table.

Syntax for SQL INSERT is:

INSERT INTO TABLE_NAME

 

[ (col1, col2, col3,

...

colN)]

 

VALUES (value1, value2, value3,

...

valueN);

 
 

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

 
 

INSERT INTO TABLE_NAME

 

VALUES (value1, value2, value3,

...

valueN);

 

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
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
VALUES (105, 'Srinath', 'Aeronautics', 27, 33000);
Inserting data to a table through a select statement.
Syntax for SQL INSERT is:
INSERT INTO table_name
[(column1, column2,
SELECT column1, column2,
columnN)]
columnN
FROM table_name [WHERE condition];
For Example: To insert a row into the employee table from a temporary table, the sql
For Example: To insert a row into the employee table from a temporary table, the sql
insert query would be like,
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,

 
 

INSERT INTO employee

 

SELECT * FROM temp_employee;

 
NOTE:We have assumed the temp_employee table has columns emp_id, emp_name, dept, age, salary, location in the
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.

SQL UPDATE Statement

The UPDATE Statement is used to modify the existing rows in a table.

The Syntax for SQL UPDATE Command is:

UPDATE table_name SET column_name1 = value1, column_name2 = value2, ... [WHERE condition] ∑ table_name - the
UPDATE table_name
SET column_name1 = value1,
column_name2 = value2, ...
[WHERE condition]
table_name - the table name which has to be updated.
column_name1, column_name2
..
- the columns that gets changed.
value1, value2
...
- are the new values.
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);

SQL Delete Statement

The DELETE Statement is used to delete rows from a table.

The Syntax of a SQL DELETE statement is:

DELETE FROM table_name [WHERE condition];

table_name -- the table name which has to be updated.

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,

 

DELETE FROM employee WHERE id = 100;

To delete all the rows from the employee table, the query would be like,

DELETE FROM employee;

SQL TRUNCATE Statement

The SQL TRUNCATE command is used to delete all the rows from the table and free the

space containing the table.

 

Syntax to TRUNCATE a table:

TRUNCATE TABLE table_name;

For Example: To delete all the rows from employee table, the query would be like,

TRUNCATE TABLE employee;

Difference between DELETE and TRUNCATE Statements:

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
TRUNCATE statement: This command is used to delete all the rows from the table and
free the space containing the table.
SQL DROP Statement:
The SQL DROP command is used to remove an object from the database. If you drop a
table, all the rows in the table is deleted and the table structure is removed from the
database. Once a table is dropped we cannot get it back, so be careful while using
RENAME command. When a table is dropped all the references to the table will not be
valid.

Syntax to drop a sql table structure:

DROP TABLE table_name;

For Example: To drop the table employee, the query would be like

DROP TABLE employee;

Difference between DROP and TRUNCATE Statement:

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.

 

SQL CREATE TABLE Statement

The CREATE TABLE Statement is used to create tables to store data. Integrity

 

Constraints like primary key, unique key, foreign key can be defined for the columns

 

while creating the table. The integrity constraints can be defined at column level or table

level. The implementation and the syntax of the CREATE Statements differs for different

RDBMS.

 

The Syntax for the CREATE TABLE Statement is:

CREATE TABLE table_name (column_name1 datatype, column_name2 datatype, column_nameN datatype ); ∑ table_name - is the name
CREATE TABLE table_name
(column_name1 datatype,
column_name2 datatype,
column_nameN datatype
);
table_name - is the name of the table.
column_name1, column_name2
....
- is the name of the columns
datatype - is the datatype for the column like char, date, number etc.

For Example: If you want to create the employee table, the statement would be like,

CREATE TABLE employee ( id number(5), name char(20), dept char(10), age number(2), salary number(10), location char(10)
CREATE TABLE employee
( id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
In Oracle database, the datatype for an integer column is represented as "number". In
Sybase it is represented as "int".

Oracle provides another way of creating a table.

CREATE TABLE temp_employee

   

SELECT * FROM employee

 
 

In the above statement, temp_employee table is created with the same number of columns

and datatype as employee table.

 

SQL ALTER TABLE Statement

The SQL ALTER TABLE command is used to modify the definition (structure) of a table by
The SQL ALTER TABLE command is used to modify the definition (structure) of a table
by modifying the definition of its columns. The ALTER command is used to perform the
following functions.
1) Add, drop, modify table columns
2) Add and drop constraints
3) Enable and Disable constraints
Syntax to add a column
ALTER TABLE table_name ADD column_name datatype;
For Example: To add a column "experience" to the employee table, the query would be
like

ALTER TABLE employee ADD experience number(3);

Syntax to drop a column

ALTER TABLE table_name DROP column_name;

For Example: To drop the column "location" from the employee table, the query would

be like

 

ALTER TABLE employee DROP location;

Syntax to modify a column

ALTER TABLE table_name MODIFY column_name datatype;

For Example: To modify the column salary in the employee table, the query would be like
For Example: To modify the column salary in the employee table, the query would be
like
ALTER TABLE employee MODIFY salary number(15,2);
SQL RENAME Command
The SQL RENAME command is used to change the name of the table or a database
object.
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.
Syntax to rename a table
RENAME old_table_name To new_table_name;
For Example: To change the name of the table employee to my_employee, the query
would be like

RENAME employee TO my_emloyee;

SQL Integrity Constraints

Integrity Constraints are used to apply business rules for the database tables.

The constraints available in SQL are Foreign Key, Not Null, Unique, Check.

Constraints can be defined in two ways 1) The constraints can be specified immediately after the
Constraints can be defined in two ways
1) The constraints can be specified immediately after the column definition. This is called
column-level definition.
2) The constraints can be specified after all the columns are defined. This is called table-
level definition.
1) SQL Primary key:
This constraint defines a column or combination of columns which uniquely identifies
each row in the table.

Syntax to define a Primary key at column level:

column name datatype [CONSTRAINT constraint_name] PRIMARY KEY

Syntax to define a Primary key at table level:

[CONSTRAINT constraint_name] PRIMARY KEY (column_name1,column_name2, )

..

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.

 

Primary Key at table level:

CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10),
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
or

CREATE TABLE employee

 

( id number(5) CONSTRAINT emp_id_pk PRIMARY KEY,

name char(20),

 

dept char(10),

age number(2),

salary number(10),

 

location char(10)

 

);

 

Primary Key at table level:

CREATE TABLE employee ( id number(5), name char(20), dept char(10), age number(2), salary number(10), location char(10),
CREATE TABLE employee
( id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
CONSTRAINT emp_id_pk PRIMARY KEY (id)
);
2) SQL Foreign key or Referential Integrity :
This constraint identifies any column referencing the PRIMARY KEY in another table. It
establishes a relationship between two columns in the same table or between different
tables. For a column to be defined as a Foreign Key, it should be a defined
tables. For a column to be defined as a Foreign Key, it should be a defined as a Primary
Key in the table which it is referring. One or more columns can be defined as Foreign
key.
Syntax to define a Foreign key at column level:
[CONSTRAINT constraint_name] REFERENCES
Referenced_Table_name(column_name)
Syntax to define a Foreign key at table level:
[CONSTRAINT constraint_name] FOREIGN KEY(column_name) REFERENCES
referenced_table_name(column_name);
For Example:
For Example:

1) Lets use the "product" table and "order_items".

Foreign Key at column level:

CREATE TABLE product

 

( product_id number(5) CONSTRAINT pd_id_pk PRIMARY KEY,

product_name char(20),

 

supplier_name char(20),

 

unit_price number(10)

 

);

 
CREATE TABLE order_items ( order_id number(5) CONSTRAINT od_id_pk PRIMARY KEY, product_id number(5) CONSTRAINT pd_id_fk REFERENCES, product(product_id),
CREATE TABLE order_items
( order_id number(5) CONSTRAINT od_id_pk PRIMARY KEY,
product_id number(5) CONSTRAINT pd_id_fk REFERENCES,
product(product_id),
product_name char(20),
supplier_name char(20),
unit_price number(10)
);

Foreign Key at table level:

CREATE TABLE order_items ( order_id number(5) , product_id number(5), product_name char(20), supplier_name char(20), unit_price number(10) CONSTRAINT
CREATE TABLE order_items
( order_id number(5) ,
product_id number(5),
product_name char(20),
supplier_name char(20),
unit_price number(10)
CONSTRAINT od_id_pk PRIMARY KEY(order_id),
CONSTRAINT pd_id_fk FOREIGN KEY(product_id) REFERENCES
product(product_id)
);

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)
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)
);
3) SQL Not Null Constraint :
This constraint ensures all rows in the table contain a definite value for the column which
is specified as not null. Which means a null value is not allowed.

Syntax to define a Not Null constraint:

[CONSTRAINT constraint name] NOT NULL

For Example: To create a employee table with Null value, the query would be like

CREATE TABLE employee ( id number(5), name char(20) CONSTRAINT nm_nn NOT NULL, dept char(10), age number(2),
CREATE TABLE employee
( id number(5),
name char(20) CONSTRAINT nm_nn NOT NULL,
dept char(10),
age number(2),
salary number(10),
location char(10)
);
4) SQL Unique Key:
This constraint ensures that a column or a group of columns in each row have a distinct
value. A column(s) can have a null value but the values cannot be duplicated.

Syntax to define a Unique key at column level:

[CONSTRAINT constraint_name] UNIQUE

Syntax to define a Unique key at table level:

[CONSTRAINT constraint_name] UNIQUE(column_name)

For Example: To create an employee table with Unique key, the query would be like,

Unique Key at column level:

CREATE TABLE employee

 

( id number(5) PRIMARY KEY,

name char(20),

 

dept char(10),

age number(2),

salary number(10),

 

location char(10) UNIQUE

);

 
or
or

CREATE TABLE employee

 

( id number(5) PRIMARY KEY,

 

name char(20),

 

dept char(10),

age number(2),

salary number(10),

 

location char(10) CONSTRAINT loc_un UNIQUE

);

 

Unique Key at table level:

CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10),
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
CONSTRAINT loc_un UNIQUE(location)
);
5) SQL Check Constraint :
This constraint defines a business rule on a column. All the rows must satisfy this rule.
The constraint can be applied for a single column or a group of columns.

Syntax to define a Check constraint:

[CONSTRAINT constraint_name] CHECK (condition)

For Example: In the employee table to select the gender of a person, the query would
For Example: In the employee table to select the gender of a person, the query would be
like
Check Constraint at column level:
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
gender char(1) CHECK (gender in ('M','F')),
salary number(10),

location char(10)

);

 

Check Constraint at table level:

CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), gender char(1),
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
gender char(1),
salary number(10),
location char(10),
CONSTRAINT gender_ck CHECK (gender in ('M','F'))
);

SQL Joins

SQL Joins are used to relate information in different tables. A Join condition is a part
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.
The Syntax for joining two tables is:
SELECT col1, col2, col3 ...
FROM table_name1, table_name2
WHERE table_name1.col2 = table_name2.col1;

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.

database table "product";

product_id

product_name

supplier_name

unit_price

     

Camera

  • 100 Nikon

   

300

 
  • 101 Onida

Television

 

100

  • 102 Vediocon

Refrigerator

   

150

Ipod

  • 103 Apple

   

75

Mobile

  • 104 Nokia

50

database table "order_items";

 

order_id

 

product_id

 

total_units

 

customer

 
 

5100

 

104

 

30

 

Infosys

 

5101

102

5

Satyam

5102

103

 
  • 25 Wipro

   

5103

101

  • 10 TCS

   
SQL Joins can be classified into Equi join and Non Equi join. 1) SQL Equi joins
SQL Joins can be classified into Equi join and Non Equi join.
1) SQL Equi joins
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.
2) SQL Non equi joins
It is a sql join condition which makes use of some comparison operator other than the
equal sign like >, <, >=, <=
1) SQL Equi Joins:
An equi-join is further classified into two categories:
a)
SQL Inner Join
b)
SQL Outer Join
  • a) SQL Inner Join:

All the rows returned by the sql query satisfy the sql join condition specified.

For example: If you want to display the product information for each order the query will
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 query for this type of sql joins would be like,
SELECT order_id, product_name, unit_price, supplier_name, total_units
FROM product, order_items
WHERE order_items.product_id = product.product_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
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,
SELECT o.order_id, p.product_name, p.unit_price, p.supplier_name,
o.total_units
FROM product p, order_items o
WHERE o.product_id = p.product_id;