Showing posts with label sql. Show all posts
Showing posts with label sql. Show all posts

Saturday, August 2, 2014

Insert records from a table to other table


Note:   While inserting records from a table to other table  values clause must not be used

Example:
     
           insert into highAchiever (name, age)  (select name, age from salesperson where salary > 100000);

Friday, August 1, 2014

SQL JOINS

              You have following tables 



SalespersonCustomer
IDNameAgeSalary
1Abe61140000
2Bob3444000
5Chris3440000
7Dan4152000
8Ken57115000
11Joe3838000
IDNameCityIndustry Type
4SamsonicpleasantJ
6PanasungoaktownJ
7SamonyjacksonB
9OrangeJacksonB
Orders
Numberorder_datecust_idsalesperson_idAmount
108/2/9642540
201/30/99481800
307/14/9591460
401/29/98722400
502/3/9867600
603/2/9867720
705/6/9897150
Given the tables above, find the following:

a. The names of all salespeople that have an order with Samsonic. 
solution:
SELECT distinct name FROM `salesperson` WHERE id in(select salesperson_id from customer,orders where id=cust_id AND name='Samsonic');
if you write  above query like:

SELECT distinct name FROM `salesperson` WHERE id=(select salesperson_id from customer,orders where id=cust_id AND name='Samsonic');
It is invalid query because subquery returning multiple records so it can't be compared. 



Insert multiple rows in mysql

MySql  :)


insert into customer values(4,'Samsonic','pleasant','J'),
(6,'Panasung','oaktown','J'),
(7,'Samony','jackson','B'),
(9,'Orange','Jackson','B');

Insert into Multiple rows in single query: SQL

Method 1 - Traditional InsertINSERT INTO #SQLAuthority (IDValue)VALUES (1'First');INSERT INTO #SQLAuthority (IDValue)VALUES (2'Second');INSERT INTO #SQLAuthority (IDValue)VALUES (3'Third');

TRUNCATE TABLE #SQLAuthority;
Method 2: INSERT…SELECT
INSERT INTO #SQLAuthority (IDValue)
SELECT 1'First'UNION ALLSELECT 2'Second'UNION ALLSELECT 3'Third';

TRUNCATE TABLE #SQLAuthority;
Method 3: SQL Server 2008+ Row Construction
-- Method 3 - SQL Server 2008+ Row ConstructionINSERT INTO #SQLAuthority (IDValue)VALUES (1'First'), (2'Second'), (3'Third');