Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
21 views
SQL Commands
Best SQL notes
Uploaded by
inglevaibhav2112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save SQL Commands For Later
Download
Save
Save SQL Commands For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
21 views
SQL Commands
Best SQL notes
Uploaded by
inglevaibhav2112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save SQL Commands For Later
Carousel Previous
Carousel Next
Save
Save SQL Commands For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 21
Search
Fullscreen
SQL COMMANDS > What is SQL? Structured Query Language and it helps to make practice on SQL commands which provides immediate results. + SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in relational database. + SQL is the standard language for Relation Database System. + All relational database management systems like MySQL, MS Acces Informix, and SQL Server use SQL as standard database language , and Oracle, Sybase, > > Why SQL Allows users to create and drop databases and tables. + Allows users to describe the data + Allows users to define the data in database and manipulate that da rs to access data in relational database management systems + Allows us + Allows embedding within other languages using SQL modules, libraries & pre-compilers. 0 Allows users to set permissions on tables, procedures, and views > SQL Architecture: + When you are executing an SQL command for any RDBMS, the system determines the best way to cary out your request and SQL engine figures out how to interpret the task. =] + ‘There are various components included in the process. ] + These components are: © Query Dispatcher o Optimization Engines 0 Classic Query Engine o SQL Query Engine, ete + Classic query engine handles all non-SQL queries but ee | SQL query engine won't handle logical files. | + Simple diagram showing SQL Architecture: ==] > SQL Commands: + The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. ‘These commands can be classified into groups based on their nature > DDL - Data Definition Language: + DDL defines the conceptual schema providing a link between the logical and the physical Structure of the database. * The functions of the Data Def ion Language (DDL) are: 1lPage Prof. K. AdiseshaChapter 14- SQL Commands DDL defines the physical characteristics of each record, filed in the record, fields data type, fields length, field”s logical name and also specify relationship among those records. DDL describes the schema and subschema. DDL indicate the keys of records DDL provides data security measures DDL provides for the logical and physical data independence. * Few of the basic commands for DDL are: veen ‘Command Description CREATE | Creates a new table, a view of a table, or other object in database ALTER | Modifi existing database object, such as a table. DROP _| Deletes an entire table, a view of a table or other object in the database. > DML - Data Manipulation Language: + DML provides the data manipulation techniques like selection, insertion, deletion, updation, modification, replacement, retrieval, sorting and display of data or records. + DML facilitates use of relationship between the records, DML provides for independence of programming languages by supporting several high-level programming languages like COBOL, PL/I and C++. * Few of the ba commands for DML are: Command Description SELECT | Retrieves certain records from one or more tables INSERT | Creates a record UPDATE | Modifies records DELETE | Deletes records > DCL - Data Control Language: + These SQL commands are used for providing security to database obj * The different DCL commands are: Command Description GRANT | Gives a privilege to user REVOKE, | Takes back privileges granted from user > TCL - Transaction Control Language: It includes commands to control the transactions in a database system. + The commonly used commands are: 2IPage Prof. K. AdiseshaChapter 14- SQL Commands Command Description COMMIT | Make all the changes made by the statements issued permanent, ROLLBACK | Undoes all changes since the beginning of transaction or since e point. > Data Types in SQL: ‘The following are the most common data types of SQL: SL No DATA TYPE DESCRIPTION 1 | NUMBER A variable-length column. Allowed values are zero, positive and negative numbers 2 | CHAR A variable length field up to 255 character in length 3 | VARCHAR/VARCHAR? | A variable length field up to 2000 character in length A fixed length field. The time is stored as a part of the 4 | DATE date, The default format is DD/MON/YY 5 | LONG A variable length filed up to 2 GB in length | vi ina 2 6 lRaw A variable length filed used for binary data up to 2000 in length A variable length filed used for binary data up to 2GB 7 [EONGRAW: in length 1. NUMBER: * Used to store a numeric value in a field column. © Itmay be decimal, integer o real value. © General syntax: NUMBER(n, d) Where n specifies the number of digits and d specifies the number of digits to right of the decimal point. Example: marks NUMBER(3), average NUMBER(2, 3) 2. CHAR: Used to store a character type data in a column, © General syntax: CHAR(size) o Where size represents the maximum (255 Characters) waracters in a column, © Example: name CHAR(IS) 3. VARCHAR/VARCHAR2: © Itis used to store variable length alphanumeric data. * General syntax: VARCHAR(size) / VARCHAR2size) 31P a Prof. K. AdiseshaChapter 14- SQL Commands © Where size represents the maximum (2000 Characters) number of characters in a column. © Example: address VARCHAR2(50) 4. DATE: © It is used to store date in columns. © SQL supports the various date formats other than the standard D-MON-YY. © Example: — dob DATE. 5. TIME: Tt is used to store time in columns. SQL supports the various time formats other than the standard hh-mm-ss. Every DATE and TIME can be added, subtracted or compared as it can be done with other data types. 6. LON 1. Itisused to store variable length strings of up to 2GB size. 2. Example: description LONG > Structure of SQL command: + Any SQL command is a combination of keywords, identifiers and clauses. + Every SQL command begins with a keyword (CREATE, SELECT, DELETE and so on) which as a specific meaning to the language. + SELECT, FROM and WHERE are keywords. + The clauses are “FROM student” and “WHERE RegNo=109”, + Here SELECT and FROM are mandatory, but WHERE is optional. + Name, Student, RegNo, are identifier that refers to objects in the database. + Name and RegNo are column names, while Student is a table name. + The equal sign is an operator and 109 is a numeric constant, > What is an Operator in SQL? © An operator is a reserved word or a character used primarily in an SQL statement’s WHERE clause to perform operation(s), such as comparisons and arithmetic operations. © Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement. 0 Arithmetic operators (+, -, *, / %) 0 Comparison ‘operators (>, <, >=, . <>, I<, 1>) © Logical operators (AND, OR, NOT, IN, BETWEEN, EXISTS, ALL, ANY, LIKE, UNIQUE) Prof. K. Adisesha> SQL Logical Operators: Here is a list of all the logical operators available in SQL. Operator Description ALL | The ALL operator is used to compare a value to all values in another value set. AND |The AND operator allows the existence of multiple conditions in an SQL statements WHERE clause. ANY | The ANY operator is used to compare a value to any applicable value in the list according to the condition, BETWEEN | The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value. EXISTS | The EXISTS operator i used to search for the presence of a row in a specified table that meets certain criteria. IN The IN operator is used to compare a value to a list of literal values that have been specified LIKE | The LIKE operator is used to compare a value to similar values using wiklcard operators. NOT | The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator. OR | The OR operator is used to combine multiple conditions in an SQL statement’s WHERE clause ISNULL | The NULL operator is used to compare a value with a NULL value. UNIQUE | The UNIQUE operator searches every row of a specified table Tor uniqueness (no duplicates), > Implementation of SQL Commands v CREATE TABLE * The SQL CREATE TABLE statement is used to create a new table. + Creating a basic table involves naming the table and defining its columns and each column's data type. + Syntax: Basic syntax of CREATE TABLE statement is as follows: 51Page CREATE TABLE Table_name ce columnl datatype, column? datatype, _column3 datatype, columaN datatype, PRIMARY KEY( one or more columns ) ys Prof. K. AdiseshaChapter 14- SQL Commands + Here CREATE TABLE is the keyword followed by the Table_name, followed by an open parenthesis, followed by the column names and data types for that column, and followed by a closed parenthes + For cach column, a name and a data type must be specified and the column name must be unique within the table definition. + Column definitions are separated by commas (,). + Uppercase and lowercase letters makes no difference in column names + ach table must have at least one column, 0 SQL commands should end with a semicolon (:) + Example: Create a table “STUDENT” that contains five columns: RegNo, Name, Combination, DOB and Fe CREATE TABLE STUDENT. ( RegNo NUMBER (6), Name VARCHAR? (15), Combination CHAR (4), DOB DATE, Fees NUMBER (9, 2), PRIMARY KEY ( RegNo ) ): + Itcreates an empty STUDENT table which looks like thi RegNo | Name | Combination | DOB | Fees 7 Viewing the table information: © The DESCRIBE or DESC command displays name of the columns, their data type and size along with the constraints. SQL> DESCRIBE STUDENT; Null? Type NOT NULL NUNBER(6) VARCHAR2(15) COMBINATION CHAR(4) os DATE FEES NUMBER (4,2) v ALTER Statement: + The table can be modified or changed by using the ALTER command. + Syntax: Basic syntax of ALTER TABLE statement is as follows 1. ALTER TABLE Tabl ADD (column_name! DataType, Cloumn_name2 DatalType...): 2. ALTER TABLE Tuble_name MODIFY (column_namel DataType, Cloumn_name2 DataType...); 3. ALTER TABLE Table_name DROP (column_namel DataType, Cloumn_ me? DataType...); Prof. K. Adisesha 61P aChapter 14- SQL Commands + Example: ‘SQL> ALTER TANLE STUDENT ROD (Address aRCHAR? (38)); Table altered. SQL> ALTER TABLE STUDENT MODIFY (Rares URREHAR2 (48)); Tanie aiterea. SQL> ALTER TABLE STUDENT DROP (ADDRESS); Tanie altered. + Using the ALTER TABLE command the following tasks cannot be performed © Changing a table name. © Changing the column name. © Decreasing the size of a column if table data exists. © Changing a column's data type. Y DROP TABLE: * The SQL DROP TABLE statement is used to remove a table definition and all data, indexes, triggers, constraints, and permission specifications for that table, 0 Syntax: Basic syntax of + DROP TABLE statement is as follows: DROP TABLE Table_name; + Example: QL> DROP TABLE STUDE able dropped v INSERT: + The SQL INSERT INTO Statement is used to add new rows of data to a table in the database. + Syntax: + There are two basic syntaxes of INSERT INTO statement as follows: Here, column, column2,...columnN are the names of the columns in the table into which you want to insert data, + You may not need to specify the column(s) name in the SQL query if you are adding values for all the columns of the table, But make sure the order of the values is in the same order as the columns in the table. METHOD 1: The SQL INSERT INTO syntax would be as follows + Example: Following statements would create six records in STUDENT table: TIPage Prof. K. AdiseshaChapter 14- SQL Commands + METHOD 2: The SQL INSERT INTO syntax would be as follows: + Alll the above statements would produce the following records in STUDENT table: 1401 RAHESH 1492 JOHN PCHE 1493 GANESH PCHE 19-AUG-99 104 HAHESH PCHE 14-JAN-98 41NO5 SURESH PCHB 03-iiaR-98 4410 ARUN PCHE O1-APR-O% 4414 suREvA ani2 PcHe rous selected. v UPDATE: + SQL provides the ability to change data through UPDATE command. + The UPDATE command used to modify or update an already existing row or rows of a table. + The basic syntax of UPDATE command is given below. Example: BIPage Prof. K. AdiseshaChapter 14- SQL Commands ¥ DELETE command: + In SQL, an already existing row or rows are removed from tables through the use of DELETE. command. + The basic syntax of DELETE command is given below. Example: v SELECT: SQL SELECT statement is used to fetch the data from a database table which returns data in the form of result table. These result tables are called result-sets. Syntax: The basic syntax of SELECT statement is as follows: SELECT column!, column2, columnN | Compulsory FROM Table_name; Part [WHERE condition(s] Optional [GROUPBY column-list] Part [HAVING condition(s)] ORDER BY column-name(s)|; Here, column1, columnd..are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax: Example: Consider the STUDENT table having the following records REGNO NAME cone noe FEES saat SHREYA rows selected. Following is an example, which would fetch REGNO, NAME and COMBINATION fields of the customers available in STUDENT table: 91P a Prof. K. AdiseshaChapter 14- SQL Commands QL> SELECT REGNO, NAME, COMBINATION FROW STUDENT; REGNO NAHE cons 4401 RAMESH PCH 4402 JOHN PCH 1403 GANESH PCHE 1404 MAHESH PCH 4405 SURESH. PCH 410 ARUN PCH 4411. SHREVA EBA rows selected. v DISTINCT: + The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records. ‘There may be a situation when you have multiple duplicate records in a table, While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records, + Syntax: The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows: + Example: Consider the STUDENT table having the following records: [SQL> select = Fron student; SH pene 1402. JOHN eM 440 an'sH PeMe 804 MESH Pen 14-snt-98 PcHe ene ceBA 49-Auk-99 “1405. SURESH 10 ARUN v1 SHREYA lr rows setectea. + First, let us see how the following SELECT query returns duplicate combination records rows selected. + Now, let us se DISTINCT keyword with the above SELECT query and see the result + This would produce the following result where we do not have any duplicate entry: 101P age Prof. K. AdiseshaChapter 14- SQL Commands {QLD SELECT DISTINCT COMBINATION FROM STUDENT ORDER GY COMBINATIONS v WHERE clause — (Extracting specific rows) + The SQL WHERE clause is used to specify a condition while fetching the data from single table or joining with multiple tables. + Ifthe given condition is satisfied then only it returns specific value from the table. You would use WHERE clause to filter the records and fetching only necessary records. ‘The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which we would examine in subsequent chapters. + Syntax: The basic syntax of SELECT statement with WHERE clause is as follows: + You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT, ete. + Following is an example which would fetch REGNO, NAME and FEES fields from the STUDENT table where FEES is greater than 15000: [SQL> SELECT REGNO, NAME, FEES FROM STUDENT WHERE FEES>1500% REGNO MANE 193 GANESH 140% MAHESH htt SHREYA 2haao, + Following is an example, which would fetch REGNO, NAME and COMBINATION fields from the STUDENT table for a COMBINATION is ,,PCMC™. + Here, it is important to note that all the strings should be given inside single quotes (") where as numeric values should be given without any quote as in above example: QL> SELECT REGNO, NANE, COMBINATION FRON STUDENT WHERE COHBINATION="PCHIC™ ; REGNO NAME come 1401 RANESH pone 140% HAHESH pone 4410 ARUN pene + The SQL AND and OR operators are used to combine multiple conditions to narrow data in an SQL statement. These two operators are called conjunctive operators. + These operators provide a means to make multiple comparisons with different operators in the same SQL statement. MIP Prof. K. AdiseshaChapter 14- SQL Commands ¥ The AND Operator: * The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause. ‘+ Syntax: The basic syntax of AND operator with WHERE clause is as follows: You can combine N number of conditions using AND operator. For an action to be taken by the SQL statement, whether it be a transaction or query, all conditions separated by the AND must be TRUE. + Example: Consider the STUDENT table having the following records: REGNO NAHE coms DOB FEES. 4401 RAMESH Pec 97-AUG-99 44900 4482 JOHN PCHB 15-SEP-99 12500 1403 GANESH PCHE 19-AuG-99 16000 1404 MAHESH PCHC 14-JAN-98 17650 1405 SURESH PCHB 03-MAR-98 11500 4410 ARUN PCHC O1-APR-O% 13000 4411 SHREYA cEBA 24080 + Following is an example, which would fetch REGNO, NAME and DOB fields from the STUDENT table where fees is less than 1500 AND combination is ,PCMC: SQL> SELECT REGO, NAME, DOB FROM STUDENT WHERE FEESC15000 AND COMDINATION= “PCH” ; REGHO NAHE pos 1401 RAMESH ‘97-AuG-99 4410 ARUN 01-APR-O% ¥ The OR Operator: +The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause. + Syntax: The basic syntax of OR operator with WHERE clause is as follows: + You can combine N number of conditions using OR operator. For an action to be taken by the SQL statement, whether it be a transaction or query, only any ONE of the conditions separated by the OR must be TRUE. + Following is an example, which would fetch REGNO, NAME and DOB fields from the STUDENT table where fees is less than 1500 OR combination is ,PCMC: 121Page Prof. K. AdiseshaChapter 14- SQL Commands SQL> SELECT REGNO, RANE, DOB FROM STUDENT WHERE FEES<15 ‘OR CONBINATION=" PHO"; REGNO NAHE pop 1401 RAMESH 97-AUG-99 1402 JOHN 15-SEP-99 1404 MAHESH 14-JAN-98. 4405 SURESH 93-HAR-9 4410 ARUN 81-APR-O% v ORDER BY - (Sorting the data) + The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sorts query results in ascending order by default, + Syntax: The basic syntax of ORDER BY clause is as follows: + You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be in column-list. + Example: Consider the STUDENT table having the following records: REGNO NAHE ‘CON DOB 1401 RAMESH "CHC 87-AUG-99 4402 JOHN PCHB 15-SEP-99 1403 GANESH PCHE 19-AUG-99 1404 MAHESH PCHC 14-Jan-98 4405 SURESH PCHB 93-HaR-08 4410 ARUN PCH 01-APR-O% 4411 SHREVA, ceBA + Following is an example, which would sort the result in ascending order by NAME: QL> SELECT = FROM STUDENT ORDER BY NAHE; REGNO NAHE comp Doe FEES 1410 ARUN PCNC 61-APR-On 13000 4403 GANESH PCME 19-AUG-99 16000 4402 JOHN PCNB 15-SEP-99 43500 1404 MAHESH PCNC 14-JAN-98 17650 4401 RAHESH PCMc 97-AUG-99 44900 4614 SHREYA cEBA 24000 1405 SURESH PCMB 03-NAaR-98 41500 rows selected. BIPage Prof. K. AdiseshaChapter 14- SQL Commands + Following is an example, which would sort the result in descending order by NAME: QL> SELECT © FROM STUDENT ORDER BY WANE DESC; REGHO NAHE comp pop FEES 405 SURESH PCMB 63-NAR-98 11500 4417 SHREYA ceBA 2401 4401 RAHESH PCNC 67-AuG-99 44900 4hO4 HAHESH PCNC 1h-JAN-98 17658 4402 JOHN PCMB 15-SEP-99 13500 1403 GANESH PCME 19-AUG-99 16000 4410 ARUN PCN 61-APR-O4 13000 7 rows selected. Y Working out simple calculations. ‘+ Whenever we want to perform simple calculations such as 10/ 5, we can perform using SELECT statement which causes an output on monitor. + But SELECT requires table name to operate + One can make use of the dummy table provided by SQL called DUAL which is a single row and single column table + Itis used when data from table is not required. + For example, when a calculation is to be performed such as 10*3, 10/2 etc. and to display the current system date, we could use the following queries. [SQL> SELECT 16+5 FROM DUAL; | (SQL> SELECT S¥SDATE FROM DUAL; 10"5 YSDATE [22-DEC-16 Y SQL Functions: + The SQL functions serve the purpose of manipulating data items and returning a result + There are many built in functions included in SQL and can be classified as Group Functions and Scalar Functions. + Group Functions: o Functions that act on set of values are called group functions © A group functions can takes entire column of data as its arguments and produces a single data item that summarizes the column, © Following are the SQL group functions, Function Description AVG Returns average value of .N*, ignoring NULL values COUNT(expr) | Returns the number of rows where expr’ is not NULL COUNT(*) | Returns the number of rows in the table including duplicates and those with NULL values MIN Retums minimum value of expr” MAX Retums maximum value of expr” SUM Returns sum of values .N* 141 Prof. K. AdiseshaChapter 14- SQL Commands + Scalar Functions: ‘© Functions that act on only one value at a time are called scalar functions. 0 We can further classify the functions using the type of data with they are designed to work. Function Description Numeric | Work with numbers. Functions Examples: ABS, POWER, ROUND, SQRT String Work with character based data, Functions Examples: LOWER, INITCAP, UPPER, SUBSTR, LENGTH, LTRIM, RTRIM Date ‘Work with Date data types. Functions | Example: ADD_MONTHS, LAST_DAY, MONTHS_BETWEEN, NEXT_DAY Conversion — | These functions are used to convert one type of data to another. Functions | Example: TO_NUMBER, TO_CHAR, TO_DATE Consider the EXAMINATION table: RegNo | Name | CC | Phy | Che | Mat ] Cs | Total] City Tol | Ajay cr | 98 | 100) 97 | 99 | 304 | Hassan 102 | Banu a@ | 38 | 50 | 37 | 49 | 174 | Ber 103 [Chandan | C2 | 100 | 100 | 97 | 99 | 396 | Mysuru 104 | John c | 7% | 80 | 7 | 79 | 308 | Atwr 105 |Kalem | Cl | 88 | 80 | OF 79 | 338 | Hassan 106 | Raheem | C2 | 100 | 98 97 79 | 374 | Hassan 107 | Sanjay c | 47 60 56 78 | 241 | Alur 108 | Tarun G3 | 33 34 7 28 | 172 | Arasikere 109 | Uday c2 | 100 | 98 97 79 | 374 | Hassan 110 | Venki c3 | 47 60 56 78 | 241 | Belur ¥ COUNT ( ) Function: This function is used to count the number of values in a column, + COUNT (*) is used to count the number of rows in the table including dupli NULL values. + Example 1: + SELECT COUNT (+) FROM EXAMINATION; + The above query returns 10. + Example 2: + SELECT COUNT (RegNo) FROM EXAMINATION WHERE CC = + The above query returns 4, tes and those with ISP a Prof. K. AdiseshaChapter 14- SQL Commands v AVG () Functio * — This function is used to find the average of the values in a numeric column, + Example |: + SELECT AVG (Cs) FROM EXAMINATION; + The above query returns 74.7 y SUM () Function: + This function is used to find the sum of the values in a numeric column. + Example: + SELECT SUM (Phy) FROM EXAMINATION; + The above query returns 729 ¥ MAX () Function: + This function is used to find the maximum values in a column, + Example: * SELECT MAX (Phy) FROM EXAMINATION; + The above query returns 100 ¥ MIN () Function: + This function is used to find the minimum values in a column, + Example: + SELECT MIN (Phy) FROM EXAMINATION; + The above query returns 33 v GROUP BY (Grouping Result) + The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. + The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause. + Syntax: The basic syntax of GROUP BY clause is given below. + Example 1: To find the number of students in each college. SELECT CC, COUNT (CC) FROM EXAMINATION GROUPBY CC: + Example 2: To find the number of students, sum, average, maximum, minimum marks in computer science from each city SELECT City, COUNT (City), SUM (Cs), AVG (Cs), MAX (Cs), MIN (Cs) FROM EXAMINATION GROUP BY City; 16 IP age Prof. K. AdiseshaChapter 14- SQL Commands > SQL CONSTRAINTS: * Constraints are the rules enforced on data columns on table. + These are limiting the type of data that can go into a table. + This ensures the accuracy and reliability of the data into the database. + SQL allows two types of cor s © Column level constraints: These constraints are defined along with the column definition when creating or altering a table structure. These constraints apply only to individual columns, © Table level constraints: These constraints are defined after all the table columns when creating or altering a table structure. These constraints apply to groups of one or more columns, + Following are the commonly used constraints available in SQL. Constraints Description NOT NULL Ensures that a column cannot have NULL value UNIQUE Ensures that all values in column are different PRIMARY KEY | Uniquely identified eac row in a database table. FOREIGN KEY | Uniquely identified each rown in any other database table DEFAULT Provides a default value for a column when none is specified CHECK Ensures that all values in a column satisfy certain condition. ¥ NOT NULL Constraint: + By default column can hold NULL values. + When a column is defined as NOT NULL then the column becomes a mandatory column, ‘+ Icimplies that a value must be entered into the column if the row is to be inserted for storage in the table. + Example: Consider the following CREATE TABLE command creates a new table called PRODUCT and add six columns, two which PID and Description specify not to accept NULLS. CREATE TABLE PRODUCT ( PID CHAR (4) NOT NULL, Description VARCHAR2 (25), NOT NULL ‘Companyld CHAR (10), DOM DATE, Type CHAR (10), Price NUMBER (10,2 % Y UNIQUE Constraints: * This constraint ensures that no rows have the same value in the specified column(s). A table must have many unique keys. + Example: UNIQUE constraint applied on PID of PRODUCT table ensures that no rows have the same PID value, as shown below a Prof. K. AdiseshaChapter 14- SQL Commands CREATE TABLE PRODUCT ( PID CHAR (4) NOT NULL UNIQUE, Description VARCHAR2 (25), NOT NULL ‘Companyld CHAR (10), DOM DATE, Type CHAR (10), Price NUMBER (10.2) » v PRIMARY KEY Constraints: +A primary key is a field which uniquely identifies each row in a database table. A primary ke table has special attributes + By default this column is NOT NULL. It defines the column as a mandatory column ie. the column cannot be left blank. * The data held in this column must be unique. + Example: CREATE TABLE PRODUCT ( PID CHAR (4) PRIMARY KEY, Description VARCHAR? (25), NOT NULL ‘Companyld CHAR (10), DOM DATE, Type CHAR (10), Price NUMBER (10,2) dy v FOREIGN KEY Constraint: + A FOREIGN KEY is used to link two tables together. + A foreign key is a column whose values are derived from the PRIMARY KEY of some other table. + Example: CREATE TABLE PRODUCT ( PID CHAR (4) PRIMARY KEY, Description VARCHAR? (25), NOT NULL Companyld CHAR (10) REFERENC COMPANY (CID) DOM DATE, Type CHAR (10), Price NUMBER (10,2) % CREATE TABLE COMPANY ( cID CHAR (10) PRIMARY KEY, Profile VARCHAR2 (200), Noofproducts. NUMBER (20), DOE DATE 18 IP a Prof. K. AdiseshaChapter 14- SQL Commands ¥ DEFAULT Constraints: + A default value can be specified for a column using the DEFAULT clause. + The ‘AULT constraint provides a default value to a column when the INSERT INTO. command does not provide a specific value. + Example: CREATE TABLE PRODUCT ¢ PID CHAR (4) PRIMARY KEY, Description VARCHAR? (25), NOT NULL. ‘Companyld CHAR (10), DOM DATE, Type CHAR (10), Price NUMBER (10, 2) DEFALUT 1000.00 » ¥ CHECK Constraints: + The CHECK Constraint is used to establish a TRUE/FALSE condition that is applied to the data placed in a column + Ifa value does not meet the condition, it cannot be placed in the column. + Example: CREATE TABLE PRODUCT ( PID CHAR (4) CHECK (PID LIKE *P%’), Description VARCHAR? (25), ‘Companyld CHAR (10), DOM DATE, ‘Type CHAR (10), Price NUMBER (10, 2) CHECK (Price>0) dy ¥ TABLE Constraints: + When a constraint is applied to a group of cohmns of the table, itis called a table constraint. + Column constraint is defined along with the end of the column, + Table constraints are defined at the end of the table + Example: CREATE TABLE PRODUCT ( PID CHAR (4) NOT NULL, Description VARCHAR? (25) NOT NULL, ‘Companyld CHAR (10), DOM DATE, Type CHAR (10), Price NUMBER (10, 2), PRIMARY KEY (PID, Description) 191Pa Prof. K. AdiseshaChapter 14- SQL Commands > Joins * The SQL Joins clause are used to fetch/retrieve data from two or more tables based on the join corlition which is specified in the WHERE condition. + Basically data tables are related to each other with keys. We can used these keys relationship in SQL joins. ¥ SQL Join Types: ‘There are different types of joins available in SQL: o INNER JOIN: returns rows when there is a match in both tables. o LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table. co RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table. © FULL JOIN: returns rows when there is a match in one of the tables. © SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement. o CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables. > Creating VIEWs: Database Views are created using the CREATE VIEW statement. + Views can be created from a single table, multiple tables or another view. + To create a view, a user must have the appropriate system privilege according to the specific implementation. + Syntax: The basic CREATE VIEW syntax is as follows: > Privileges and Roles: + Privileges: Privileges defines the access rights provided to a user on a database object. + There are two types of privileges: © System Privileges: This allows the user to CREATE, ALTER, or DROP database objects. © Object privileges: This allows the user to EXECUTE, SELECT, INSERT, UPDATE or DELETE data from database objects to which privileges apply. 21Page Prof. K. AdiseshaChapter 14- SQL Commands VSA (1 marks) SA 2 marks) LA (3 Marks) | Essay (5 Marks) Total 01 Question . 01 Question 02 Question - Question no 17 - Question no 36 (06 Marks Important Questions Two Marks Questions: 1. Give the syntax and example for DELETE command in SQL. [March 2015} 2. List the data types supported in SQL. (June 2015] 3. Write the syntax for DELETE and INSERT commands in SQL. [March 2016] 4, Mention the logical operators used in SQL. (June 2016] 5. Give the syntax and example of UPDATE command in SQL. [March 2017] 6. What is the difference between ORDER BY and GROUP BY clause used in SQL? Give example for each, (June 2017] 7. List the relational operators supported by SQL. 8. Why the DROP command used? Write its syntax. 9. What are the difference between DROP and DELETE command? 10. Give the syntax and example for CREATE VIEW command in SQL. 11. Classify the built-in functions in SQL. Five Marks Question: 1. Explain various group functions in SQL. [March 2015, March 2017, June 2017) 2. What is data definition language? Explain SELECT and UPDATE command. (une 2015] 3. Describe any five logical operators available in SQL. [March 2016} 4. What is SQL? Explain the different SQL commands. 5. What is the purpose of CREATE command? Write the syntax and example of CREATE command. 6. Explain SELECT statement with syntax and with minimum 3 examples. 7. Explain 5 variations of SELECT command. 8, What are SQL constraints? Explain any two constraints. SH Heoeeeee IP a Prof. K. Adisesha
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6125)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (627)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brené Brown
4/5 (1148)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (932)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8214)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (954)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2922)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (484)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4972)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Tóibín
3.5/5 (2061)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4281)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (447)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1068)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1987)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1993)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2641)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4074)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2530)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4/5 (105)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Principles: Life and Work
From Everand
Principles: Life and Work
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Steve Jobs
From Everand
Steve Jobs
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Yes Please
From Everand
Yes Please
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
The Outsider: A Novel
From Everand
The Outsider: A Novel
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
John Adams
From Everand
John Adams
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
Little Women
From Everand
Little Women
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel