Você está na página 1de 8

SQL FAQ Popular Relational Database Management Systems

 SQL is short for Structured Query Language  Microsoft SQL Server (Microsoft Corporation)
 SQL is a declarative programming language for interaction  DB2 (IBM)
with Relational Database Management Systems (RDBMS)  Oracle (Oracle Corporation)
 SQL is pronounced as either "S-Q-L" or "sequel"  MySQL (Oracle Corporation)
 SQL was originally developed at IBM in the 1970s.  PostgreSQL (Open Source)
 RDBMS store data in tables  Microsoft Access (Microsoft Corporation)

Creating a Database Table


CREATE TABLE <TableName> CREATE TABLE Cars
( ColumnName1 DataType, ( Company VARCHAR(100),
ColumnName2 DataType, Country VARCHAR(100),
ColumnName3 DataType, Model VARCHAR(255),
…. ) YEAR INT )

Selecting Data from a Database Table Inserting Data in a Database Table


SELECT <List of Table Columns> INSERT INTO <TableName>
FROM <TableName> (<List of Table Columns>) VALUES (<Values>)
WHERE <Search Criteria> Example:
Example: INSERT INTO Cars
SELECT Company, Country, Model, Year (Company, Country, Model, Year) VALUES
FROM Cars ('Toyota ', 'Japan ', 'Camry ', 2014)
WHERE Year > 2012

Updating Data in a Table Deleting Data from a Table


UPDATE <TableName> DELETE FROM <TableName>
SET <Column1> = <Value1>, <Column2> = <Value2>, … WHERE <Search Criteria>
WHERE <Search Criteria> Example:
Example: DELETE FROM Cars
UPDATE Cars WHERE Year < 1990
SET Country = 'Japan'
WHERE Company = 'Toyota'

Grouping Data and Using Aggregate Functions Ordering Data Results


SELECT <List of Table Columns> SELECT <List of Table Columns>
FROM <TableName> FROM <TableName>
WHERE <Search Criteria> WHERE <Search Criteria>
GROUP BY < List of Table Columns> ORDER BY < List of Table Columns>
Example: SELECT Company, COUNT(*) Example: SELECT Company, Model, Year
FROM Cars FROM Cars
WHERE Year = 2014 WHERE Country = 'Japan'
GROUP BY Company ORDER BY Company, Model

Selecting Data from Multiple Tables Using UNION Operator


SELECT < List of Table Columns> SELECT < List of Table Columns > FROM <TableName1>
FROM <TableName1> INNER JOIN <TableName2> UNION
ON <TableName1>.<Column1> = <TableName2>.<Column5> SELECT < List of Table Columns > FROM <TableName2>
Example: Example:
SELECT Customers.Name, Orders.CarModel SELECT Company, Country, Model, Year FROM Cars
FROM Customers JOIN Orders ON UNION
Customers.ID = Orders.CustomerID SELECT Company, Country, Model, Year FROM Trucks

ramnibas@hotmail.com
Primary Key – It is a column or set of columns in a table that uniquely identifies tuples (rows) in that table.
Super Key – A super key is a set of one of more columns (attributes) to uniquely identify rows in a table.
Candidate Key – A super key with no redundant attribute is known as candidate key
Alternate Key – Out of all candidate keys, only one gets selected as primary key, remaining keys are known as
alternate or secondary keys.
Composite Key – A key that consists of more than one attribute to uniquely identify rows (also known as
records & tuples) in a table is called composite key.
Foreign Key – Foreign keys are the columns of a table that points to the primary key of another table. They act
as a cross-reference between tables.
Natural keys. A natural key is one or more existing data attributes that are unique to the business
concept. For the Customer table there was two candidate keys, in this
case CustomerNumber and SocialSecurityNumber.
Surrogate key. Introduce a new column, called a surrogate key, which is a key that has no business
meaning. Addresses don't have an "easy" natural key because you would need to use all of the columns of
the Address table to form a key for itself (you might be able to get away with just the combination
of Street and ZipCode depending on your problem domain), therefore introducing a surrogate key is a much
better option in this case.
The primary key is a unique key in your table that you choose that best uniquely identifies a record in the
table. All tables should have a primary key, because if you ever need to update or delete a record you need
to know how to uniquely identify it.
A surrogate key is an artificially generated key. They're useful when your records essentially have no natural
key (such as a Person table, since it's possible for two people born on the same date to have the same name,
or records in a log, since it's possible for two events to happen such they they carry the same timestamp).
Most often you'll see these implemented as integers in an automatically incrementing field, or as GUIDs that
are generated automatically for each record. ID numbers are almost always surrogate keys.
CARDINALITY
In terms of data modeling, cardinality refers to the relationship between two tables. They can be of four types:
One to One – A single row of table 1 associates with single row of table 2
One to Many – A single row of table 1 associates with more than one rows of table 2
Many to One – Many rows of table 1 associate with a single row of table 2
Many to Many – Many rows of table 1 associate with many rows of table 2
be having the low cardinality. These cardinality scores helps in query optimization.
ACID Property:
To ensure the integrity of data during a transaction the database system maintains ACID properties:

 Atomicity: This property ensures that either all the operations of a transaction reflect in database or
none.
 Consistency: To preserve the consistency of database, the execution of transaction should take place in
isolation (that means no other transaction should run concurrently when there is a transaction already
running
 Isolation: For every pair of transactions, one transaction should start execution only when the other
finished execution.
 Durability: Once a transaction completes successfully, the changes it has made into the database should
be permanent even if there is a system failure. The recovery-management component of database
systems ensures the durability of transaction.
Types of constraints

 NOT NULL : NOT NULL constraint makes sure that a column does not hold NULL value
 UNIQUE : If a column has a unique constraint, it means that column cannot have duplicate values in a table.
 DEFAULT: The DEFAULT constraint provides a default value to a column when there is no value provided
while inserting a record into a table.
 CHECK: It ensures that the specified column must have the value satisfying the cond. Eg : ROLL_NO INT NOT
NULL CHECK(ROLL_NO >1000)
 Key Constraints – PRIMARY KEY, FOREIGN KEY
Primary key uniquely identifies each record in a table. It must have unique values and cannot contain nulls. In
the below example the ROLL_NO field is marked as primary key, that means the ROLL_NO field cannot have
duplicate and null values.
CREATE TABLE STUDENT(
ROLL_NO INT NOT NULL,
STU_NAME VARCHAR (35) NOT NULL UNIQUE,
STU_AGE INT NOT NULL,
STU_ADDRESS VARCHAR (35) UNIQUE,
PRIMARY KEY (ROLL_NO) );
Foreign key:
Foreign keys are the columns of a table that points to the primary key of another table. They act as a cross-
reference between tables.
Joining types
Inner Join: Inner join return rows when there is at least one match of rows between the tables.
Right Join: Right join return rows which are common between the tables and all rows of Right hand side table.
Simply, it returns all the rows from the right hand side table even though there are no matches in the left hand
side table.
Left Join: Left join return rows which are common between the tables and all rows of Left hand side table.
Simply, it returns all the rows from Left hand side table even though there are no matches in the RHS table.
Full Join: Full join return rows when there are matching rows in any one of the tables. This means, it returns all
the rows from the left hand side table and all the rows from the right hand side table.
What is normalization?
Normalization is the process of minimizing redundancy and dependency by organizing fields and table of a
database. The main aim of Normalization is to add, delete or modify field that can be made in a single table.
The normal forms can be divided into 4 forms, and they are explained below -.
 First Normal Form (1NF): This should remove all the duplicate columns from the table. Creation of tables for
the related data and identification of unique columns.
 Second Normal Form (2NF): Meeting all requirements of the first normal form. Placing the subsets of data in
separate tables and Creation of relationships between the tables using primary keys.
 Third Normal Form (3NF): This should meet all requirements of 2NF. Removing the columns which are not
dependent on primary key constraints.
 Fourth Normal Form (4NF): Meeting all the requirements of third normal form and it should not have
multivalued dependencies.
What is an Index? What are all the different types of indexes?
An index is performance tuning method of allowing faster retrieval of records from the table. This indexing
does not allow the field to have duplicate values if the column is unique indexed. Unique index can be applied
automatically when primary key is defined.
 Clustered Index: This type of index reorders the physical order of the table and search based on the key
values.Each table can have only one clustered index.
 Non Clustered Index: NonClustered Index does not alter the physical order of the table and maintains logical
order of data. Each table can have 999 non clustered indexes .
Eg:CREATE INDEX idx_age ON CUSTOMERS ( AGE );
What is a trigger? What are the types of Triggers?
A DB trigger is a code or programs that automatically execute with response to some event on a table or view
in a database. Mainly, trigger helps to maintain the integrity of the database.
Example: When a new student is added to the student database, new records should be created in the related
tables like Exam, Score and Attendance tables.
• Insert
• Delete
• Update
• Instead of
Difference between function and Procedure
A procedure does not have a return value, whereas a function has.
Example:
CREATE OR REPLACE PROCEDURE my_proc
(p_name IN VARCHAR2 := 'John') as begin ... end

CREATE OR REPLACE FUNCTION my_func


(p_name IN VARCHAR2 := 'John') return varchar2 as begin ... end
What is the difference between DELETE TRUNCATE and DROP commands?
DELETE command is used to remove rows from the table, and WHERE clause can be used for conditional set of
parameters. Commit and Rollback can be performed after delete statement.
TRUNCATE removes all rows from the table. Truncate operation cannot be rolled back.
Drop command is used to drop the table or keys like primary, foreign from a table.
Difference between WHERE and HAVING in SQL::
1) Apart from SELECT queries, you can use WHERE clause with UPDATE and DELETE clause but HAVING clause
can only be used with SELECT query. For example following query, which involve WHERE clause will work but
other which uses HAVING clause will not work :
update DEPARTMENT set DEPT_NAME="NewSales" WHERE DEPT_ID=1 ; // works fine
update DEPARTMENT set DEPT_NAME="NewSales" HAVING DEPT_ID=1 ; // Incorrect syntax near 'HAVING'.
2) WHERE clause is used for filtering rows and it applies on each and every row, while HAVING clause is used
to filter groups in SQL.
3) Syntax level difference between WHERE and HAVING clause is that, former is used before GROUP BY clause,
while later is used after GROUP BY clause.
4) When WHERE and HAVING clause are used together in a SELECT query with aggregate function,WHERE
clause is applied first on individual rows and only rows which pass the condition is included for creating
groups. Once group is created, HAVING clause is used to filter groups based upon those condition.
Self Join vs Equi Join
In the short major difference between Self Join and Equi Join in SQL is that Self Join requires only one table
while most of Equi join is condition used in join predicate. Since Equi Join is based on the condition for
comparison, it can occur in any INNER, OUTER or SELF join in SQL.Self Join is one of the important technique
to solve many SQL query related problem where two columns of the table contain the same type of data e.g.
here emp_id and dept_id are essentially same data.
What is the difference between JOIN and UNION?
Join can be done with tables related through a common column where as Union needs tables to have similar
datasets .
What is the difference among UNION, MINUS and INTERSECT?
UNION combines the results from 2 tables and eliminates duplicate records from the result set.
MINUS operator when used between 2 tables, gives us all the rows from the first table except the rows which
are present in the second table.
INTERSECT operator returns us only the matching or common rows between 2 result sets
What is the difference between UNION and UNION ALL ?
Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables and combines.
A UNION statement effectively does a SELECT DISTINCT on the results set(means removes duplicate)
What is Self Join and why is it required?
Self Join is the act of joining one table with itself. Self Join is often very useful to convert a hierarchical
structure into a flat structure
What is a view?
Views are virtual tables. Unlike tables that contain data, views simply contain queries that dynamically retrieve
data when used.
What is a materialized view?
Materialized views is also a view but are disk based. Materialized views get updated on specific duration, base
upon the interval specified in the query definition. We can index materialized view.
What is an IDENTITY column in insert statements?
IDENTITY column is used in table columns to make that column as Auto incremental number or a surrogate
key. Auto increment keyword allows the user to create a unique number to be generated when a new record
is inserted into the table. AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be
used in SQL SERVER
What is Datawarehouse?
Datawarehouse is a central repository of data from multiple sources of information. Those data are
consolidated, transformed and made available for the mining and online processing. Warehouse data have a
subset of data called Data Marts
What are aggregate and scalar functions?
Aggregate functions are used to evaluate mathematical calculation and return single values. This can be
calculated from the columns in a table. Scalar functions return a single value based on the input value.
Example -Aggregate – max(), count – Calculated with respect to numeric.
Scalar – UCASE(), NOW() – Calculated with respect to strings
What is the purpose of FLOOR function?
FLOOR function is used to round up a non-integer value to the previous least integer. Example is given
FLOOR(6.7) Returns 6
What is referential integrity?
Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e.
every foreign key value must have a corresponding primary key value.
Probable Queries:
 Create new table from an existing table (only structure)

OR :: Select * from Student into <Student2> where 1=2 ;


 Nth highest Salary:: Oracle
SELECT name, salary FROM #Employee e1 WHERE N-1 = (SELECT COUNT(DISTINCT
salary) FROM #Employee e2 WHERE e2.salary > e1.salary)
 Nth highest Salary:: SQL Server
SELECT TOP 1 salary FROM ( SELECT DISTINCT TOP N salary FROM #Employee ORDER
BY salary DESC ) AS temp ORDER BY salary
 To fetch ALTERNATE records from a table. ﴾EVEN NUMBERED﴿
select * from emp where rowid in ﴾select decode﴾mod﴾rownum,2﴿,0,rowid, null﴿ from emp﴿
 To select ALTERNATE records from a table. ﴾ODD NUMBERED﴿
select * from emp where rowid in ﴾select decode﴾mod﴾rownum,2﴿,0,null ,rowid﴿ from emp﴿;
 Find the 3rd MAX salary in the emp table.
select distinct sal from emp e1 where 3 = ﴾select count﴾distinct sal﴿ from emp e2 where
e1.sal <= e2.sal﴿;
 Find the 3rd MIN salary in the emp table.
select distinct sal from emp e1 where 3 = ﴾select count﴾distinct sal﴿ from emp e2where
e1.sal >= e2.sal﴿;
 Select FIRST n records from a table.
select * from emp where rownum <= &n;
 Select LAST n records from a table
select * from emp minus select * from emp where rownum <= ﴾select count﴾*﴿ ‐ &n from emp﴿;
 List dept no., Dept name for all the dept in which there are no employees
select * from dept where deptno not in ﴾select deptno from emp﴿;
alternate solution: select * from dept a where not exists ﴾select * from emp b where
a.deptno = b.deptno﴿;
 How to get nth max salaries ?
select distinct hiredate from emp a where &n = ﴾select count﴾distinct sal﴿ from emp b
where a.sal >= b.sal﴿;
 Select DISTINCT RECORDS from emp table.
select * from emp a where rowid = ﴾select max﴾rowid﴿ from emp b where a.empno=b.empno﴿;
 How to delete duplicate rows in a table?
delete from emp a where rowid != ﴾select max﴾rowid﴿ from emp b where a.empno=b.empno﴿;
 Count of number of employees in department wise.
select count﴾EMPNO﴿, b.deptno, dname from emp a, dept b where a.deptno﴾+﴿=b.deptno
group by b.deptno,dname;
 Select all record from emp where job not in SALESMAN or CLERK.
select * from emp where job not in ﴾'SALESMAN','CLERK'﴿;
 Select all records where ename starts with ‘S’ and its lenth is 6 char.
select * from emp where ename like'S____';
 In emp table add comm+sal as total sal .
select ename,﴾sal+nvl﴾comm,0﴿﴿ as totalsal from emp;
 How can I create an empty table emp1 with same structure as emp?
Create table emp1 as select * from emp where 1=2;
 Select all records where dept no of both emp and dept table matches.
select * from emp where exists﴾select * from dept where emp.deptno=dept.deptno﴿
 If there are two tables emp1 and emp2, and both have common record. How can I
fetch all the recods but common records only once?
﴾Select * from emp﴿ Union ﴾Select * from emp1﴿
 How to fetch only common records from two tables emp and emp1?
﴾Select * from emp﴿ Intersect ﴾Select * from emp1﴿
 How can I retrive all records of emp1 those should not present in emp2?
﴾Select * from emp﴿ Minus ﴾Select * from emp1﴿
 Count the total sal deptno wise where more than 2 employees exist.
SELECT deptno, sum﴾sal﴿ As totalsal
FROM emp
GROUP BY deptno
HAVING COUNT﴾empno﴿ > 2
 delete duplicate records Oracle:
SQL > delete from emp where rowid not in (select max(rowid) from emp group by empno);
 SQL INSERT INTO SELECT Syntax:
INSERT INTO table2(column names) SELECT (column names) FROM table1;
Query to find duplicate rows in table?
Select * from Employee a where row_id != select max(row_id) for Employee b where
a.Employee_num=b.Employee_num;
What is the Query to fetch last record from the table?
Select * from Employee where Rowid= select max(Rowid) from Employee;
How to fetch all the records from Employee whose joining year is 2017?
Oracle:: select * from Employee where To_char(Joining_date,’YYYY’)=’2017′;
SQL Query to find Max Salary from each department.
SELECT DeptID, MAX(Salary) FROM Employee GROUP BY DeptID.
Write an SQL Query to find the year from date.
find Year from a Date in SQL Server: SELECT YEAR(GETDATE()) as "Year";
Write SQL Query to find duplicate rows in a database? and then write SQL query to delete them?
SELECT * FROM emp a WHERE rowid = (SELECT MAX(rowid) FROM EMP b WHERE a.empno=b.empno)
to Delete:
DELETE FROM emp a WHERE rowid != (SELECT MAX(rowid) FROM emp b WHERE a.empno=b.empno
There is a table which contains two column Student and Marks, you need to find all the students, whose
marks are greater than average marks i.e. list of above average students.
Answer: SELECT student, marks from table where marks > SELECT AVG(marks) from table)
How do you find all employees which are also manager? .
SELECT e.name, m.name FROM Employee e, Employee m WHERE e.mgr_id = m.emp_id;
SQL Query to find duplicate records wrt name in a table in MySQL
select name, count(name) from contacts group by name;
Three table JOIN syntax in SQL:
SELECT t1.col, t3.col FROM table1 join table2 ON table1.primarykey = table2.foreignkey
join table3 ON table2.primarykey = table3.foreignkey
Query to show Employee (names) who have a bigger salary than their manager.
SELECT e.EMPID,e.Salary,mgr.EMPID AS BossID,mgr.Salary AS BossSalary FROM emp e
INNER JOIN Emp mgr ON e.empID = mgr.empID AND mgr.Salary < e.Salary;
Customers Who Never placed an Order(Customers , Orders are 2 tables):
SELECT A.Name FROM Customers A WHERE A.Id NOT IN (SELECT B.CustomerId FROMs Orders B)
How to find name of all tables in SQL Server database
SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'
or you can use sys.tables to get all table names from selected database as shown in following SQL query
SELECT * FROM sys.tables
Employees who have the highest salary in their Department
SELECT a.emp_name, a.dept_id
FROM Employee a JOIN
(SELECT a.dept_id, MAX(salary) as max_salary
FROM Employee a JOIN Department b ON a.dept_id = b.dept_id
GROUP BY a.dept_id) b
ON a.salary = b.max_salary AND a.dept_id = b.dept_id;
Write an SQL query to list Departments that have less than 3 people in it?
This is a rather simple SQL query interview question to solve. You just need to know how to use the COUNT()
function and GROUP BY clause.
SELECT dept_id, COUNT(emp_name) as 'Number of Employee'
FROM Employee
GROUP BY dept_id
HAVING COUNT(emp_name) < 3;
Query for all Departments along with the number of people working there (leaving out empty departments)
SELECT b.dept_name, COUNT(a.dept_id) as 'Number of Employee' FROM Employee a FULL OUTER JOIN
Department b ON a.dept_id=b.dept_id GROUP BY b.dept_name;
Query for Employees that don't have a manager in the same department.
self-join for this.Here we compared the salary of employee and here we have compared their department.
SELECT a.emp_name FROM Employee a JOIN Employee b ON a.mngr_id = b.emp_id
WHERE a.dept_id != b.dept_id;
All Department along with the total salary there.
Here also you need to use OUTER JOIN instead of INNER join to include empty departments which should have
no salaries.
SELECT b.dept_name, SUM(a.salary) as 'Total Salary' FROM Employee a
FULL OUTER JOIN Department b ON a.dept_id = b.dept_id GROUP BY b.dept_name;
delete duplicate records Oracle:SQL > delete from empwhere rowid not in(select max(rowid) from emp group by empno);

SQL INSERT INTO SELECT Syntax(inserting columns from other table):

INSERT INTO table2(column names)SELECT (column names) FROM table1;

By: Ramnivas Purohit(ramnibas@hotmail.com)

Você também pode gostar