Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I would like to delete all tables sharing the same prefix ('supenh\_agk') from the same database, using one sql command/query. | To do this in *one* command you need dynamic SQL with `EXECUTE` in a [`DO`](https://www.postgresql.org/docs/current/sql-do.html) statement (or function):
```
DO
$do$
DECLARE
_tbl text;
BEGIN
FOR _tbl IN
SELECT quote_ident(table_schema) || '.'
|| quote_ident(table_name) -- escape identifier and sch... | Suppose the prefix is 'sales\_'
**Step 1:** Get all the table names with that prefix
```
SELECT table_name
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'sales_%';
```
**Step 2:** Click the "Download as CSV" button.
**Step 3:** Open the file in an editor and replace **"sales\_** with **,sales**
and **"** wit... | drop all tables sharing the same prefix in postgres | [
"",
"sql",
"postgresql",
"plpgsql",
"dynamic-sql",
""
] |
I have a table `ASSETS` that has a structure as it is shown below :
```
----------------------------------------------------
ID (PK) | DESCRIPTION | TYPE | Do- | Do+ | Dx- | Dx+
----------------------------------------------------
```
`TYPE` column has a *foreign key*, possible values are `SECURITY` or `CURRENCY` (i.... | Answer to your original question is to use an additional `CHECK` *constraint* like :
```
CREATE TABLE CURRENCIES (
...
CONSTRAINT c_asset_from CHECK(exists(select 1 from ASSETS a where a.id = from and a.type = 'CURRENCY'))
);
```
And similar constraion for `TO` field and in `SECURITIES` for `CURRENCY` field.
... | IMO technically the design could be criticized in two categories:
* Having a dual-purpose foreign key in Asset table called **`type`** ([Polymorphic
Association anti-pattern](https://stackoverflow.com/questions/22177776/foreign-key-column-mapped-to-multiple-primary-keys/22179608#22179608)).
That will violating... | Specify foreign key on one column and the value of another column | [
"",
"sql",
"database",
"database-design",
"schema",
"polymorphic-associations",
""
] |
i have query like following
```
select max(id), count(id)
from table
group by col1, col2
having count(col1)>1 and count(col2)>1;
```
which results output like below
```
**+---------+-----------+
| max(id) | count(id) |
+---------+-----------+
| 43 | 4 |
| 108 | 2 |
| 171 | 2 ... | As far as I know, MySQL does not allow select from same table in sub query for delete. You have to use temporary table.
```
create temporary table t as
select
max(id)
from payments_records
group by
policy_id,
ref_txn_no;
delete from payments_record
where id not in (select * from t);
drop temporary table t;... | The id should be unique. Therefore you can select the data rows to delete by the ids and you do not need grouping etc. The inner select returns multiple values, so you should use the IN statement.
The following code is expected to work, but it does not, because MySql cannot delete from the table nested in the where cl... | SQL : Delete from table where not max in group by | [
"",
"mysql",
"sql",
""
] |
I have the following data.
```
FullName
---------------
Ray,John
Daly,Raymond
```
I want to make a search using last name.
I tried this
```
SELECT FullName
FROM Names
WHERE UPPER(FullName) LIKE UPPER('%ray%')
```
This returns both the rows as there is a clear match.
However searching by first name was easier. I... | assuming the last name is the bit before the comma:
and you want lastnames containing the subscting 'ray'
```
SELECT FullName FROM Names WHERE UPPER(FullName) LIKE UPPER('%ray%,%')
```
if you want last name exactly 'ray' use
```
SELECT FullName FROM Names WHERE UPPER(FullName) LIKE UPPER('ray,%')
```
if your data... | ```
SELECT FullName FROM Names
WHERE UPPER(FullName) LIKE
UPPER('%ray%,%')
```
Just add the comma after the expression! | How to search by Last Name in a Full name in SQL? | [
"",
"sql",
""
] |
I need MySQL select query like
```
select wt_id,wt_name from work_type where cat_id=1,2,5..;
```
Is it possible? | You just have to use [**IN**](http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_in) operator
```
SELECT wt_id, wt_name
FROM work_type
WHERE cat_id IN (1,2,5..);
``` | Use IN operator ex.
```
... where cat_id IN (1,2,5..)
``` | Mysql select Query with multiple conditions of same column | [
"",
"mysql",
"sql",
"select",
"where-clause",
"in-operator",
""
] |
```
Select *
FROM Products as a
join ProductTags as b
on (a.ProductId = b.ProductId)
join Tags as c
on (b.TagId = c.TagId)
where c.TagName = 'FISH'
Select *
FROM Products as a
join ProductTags as b
on (a.ProductId = b.ProductId)
join Tags as c
on ( b.TagId = c.TagId)
where c.TagName = 'STEAK'
```
I know ther... | This is something called relational division, which I just brought up on [Meta](https://meta.stackoverflow.com/questions/281023/what-can-we-do-to-prevent-repeated-relational-division-questions) earlier today. You can use a subquery for this. The outer query will pull all rows that match 'Fish' and the inner query will ... | You just need an `IN` condition:
```
Select *
FROM Products as a
join ProductTags as b
on (a.ProductId = b.ProductId)
join Tags as c
on (b.TagId = c.TagId)
where c.TagName IN ('FISH', 'STEAK')
```
You can add as many literals as you like in the `IN` clause as long as they are comma separated.
**Edit per the upda... | How can I combine these two queries? (where in clause)? | [
"",
"sql",
"join",
""
] |
I'm trying to list some data in a table. The data comes from a database, I have 3 tables in my DB.
I'm trying to join those 3 three tables in a SQL-statement like this:
```
SELECT * FROM cases
LEFT JOIN users ON cases.fk_supporter = users.user_id
LEFT JOIN users ON cases.fk_creator = users.user_id
```
The `fk_suppor... | You need unique alias for same tables in the join
```
SELECT * FROM cases c
LEFT JOIN users u1 ON c.fk_supporter = u1.user_id
LEFT JOIN users u2 ON c.fk_creator = u2.user_id
``` | You just have to give **ALIAS** name to table
Try this:
```
SELECT *
FROM cases c
LEFT JOIN users u1 ON c.fk_supporter = u1.user_id
LEFT JOIN users u2 ON c.fk_creator = u2.user_id;
``` | Joining the same table twice | [
"",
"mysql",
"sql",
"select",
"join",
"alias",
""
] |
Why are these two SQL queries not equivalent? One uses a correlated subquery, the other uses group by. The first produces a little over 51000 rows from my database, the second nearly 66000. In both cases, I am simply trying to return all the parts meeting the stated condition, current revision only. A comparison of the... | Query 1 is returning each of the max ids and then those that have a pmodel of the type specified within your where clause.
Whereas query 2 is selecting all items with a pmodel of the type specified in your where clause and each of the max ids of that.
You may have data which isn't the max id which satisfies your wher... | There are two differences and the rest of the answers focus on one. The "easy" difference is that the `max()` in the `group by` is affected by the filter clause. The `max()` in the other query has no filter, and so it might return no rows (when `max(prev)` is on a row otherwise filtered out by the `where` conditions).
... | Why are queries these not equivalent? (correlated subquery vs. group by) | [
"",
"sql",
"sql-server",
""
] |
I am trying to execute sp as sub query and treat result set of sp as column of outer query . Some thing like this
`Select U.FirstName , (exec SomeSP ) as columnFromSP from User U`
Is this possible i searched alot but found nothing on google.
**Update**
I cannot use #temp table because i am trying to do without #tem... | If you are able to convert your USP to a table value UDF, you will be use the UDF in your FROM statement.
```
CREATE FUNCTION dbo.SomeUDF
(
-- Add the parameters for the function here
@param varchar(1000)
)
RETURNS TABLE
AS
RETURN
(
SELECT @param as Value
)
GO
SELECT
a.Value,
'B' as Value2 ... | Not possible, but you can work around it
* Create a temp table & insert the results of the procedure into
it
* Now join the User table with the temporary table and select the
columns you want from both tables
This assumes however, you have a joinable expression returned from the stored proc (one that you can ma... | Combine sp result in select as column | [
"",
"sql",
"sql-server",
"sql-server-2008",
"stored-procedures",
""
] |
I have a select that gives me this result:
```
- ID | System | Type1 | NID | Name_ | Type2__ | Date
- 24 | AA-Tool | PRIV | 816 | Name1 | IMPLICIT | 17.12.2014
- 24 | AA-Tool | PRIV | 816 | Name1 | EXPLICIT | 19.12.2014
- 24 | AA-Tool | PRIV | 816 | Name1 | EXPLICIT... | Try this:
```
SELECT a.ID, a.System, a.Type1, a.NID, a.Name_, a.Type2__, a.Date
FROM tableA a
INNER JOIN (SELECT a.ID, a.System, a.Type1, a.NID, a.Name_, MAX(a.Date) Date
FROM tableA a
GROUP BY a.ID, a.System, a.Type1, a.NID, a.Name_
) b ON a.ID = b.ID AND a.System = b.System AND
... | Another approach could be:
```
SELECT t.*
FROM(SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY id, system, type1, nid, name
ORDER BY date DESC) AS rn
FROM tabelA t
)
WHERE rn = 1
```
Maybe it will help you. | Oracle group part of row and get row with latest timestamp | [
"",
"sql",
"oracle",
"select",
"group-by",
"greatest-n-per-group",
""
] |
```
+---+------------+
|sid| discounts |
+---+------------+
| 1 | 10.00 |
| 2 | 20.00 |
2 | 20.00 |
+---+------------+
```
I need to get the sum of column discounts but if column sid has the same values just add one row to total not all.
So I need to say 30.00 and not 50.00
I tried something like ... | Your second query will work if you remove `single quuto betwwen sid`
```
SELECT SUM(discounts) FROM $table_name WHERE sid IN (SELECT DISTINCT sid FROM $table_name)
``` | ```
select sum(discounts) from (select discounts,sid from $table_name group by sid) t
``` | How do I sum distinct values? | [
"",
"mysql",
"sql",
""
] |
I'm trying to join two tables together as shown below, in the " \* " section, I'm having trouble doing the following,
Operation: want to select all columns on the left, and just wanna attach few relevant columns from the right table to the left table. Instead of writing all the columns like left\_table.column1, left\_... | Yes, add the table name before the `*` to select all columns of a table
```
SELECT nutrients.*, measures.colX
FROM nutrients
LEFT JOIN measures ON nutrients.name=measures.name
``` | You can select all column using `*` like following
```
SELECT nutrients.*,
measures.name,
measures.col2
FROM nutrients
LEFT JOIN measures ON nutrients.name=measures.name
``` | MySQL - Left Join, Select all columns left, few columns on the right tables, | [
"",
"mysql",
"sql",
"left-join",
""
] |
I would like to know the most `efficient` way of `removing` any `occurrence` of characters like `, ; / "` from a `varchar` column.
I have a function like this but it is incredibly slow. The table has about **20 million records**.
```
CREATE FUNCTION [dbo].[Udf_getcleanedstring] (@s VARCHAR(255))
returns VARCHAR(255)
... | Whichever method you use it is probably worth adding a
```
WHERE YourCol LIKE '%[/-;"]%'
```
Except if you suspect that a very large proportion of rows will in fact contain at least one of the characters that need to be stripped.
As you are using this in an `UPDATE` statement then simply adding the `WITH SCHEMABINDI... | I want to show the huge performance differences between the using with 2 types of USER DIFINED FUNCTIONS:
1. User TABLE function
2. User SCALAR function
See the test example :
```
use AdventureWorks2012
go
-- create table for the test
create table dbo.FindString (ColA int identity(1,1) not null primary key,ColB var... | Efficiently replacing many characters from a string | [
"",
"sql",
"sql-server",
""
] |
I am studying for SQL exam, and I came across this fact, regarding subqueries:
```
2. Main query and subquery can get data from different tables
```
When is a case when this feature would be useful? I find it difficult to imagine such a case. | Millions of situations call for finding information in different tables, it's the basis of relational data. Here's an example:
Find the emergency contact information for all students who are in a chemistry class:
```
SELECT Emergency_Name, Emergency_Phone
FROM tbl_StudentInfo
WHERE StudentID IN (SELECT b.StudentID
... | ```
SELECT * FROM tableA
WHERE id IN (SELECT id FROM tableB)
``` | Why would a SQL query need to be so complicated like this feature allows? | [
"",
"mysql",
"sql",
"subquery",
""
] |
Currently I'm working on a project where we just added the ability to have multiple values stored within a field. Previously, it stored a single value, but now it contains multiple. Below is an example of what I'm talking about.
Ex. A person's name is passed in (John Smith). Now the user can pass in multiple people's ... | Check the demo in fiddler link <http://sqlfiddle.com/#!3/390f8/11>
```
Create table test(name varchar(1000));
Insert into test values('AAA BBB; CCC DDD; eee fff');
CREATE FUNCTION SplitString
(
@Input NVARCHAR(MAX),
@Character CHAR(1)
)
RETURNS @Output TABLE (
Ite... | this might work.
```
drop table authors
GO
create table Authors (Author_ID int identity (1,1),name varchar (255), category varchar(255))
GO
insert into authors
(name,category)
select
'jane doe','nonfiction'
union
select
'Jules Verne; Mark Twain; O. Henry', 'fiction'
union
select
'John Smith; John Doe', 'nonfiction... | Dealing with splitting strings in SQL | [
"",
"sql",
"sql-server",
""
] |
I want to write a mysql query to fetch distinct product\_id where combination of attribute\_id column for the similar product\_id values to be displayed.
I tried this one:
`SELECT DISTINCT(product_id) FROM oc_product_attribute WHERE (attribute_id = 26 AND CAST(text AS UNSIGNED) >= '1') and (attribute_id = 29 AND text... | You need to do EXISTS()...
```
SELECT DISTINCT product_id
FROM oc_product_attribute t1
WHERE EXISTS(SELECT * FROM oc_product_attribute t2
WHERE t1.product_id=t2.product_id
AND attribute_id = 26 AND CAST(text AS UNSIGNED) >= '1'
)
AND EXISTS (SELECT * FROM oc_product_attribute t3
WHERE t1.product_id=t3.product... | You can use a subquery along with the `IN` operator to solve this. Think of it this way.
First, write a query that pulls all product\_ids that match the first requirement:
```
SELECT DISTINCT product_id
FROM oc_product_attribute
WHERE (attribute_id = 26 AND CAST(text AS UNSIGNED) >= '1');
```
Then, write a second qu... | mysql query to run query after grouping rows based on product_id | [
"",
"mysql",
"sql",
""
] |
I have a many-to-many relational schema with 3 tables: Users, Teams, and Teamuser.
Since a user can be on many teams and a team can have many users, teamuser is a table that joins users.id to teams.id.
I'd like to do a query that asks "With a given user ID, show me all of the teams in the teams table, with a calculat... | Run something like the following to get the Cartesian product and then do the correlated sub-select wrapped in a coalesce to indicate membership?
select u.username, t.teamname,
COALESCE((select 1 from teamusers itu where itu.teamid = t.teamid and itu.userid = u.userid), 0)
from users u, teams t
where u.username = 'fin... | Here how you can do it
```
select
t.id,
t.name,
case when x.userid is not null then 1 else 0 end as `member`
from teams t
left join (
select
tu.userid,
tu.teamid
from teamuser tu
left join users u on u.id = tu.userid
where u.id = 1 -- change the user id here which you are looking at
)x
on x.teamid = t.id
``` | SQL Query to return Yes/No Based on a Subquery with Many-Many Join | [
"",
"mysql",
"sql",
"join",
"subquery",
""
] |
How to select people like apple and banana both from the data below?
table: MyTable
```
persons | fruit
-----------------------------
P1 Apple
P1 Banana
P1 Mango
P2 Banana
P2 Apple
P3 Mango
P3 Apple
```
i.e in this case, P1, P2 should be the result.
... | ```
SELECT a.persons
FROM MyTable a JOIN MyTable b on a.persons=b.persons
WHERE a.fruit='Apple' and b.fruit='Banana'
``` | Try this:
```
SELECT persons
FROM MyTable
WHERE fruit IN ('Apple', 'Banana')
GROUP BY persons
HAVING COUNT(DISTINCT fruit) = 2;
``` | select persons who like apple and banana both | [
"",
"mysql",
"sql",
"select",
"group-by",
"having",
""
] |
Got two tables:
```
tblJumper
JumperID
JumperName
```
and
```
tblWidthScored
ScoreID
fkJumperID
fkScoredWidth
```
Tables related by `tblWidthScored.fkJumperID = tblJumper.JumperID`
Table Contains following data:
```
tblJumper
1 Tom
2 Jerry
3 Bugs
tblWidthScored
1 1 5,72m
2 2 6,13... | Although I think this is just a Join question and appropriate articles could be found on the web, I'll post one of the answers...
```
SELECT
J.JumperName,
S.Score
FROM tblJumper as J
INNER JOIN(
SELECT
fkJumperID,
Max(fkScoredWidth) as Score
FR... | you can try this query. for this type of query, you have to use Group BY Clause with Sub-query.
```
SELECT JumperName, innertblWidthScored
FROM tblJumper INNER JOIN(SELECT fkJumperID,
Max(fkScoredWidth) as innertblWidthScored
FROM tblWidthScored
GROUP BY fkJumperID) Wid... | Select records from joint tables | [
"",
"sql",
"select",
"distinct",
""
] |
I need to add 40 days to a column , which contains date in d-m-y format,
and insert result into new column . eg
```
$querydate="UPDATE services SET paymentdue_date=payment_date+30 DAY WHERE my condition ";
```
and i tried
```
$querydate="SELECT up_id=".$up_id.",DATE_ADD(payment_date,INTERVAL 30 DAY) AS paymentdue_... | I tried running this query and it worked for me , updated my column with new :)
```
$querydate="UPDATE up_services SET paymentdue_date=DATE_ADD(payment_date,INTERVAL 30 DAY) WHERE my condition ";
``` | correct query will be
```
$querydate="SELECT up_id,DATE_ADD(payment_date,INTERVAL 30 DAY) AS paymentdue_date FROM up_services where up_id='$up_id'";
```
you can't add compare in select like `up_id=".$up_id."` use where instead
if you want update query you can follow **@saharsh shah** answer | Adding days to date column and result in new column? | [
"",
"mysql",
"sql",
"date",
"select",
"dateadd",
""
] |
I have a database in Microsoft SQL Server where the table names look like **firstpart.secondpart**. For example, Accounts.BankTransactionBASE or CustomerService.SurveyCommentBASE. I don't think the entire name is the name of the table, because when I find the name of the tables in the database using sys.tables, it only... | Naming format in SQL Server is: `servername.databasename.schemaname.tablename`. Typically only the last two are needed; the database name and server name are generally omitted as unnecessary unless you're working across multiple databases and/or servers.
In your case, the firstpart is the schema name and the secondpar... | As the other answers here have already said, the part before the table name is the schema. A simple edit to your query will get it for you:
```
select schema_name(schema_id), * from sys.tables
``` | what's the part before the dot in the name of the table? | [
"",
"sql",
"sql-server",
""
] |
I have one table as below:
```
ID USER1 USER2
1 Q Y
2 W Y
3 R Y
4 T Y
5 XY Y
```
How I can check when USER2 column is ALL duplicate ? I'm using this code but It not working
```
$res = mysqli_query($conn, "SELECT COMLUMN FROM TABLE");
$result = arr... | Just do a:
```
SELECT COUNT(USER2) FROM tablename GROUP BY USER2
```
And see if it returns 1 record, or the first record value is equal to the total record count.
Here is an example:
```
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connecti... | suppose you are trying to find `USER2` column duplicate values, then try this query
```
SELECT tableName.*, COUNT(*) AS duplicate_count FROM tableName
GROUP BY USER2
HAVING duplicate_count > 1
```
this query return all duplicate `USER2` rows | How to check duplicate value in MySQL | [
"",
"mysql",
"sql",
"select",
"group-by",
"having",
""
] |
I have two tables:
**Product**
> productID, productName, productPrice
**Purchased**
> productID, creationDate
Query - return a list of `unique products` that were bought since `June 2nd` with `most expensive product` returned `first`
For this I wrote below query:
```
SELECT Product.productID,
Product.prod... | Try this:
```
SELECT p.productID, p.productName, p.productPrice, pp.creationDate
FROM Product p
LEFT JOIN Purchased pp ON p.productID = pp.productID
WHERE pp.creationDate > '2014-06-02'
ORDER BY p.productPrice DESC;
``` | And make it shorter using `alises`
```
SELECT pr.productID,
pr.productName,
pr.productPrice,
pu.creationDate
FROM Product pr
LEFT JOIN Purchased pu
ON pr.productID = pu.productID
WHERE pu.creationDate > 02 / 06 / 2014
ORDER BY pr.productPrice DESC
``` | SQL query with left join to get rows in decreasing order from a specific date | [
"",
"mysql",
"sql",
"sql-server",
"sqlite",
""
] |
I im trying to hide and just dysplay the values in Working\_On attribute if they are lower than 2. I have tried using WHERE clauses but without luck. I am pretty new to MySQL. Anybody a hand?
This is the table I am using:
```
mysql> SELECT*
FROM employee_project;
+------+-------+---------------+
| eNum | pC... | Below Query will help you
```
SELECT eNum, COUNT(pCOde) as Working_On
FROM employee_project
GROUP BY eNum;
HAVING COUNT(pCOde) < 2;
``` | To this:
```
SELECT eNum, COUNT(pCOde) as Working_On
FROM employee_project
GROUP BY eNum;
```
add this:
```
having count(pCode) < 2
```
after the group by clause. Some database engines will allow you to do this:
```
having working_on < 2
```
but I don't know if mySql is one of those. | Don't Show if Count<2 | [
"",
"mysql",
"sql",
""
] |
Why would adding columns to the select list and group by in query increase the number of rows returned? For instance, below is my basic query, but if I add columns, I get more rows returned. The more columns added, the more rows returned. It seems the where clause conditions should be the only thing controlling the row... | When you add a `WHERE` clause, it filters the set of rows which will be handed down next to the `GROUP BY`, so `WHERE` is applied *before* groups. The rows which will be grouped and on which aggregates like `SUM(),MAX(),MIN(),COUNT()` will be performed have already been limited to those matching the `WHERE` conditions ... | Adding a new group-by increases the number of results you see beacuase each `group by` partitions the data in another way.
If you are using only an aggregate function you only get a single row result, The more finely you group the data the more result rows you will see
The `where` clause controls the inputs to the gr... | Why does adding columns to group by increases rows returned | [
"",
"sql",
"sql-server",
""
] |
I have a query which returns the total # of tickets of assignees:
```
SELECT DISTINCT case
when ASSIGNEE LIKE '%e474728%' then 'Jason'
when ASSIGNEE LIKE '%e499653%' then 'Alexis'
when ASSIGNEE LIKE '%e509255%' then 'David'
when ASSIGNEE LIKE '%e533676%' then 'KC Lin'
when ASSIGNEE LIKE '%Desktop_S... | You are grouping by ASSIGNEE, not by the result of the case expression (rename is performed after group by). Also distinct is redundant, here's one way to do it without repeating the case in the group by clause:
```
SELECT ASSIGNEE, count(status)
FROM (
SELECT case when ASSIGNEE LIKE '%e474728%' then 'Jason'
... | Use a different name for the alias of the `case` to distinguish it from the original column name.
```
SELECT DISTINCT case
when ASSIGNEE LIKE '%e474728%' then 'Jason'
when ASSIGNEE LIKE '%e499653%' then 'Alexis'
when ASSIGNEE LIKE '%e509255%' then 'David'
when ASSIGNEE LIKE '%e533676%' then 'KC'
wh... | How to combine multiple results? | [
"",
"sql",
""
] |
I have two tables **Table A** and **Table B**
**Table A**
```
1. *id*
2. *name*
```
**Table B**
```
1. *A.id*
2. *datetime*
```
I want to select
```
1. *A.id*
2. *A.name*
3. *B.datetime*
```
Even if table B do not contains a row with *A.id* for specific day and it should replace that column with *NULL*
e.g
*Ta... | Use [**LEFT OUTER JOIN**](http://www.w3schools.com/sql/sql_join_left.asp) to get all the rows from `Left table` and one that does not have match will have `NULL` values in `Right table` columns
```
SELECT A.id,
A.name,
B.[datetime]
FROM tableA A
LEFT OUTER JOIN tableB B
ON A.... | ```
SELECT A.id, A.name, b.datetime
FROM A
LEFT Outer JOIN B on B.id = A.id
``` | Select using LEFT OUTER JOIN with condition | [
"",
"sql",
"sql-server",
""
] |
This is sample information from my database so full picture can be shown as to what I am needing to accomplish
```
Create Table #Information
(
salesID int,
storelocation varchar(100),
salespersonName varchar(100)
)
Insert Into #Information Values
(1, 'New York', 'Michael'),
(2, 'New York', 'Michael'),
(3,... | Make the total Count query as `Subquery` and divide it by `storelocation` group count
```
SELECT storelocation,
(SELECT CONVERT(DECIMAL(18, 4), Count(1))
FROM #Information) / Count(1)
FROM #Information
GROUP BY storelocation
``` | ```
CREATE TABLE #Information
(
salesID INT,
storelocation VARCHAR(100),
salespersonName VARCHAR(100)
)
INSERT INTO #Information
VALUES
(1, 'New York', 'Michael'),
(2, 'New York', 'Michael'),
(3, 'New York', 'Michael'),
(4, 'New York', 'Michael'),
(5, 'Texas', 'Richard'),
(6, 'Texas',... | Division In Query | [
"",
"sql",
"sql-server",
"sql-server-2008",
"select",
"group-by",
""
] |
I have two tables.
### common\_products
* id
* product
* owner\_uid
* backup\_uid
* manager\_uid
## ss\_users
* userID
* firstName
* lastName
* email
I want to get a name/email list of all the owners, backups and managers.
I am using the query below, but was wondering if there was a more efficient way to go about... | I suspect that this version might be faster:
```
select u.email, (u.firstName+ ' '+u.lastName) AS userFull, u.lastName
from ss_users u
where exists (select 1 from common_products cp where u.userID = cp.owner_uid) or
exists (select 1 from common_products cp where u.userID = cp.backup_uid) or
exists (select ... | Ensure there are indexes on common\_products's owner\_uid, backup\_uid, and manager\_uid fields as well as ss\_users's userID field and you could improve performance a bit further by including the columns needed on the index.
```
SELECT DISTINCT
user_owner.email [OwnerEmail],user_owner.firstName + ' ' + user_owner... | Optimizing SQL join single column with multiple columns in another table | [
"",
"sql",
"sql-server",
"performance",
""
] |
I don't understand why my sql is not running,
it pop out a window say
> "Your query does not include the specified expression `' SUM(SaleRecord.Number)*(product.Price'` as part of an aggregate function"
```
SELECT SUM(SaleRecord.Number)*(Product.Price) AS TotalIncome
FROM Product, SaleRecord
WHERE Product.ProductID=S... | You asked in my previous answer:
> "thank you, I just make some mistake, now it is working. And sorry to
> bother you more, I want to select the product who sell the most out,
> how can I do it, I try to add MAX(xxx) on it, and it don't work"
Now, I am by no means an expert, but there are two processes going on. Your... | `Product.Price` is not part of the aggregate. Presumably, you intend:
```
SELECT SUM(SaleRecord.Number * Product.Price) AS TotalIncome
FROM Product INNER JOIN
SaleRecord
ON Product.ProductID=SaleRecord.SaleProduct;
```
Note that I also fixed the archaic `join` syntax. | Your Query does not include the specified expression, how to fix it? | [
"",
"sql",
"ms-access",
""
] |
Let's say I have this table called `mytable`:
```
+-----+-----+-----------+
|ID | ID2 | product |
+-----+-----+-----------+
| 1 | 1 | product1 |
| 2 | 2 | product1 |
| 3 | 1 | product2 |
| 4 | 4 | product2 |
| 5 | 1 | product3 |
| 6 | 1 | product4 |
| 7 | 4 | product4 |
+-----+--... | Another query using conditional aggregation to select products and the id corresponding to id2=4 or id2=2
```
select coalesce(
max(case when id2=4 then id end),
max(case when id2=1 then id end)
) id,
product
from mytable
where id2 in (4,1)
group by product
```
<http://sqlfiddle.com/#!9/47050/1> | For this you can use `OR`. It should work in this case, because if you meet the first condition, you're satisfied. If you don't, you'll fall back on the second one. If you still don't meet it, then it won't be included. Try this:
```
SELECT DISTINCT product
FROM myTable
WHERE id2 = 4 OR id2 = 1;
```
**EDIT**
This do... | how to select one thing and if the condition is false then select something else | [
"",
"mysql",
"sql",
""
] |
I am having one table "Mark" which contains marks of different subjects. If marks fit into one particular range then I should pick up respective rank and insert into marks table itself in column 'rank\_sub\_1'. could you please help me how can I look up in the table and insert in the column. Below is my table structure... | (Considering there is no overlapping in range values)
Take two instances of lookuptable and join first with subject1\_marks and second with subject2\_marks. Here i haven't used LEFT JOINS as i am assuming your subject marks will fall under 1 range for sure. If you are not sure about that, please use left joins and han... | I think this`update`statement should do what you want:
```
UPDATE Marks m
SET Rank_Sub_1 = (SELECT l.Rank
FROM LookupTable l
WHERE m.Subject1_Marks BETWEEN l.range1 AND l.range2)
WHERE EXISTS (
SELECT 1
FROM LookupTable l
WHERE m.Subject1_Marks BETWEEN l.range1 AND l.... | How to compare values with lookup table | [
"",
"sql",
"plsql",
""
] |
I have two tables:
tournament\_teams:
```
ID TEAM TournamentID
2 Berp 7
3 Dang 7
```
tournament\_pool\_team:
```
ID TournamentID PoolID TeamID VersusTeamID
1 7 5 2 3
```
Now this query should return nothing since all teams are in the pool (teamid and versusteamid)
```
SELECT t1.id,
... | ```
SELECT t1.id,
t1.team
FROM tournament_teams t1
WHERE t1.id NOT IN(SELECT t2.teamid
FROM tournament_pool_team t2
WHERE t2.teamid = t1.id
AND poolid = '5'
UNION
SELECT t2.versusteamid
... | Your sub query returns tournament\_pool\_team's `ID` which is not present in tournament\_teams `id` so you are getting wrong result.
Use `Not Exists` operator which will help you to find the tournament\_teams which is not present in tournament\_pool\_team's `TeamID` or `VersusTeamID`
```
SELECT t1.id,
t1.team
... | SQL (Mysql) NOT IN in combination with OR, wrong results | [
"",
"mysql",
"sql",
""
] |
```
select ROUND(5.8990,0) output is 6.000
select ROUND(643/109,0) output is 5
```
Why is this difference in output ? | It's due to use of integer division.
```
> select 643/109;
5
> select round(643/109, 0);
5.0
> select 643/109.0;
5.89908256880734
> select round(643/109.0, 0);
6.0
```
The first command shows that integer division is taking place. So, change the divisor or dividend to a float and you will get your expected result as ... | `select 643/109` gives `5` quotient . So `select ROUND(5,0)` is `5` | Why is this difference in output ? | [
"",
"sql",
"sql-server",
""
] |
I have two tables T1 and T2. I want to select all rows from T2 table where t1\_id not equal to any id in T1 table. This is not working:
```
SELECT t2.id, t2.t1_id, t2.data FROM T2.t2, T1.t1 WHERE t2.t1_id != t1.id
``` | You could use subquery with NOT IN clause as below:
```
SELECT t2.id, t2.t1_id, t2.data
FROM T2 t2
WHERE t2.t1_id NOT IN (SELECT DISTINCT id
FROM T1)
``` | Use **LEFT JOIN** to fetch all records from left table and add where condition with checking of null value of second table to find unmatched records of left table
Try this:
```
SELECT t2.id, t2.t1_id, t2.data
FROM T2.t2
LEFT OUTER JOIN T1.t1 ON t2.t1_id = t1.id
WHERE t1.id IS NULL
``` | Select SQL statement on related tables | [
"",
"mysql",
"sql",
"select",
"join",
"relational-database",
""
] |
I am using SQL 2012.
I have large Database Structure in my project.
I have around 10000 Stored Procedure in my Database.
I have to delete one table from the database, Is there any way that I can directly check that by deleteting my table how many stored procedure will affect.
Any help Will Be appriciated. | Using [sp\_depends](http://msdn.microsoft.com/en-us/library/ms189487.aspx):
```
EXEC sp_depends @objname = N'yourtablename'
``` | If you are using SQL Server Management Studio, you can right click table and select "View Dependencies" to view the dependent objects | How check that how many stored procedure will affect after deleting one table in SQL | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I'm trying to create an SQL query that only leaves "yahoo finance" and remove the others in following dataset. This dataset is a part of InnoDB table.
```
yahoo/finance
yahoo.finance
yahoo. finance
yahoo-finance
yahoo+finance
yahoo finance
yahoo .finance
yahoo . finance
yahoo - finance
yahoo + finance
```
I ... | Try this:
```
SELECT DISTINCT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(columnA, '/', ' '), '.', ' '), ',', ' '), '+', ' '), '-', ' '), ' ', ' '), ' ', ' ')
FROM tableA;
``` | You may want to consider using `LIKE` with a reg-ex pattern.
Perhaps a where clause something like:
```
... WHERE Field LIKE 'yahoo[. -+]finance'
```
<http://msdn.microsoft.com/en-us/library/ms179859.aspx> | SQL to remove duplicated records by ignoring non-letters and non-digits | [
"",
"mysql",
"sql",
"sql-server",
"select",
"replace",
""
] |
I have a column, call 'expected\_salary'. By the name, it suppose to be some numerical value. But I would like it to also hold value such as "competitive", "commission based" etc, so, it became a string type.
Now the dumb problem is, I would like to query it, like, `SELECT all rows where expected_salary >= 3000`. Of c... | Sure, create additional columns, probably booleans, which are false by default. `is_commissioned`, `is_competitive`, etc.
Then the proper query is
```
SELECT *
FROM table
WHERE expected_salary >= 3000 AND is_competitive
``` | A guess:
```
create table salaries (
expected_salary text
);
insert into salaries values ('1000'),('1500,comment'),('3000,comment'),('3500'),
('comment'),('4000'),('4500,comment');
```
you can use `substring()` function to extract `Integer` from a `string`
```
select... | Query a string column | [
"",
"sql",
"postgresql",
""
] |
I have two tables `tblData1` and `tblData2` and now I want to migrate records from another table with identity insert and I am trying to run a command as shown below
```
SET IDENTITY_INSERT LP1.dbo.tblData1 ON
GO
SET IDENTITY_INSERT LP1.dbo.tblData2 ON
GO
INSERT INTO LP1.DBO.tblData1 (ID,DATA)
SELECT ID,DATA FROM LP... | **At any time, only one table in a session can have the IDENTITY\_INSERT property set to ON.**
So before enabling the other one, you should turn of existing if any.
If it is lesser number of tables you can turn on and turn off before and after your operations.
If the table count is huge, you should automate someho... | Did you try changing the order
```
go
SET IDENTITY_INSERT LP1.dbo.tblData1 ON
INSERT INTO LP1.DBO.tblData1
(ID,DATA)
SELECT ID,DATA
FROM LP.DBO.tblData1
SET IDENTITY_INSERT LP1.dbo.tblData1 OFF
GO
SET IDENTITY_INSERT LP1.dbo.tblData2 ON
INSERT INTO LP1.DBO.tblData2
(ID,DATA)
SELECT ID,D... | How to SET IDENTITY_INSERT ON in SQL Server 2008 for multiple tables at once | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"sql-server-2008-r2",
""
] |
The Following is the schema
```
+---------+---------+
| Employee Table |
+---------+---------+
| EmpId | Name |
+---------+---------+
| 1 | John |
| 2 | Lisa |
| 3 | Mike |
| | |
+---------+---------+
+---------+-----------------+
| Family Table |
+----... | It looks like you are trying to assign the loans "sequentially" to rows in the family table. The approach to solve this is to first get the right rows, and then to get the loans assigned to rows.
The right rows (and first three columns) are:
```
select f.EmpId, e.Name, f.Relationship
from family f join
Employee ... | The approach outlined below allows to easily "concatenate" more tables to the result set. It is not limited to two tables.
I'll use table variables to illustrate the solution. In real life these tables would be real tables, of course, not variables, but I'll stick with variables to make this sample script easy to run ... | Concatenate more than two tables horizontally in SQL Server | [
"",
"sql",
"sql-server-2008",
"t-sql",
"outer-join",
""
] |
Is there a general rule of thumb or formula as to when it would be useful to use an index?
For example, in the following case, it would be obvious to add an INDEX on the `id` column:
```
SELECT * FROM table WHERE id = '1iuhiasdf89384h'
```
However, the following would probably not useful on `is_qualified` if it has ... | As a general rule of thumb, the reason the optimizer chooses to use an index in a `where` clause is to reduce the number of data pages being read. So, if your data is spread randomly over the pages, the important question is how many records are on each page and how many records is the filter selecting.
Say there are ... | I think you need to do some research and reading on using indexes. Even from your own example, you expect an index on the "id" column because you are looking for a specific ONE... But then its not important to have an index on IS\_QUALIFIED because it can have only 2 possible values... But the ID with alpha-numeric can... | When to use an index | [
"",
"mysql",
"sql",
""
] |
I've been trying for hours to make a left join query with MySQL.
I've a table called "at\_friends" where I store the relationships between users.
```
id | id_user1 | id_user2 | accepted
1 | 2 | 1 | 1
2 | 1 | 3 | 0
```
It means that user 1 is friend with user 2, and user ... | Try this:
```
SELECT u.id, u.name
FROM at_users u
INNER JOIN (SELECT id_user2 AS friendID FROM at_friends WHERE id_user1 = 1 AND accepted = 1
UNION
SELECT id_user1 AS friendID FROM at_friends WHERE id_user2 = 1 AND accepted = 1
) AS A ON u.id = A.friendID
``` | An alternative that only requires a single scan of the friends table:
```
SELECT u.id, u.name
FROM at_users u
JOIN at_friends f
ON 1 in (f.id_user1, f.id_user2) and
u.id = case f.id_user1 when 1 then id_user2 else id_user1 end and
f.accepted=1
```
[SQLFiddle here.](http://sqlfiddle.com/#!2/ae1acd/4) | Left Join query return bad results | [
"",
"mysql",
"sql",
"select",
"join",
"laravel",
""
] |
Here is my query however it is getting error
The error
> Msg 156, Level 15, State 1, Line 6
> Incorrect syntax near the keyword 'order'.
>
> Msg 156, Level 15, State 1, Line 13
> Incorrect syntax near the keyword 'order'.
>
> Msg 156, Level 15, State 1, Line 20
> Incorrect syntax near the keyword 'order'.
The ... | Copy the query results into `temp table` and use `Union all`
```
SELECT TOP 20 cl_RooSiteId,
cl_CrawlOrgUrl,cl_LastCrawlDate
INTO #Temp1
FROM tblCrawlUrls
WHERE Sysutcdatetime() > Dateadd(MINUTE, 50000, cl_LastCrawlDate)
AND cl_DuplicateUrl_ByCanonical = 0
AND cl_RooSiteId = 1
ORDER B... | Assuming that you want these in the order you have written them:
```
SELECT cl_RooSiteId, cl_CrawlOrgUrl
FROM ((SELECT TOP 20 cl_RooSiteId, cl_CrawlOrgUrl, cl_LastCrawlDate, 0 as priority
FROM tblCrawlUrls
WHERE Sysutcdatetime() > Dateadd(MINUTE, 50000, cl_LastCrawlDate) AND
cl_Duplicate... | How to use union all when using order by clause SQL Server 2014 | [
"",
"sql",
"sql-server",
"t-sql",
"union",
"sql-server-2014",
""
] |
I spent many hours combining my query into one. I have 3 database table. This is example schema.

I have only user name from session. I need take all tickets from database from user company.
Example:
User A working in company B.
Company B hav... | This should do it:
```
SELECT *
FROM User u1
INNER JOIN User u2 on u2.id_company = u1.id_company
INNER JOIN Ticket t on t.id_author = u2.id_user
WHERE u1.Name = @SessionUser
``` | Is this what you are looking for?
```
select t.*
from users u join
tickets t
on u.id_user = t.id_author
where u.company_id = (select u2.company_id from users u2 where u2.id_user = 'UserA');
``` | Combining 2 sql queries into one | [
"",
"mysql",
"sql",
""
] |
If I have a table such as:
```
memberid,time,ip
```
The his an ip history of all the ip's that have logged in and the associated account id they logged in with and their respective IP.
**Is there anyway with a single query that you can check if there are any IP's in the table that have logged into `> 1` account and ... | The question can be phrased as: "members that share the same ip". To determine that something like:
```
select ip
from T
group by ip
having count(distinct memberid) > 1
```
can be used. If you want the members that are associated with these ip's you can join the original table with that:
```
select distinct x.member... | You have an ip address say "192.0.100.1" of member "myuser" and you want to check what all member that logged nto the system with same and check if other members who logged in using the same ip, then you could use where clause as below:
```
SELECT DISTINCT memberid
FROM iphistory
WHERE ip = "192.0.100.1"
AND memberi... | Get accounts that have looged in with the same ip within ip loging table | [
"",
"mysql",
"sql",
""
] |
I need to update multiple rows in the table on the basis of Ids. In the stored procedure, I'm creating a varchar variable that holds the Ids list.
Now, in the table I have entries with Ids 1, 2. The varchar variable has value `1,2`; so I'm expecting no row to be updated with following query.
```
UPDATE mytbl
SET flag... | Try this:
```
UPDATE mytbl
SET flag = 1
WHERE @IdList LIKE CONCAT('%,',Id,',%');
```
Note that your varchar list `@IdList` must start and end with comma (e.g. `,1,2,20,30,`). | just use the ids as integers like so:
```
UPDATE mytbl
SET flag = 1
WHERE id in (1,2,3,....)
``` | Updating multiple rows using list of Ids | [
"",
"mysql",
"sql",
""
] |
I have two tables from which I need to get data in the same `SELECT` output. The thing is that I need to limit the amount of results.
Say I have an `ID` column that is unique in `table1`, but in `table2` it has many rows with that `ID`.
Now I just want to list how many different `ID`s I have in `table1` and some othe... | Use a `JOIN` and `GROUP BY`:
```
SELECT t1.Id_thread, t2.Name, t1.Date
FROM t1
JOIN t2 ON t1.Id_thread = t2.Id_thread
GROUP BY t1.Id_thread
```
Note that if `Name` is the same for all rows in `t2` that have the same `Id_thread`, that column probably should be in `t1`. If you fix that, you don't need the `JOIN`. | I'd join and use `distinct`:
```
SELECT DISTINCT t1.id_thread, t2.name, t1.date
FROM t1
JOIN t2 ON t1.id_thred = t2.id_thread
``` | SQL SELECT from multiple tables or JOIN | [
"",
"mysql",
"sql",
"select",
"join",
"syntax",
""
] |
I have following table
```
Key ID Value
1 1 C
2 1 C
3 1 I
4 2 C
5 2 C
6 2 C
7 1 C
```
If the value of value column is I then want to update previous records of same `ID` to `I`.
For example `ID` 1 has last recod with value `I` so want to update first 2 records... | Try this (or the alternate below the Results):
```
SET NOCOUNT ON;
DECLARE @Data TABLE
(
[Key] INT NOT NULL,
[ID] INT NOT NULL,
[Value] VARCHAR(50) NOT NULL
);
INSERT INTO @Data VALUES (1, 1, 'C');
INSERT INTO @Data VALUES (2, 1, 'C');
INSERT INTO @Data VALUES (3, 1, 'I');
INSERT INTO @Data VALUES (4, 2, 'C');
... | This should work:
```
WITH CTE AS
(
SELECT *,
MAX([Key]) OVER(PARTITION BY ID) MaxKey
FROM dbo.YourTable
)
UPDATE A
SET Value = 'I'
FROM CTE A
WHERE EXISTS(SELECT 1 FROM CTE
WHERE [Key] = A.MaxKey
AND Value = 'I');
```
[**Here is a sqlfiddle**](http://sqlfiddle.com/#!3... | SQL Scanning table to update the value | [
"",
"sql",
"sql-server",
""
] |
I want to get the distinct `"SkillCategory"` and sort by `id`
here is the script below :
```
SELECT distinct EC.SKILL_CATEGORY from ETOPS_CHECK_FORM E
INNER JOIN EC_FORM_SKILL EC
ON EC.EC_FORM_ID=E.ID group by EC.SKILL_CATEGORY ORDER BY EC.ID
```
what i'm doing wrong? | The problem is that you need to decide *which* id to sort by. Remove the `distinct` and then use an aggregation function in the `order by`:
```
SELECT EC.SKILL_CATEGORY
FROM ETOPS_CHECK_FORM E INNER JOIN
EC_FORM_SKILL EC
ON EC.EC_FORM_ID = E.ID
GROUP BY EC.SKILL_CATEGORY
ORDER BY MIN(EC.ID);
``` | If you only want distinct records with no use of aggregate functions then use **DISTINCT** keyword instead of **GROUP BY**
Try this:
```
SELECT DISTINCT EC.SKILL_CATEGORY
FROM ETOPS_CHECK_FORM E
INNER JOIN EC_FORM_SKILL EC ON EC.EC_FORM_ID = E.ID
ORDER BY EC.ID;
``` | ORA-01791-Distinct and order by | [
"",
"sql",
"oracle",
"group-by",
"sql-order-by",
"distinct",
""
] |
Imagine the following 3 tables:
train: key, name, departure\_date
group\_train: train, group
group: key, name
The group\_train.train as a foreign key relation with train.key and group\_train.group with group.key.
A group can contain multiple trains and a train might be present in multiple groups.
I would like t... | Analytical function Approach;
```
SELECT train.*
FROM
(
SELECT T.KEY,
T.NAME AS TRAIN_NAME,
T.departure_date,
G.name AS GROUP_NAME,
RANK() OVER (PARTITION BY G.group ORDER BY T.departure_date DESC) AS MY_RANK
FROM GROUP_TRAIN GT
INNER JOIN TRAIN T ON ... | Try this:
```
SELECT g.key, g.name, t.key, t.name, t.departure_date
FROM group g
INNER JOIN group_train gt ON g.key = gt.group
INNER JOIN train t ON gt.train = t.key
INNER JOIN (SELECT gt.group, MAX(t.departure_date) AS departure_date
FROM group_train gt
INNER JOIN train t ON gt.train = t.na... | unable to retrieve the latest row based on a date | [
"",
"sql",
"database",
"oracle",
"group-by",
"greatest-n-per-group",
""
] |
How would do the following in SQL:
"select all emps with list mark all one's tasks".................................
```
EmpId EmpName
------ --------
1 tom
2 jerry
3 jack
taskId EmpID mark
------ ----- ------
1 1 5
2 3 0
3 1 10
4 2 5
5 ... | Try this:
```
SELECT e.EmpId, e.EmpName,
SUM(CASE WHEN t.mark = 0 THEN 1 ELSE 0 END) AS 0Mark,
SUM(CASE WHEN t.mark = 5 THEN 1 ELSE 0 END) AS 5Mark,
SUM(CASE WHEN t.mark = 10 THEN 1 ELSE 0 END) AS 10Mark,
COUNT(1) AS TotalMark
FROM employee e
INNER JOIN task t ON e.EmpId = t.EmpId
GRO... | ```
select
e.empname,
(select count(*) from tasks t where e.empid=t.empid and mark=0) as mark0,
(select count(*) from tasks t where e.empid=t.empid and mark=5) as mark5,
(select count(*) from tasks t where e.empid=t.empid and mark=10) as mark10,
(select count(*) from tasks t where e.empid=t.empid) as mar... | SELECT employees with count of finished tasks | [
"",
"sql",
"select",
"group-by",
"sum",
"pivot",
""
] |
I have a table in oracle database where a column ONSITE\_MANAGER has data like
```
ONSITE_MANAGER
--------------
jhon
'bikram'
'hari'singh
"'vijay'kumar"
kumar
```
to select a particular data with matching records i am using following select query
```
SELECT *
from (
Select M.*, Rownum R
From IMDB1_FINAN... | Use the [new quoting method](http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/fundamentals.htm#sthref336) from ora10g onwards
> You choose a character that is not present in the string, and then do
> not need to escape other single quotation marks inside the literal
So your query would be
```
SELECT * from (Se... | I think you have syntax error in the query:
Try following:
```
SELECT * from (Select M.*, Rownum R From IMDB1_FINANCE_ACTUAL M) where r > 0 and r <= 10 AND ONSITE_MANAGER='bikram'
``` | select query with where condition in oracle 10g giving ORA-00933: SQL command not properly ended | [
"",
"sql",
"oracle",
"jdbc",
""
] |
I've got the tables
```
person
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
... | Your `id` field is `auto_increment`, so you can just leave it out of the query and it will automatically set the row to the next value. Also, since `col2` has a default value of `NULL`, it too can be left out of the query. It will be set to its default automatically.
```
INSERT INTO chatroom (col1) SELECT id FROM pers... | Because your `chatroom` table has `id` column as auto-incremant so there is no need to pass value for this column. This column have automatic value when new row inserted in table. So no need of `DEFAULT`.
Second, `col2` will accept the `null` as per your table definition, so there is also no need to pass value for thi... | INSERT INTO with SELECT and some DEFAULT values | [
"",
"mysql",
"sql",
""
] |
This query runs on an `invoices` table to help me decide who I need to pay
Here's the base table:
The **users** table
```
+---------+--------+
| user_id | name |
+---------+--------+
| 1 | Peter |
| 2 | Lois |
| 3 | Stewie |
+---------+--------+
```
The **invoices** table:
```
+------------+... | Use **HAVING** clause instead of **SUM** in **WHERE** condition
Try this:
```
SELECT u.user_id, u.name, i.currency, SUM(i.amount) invoiceAmount
FROM mydb.users u
INNER JOIN mydb.invoices i ON u.user_id = i.user_id
WHERE i.is_paid = 0
GROUP BY u.user_id, i.currency
HAVING SUM(i.amount) >= (CASE i.currency WHEN 'usd... | You can't use `SUM` in a `WHERE`. Use `HAVING` instead. | Mind numbing SQL madness | [
"",
"mysql",
"sql",
"select",
"group-by",
"having",
""
] |
I want to be able to:
* extract specific words from *column1* in *Table1* - but only the words that are matched from *Table2* from a column called *word*,
* perform a(n individual) count of the number of words that have been found, and
* put this information into a permanent table with a format, that looks like:
**Fi... | You could work along the updated
```
WITH
Detail AS (
SELECT
W.id
, W.word
, T.extext
, (LEN(REPLACE(T.extext, ' ', ' ')) + 2
- LEN(REPLACE(' '
+ UPPER(REPLACE(REPLACE(REPLACE(REPLACE(T.extext, ' ', ' '), ':', ' '), '.', ' '), ',', ' '))
+ ' ', ' ' + UP... | From what I could understand, this might do the job. However, things will be more clear if you post the schema
```
create table final(
word varchar(100),
count integer
);
insert into final (word, count)
select column1, count(*)
from table1, table2
where table1.column1 = table2.words
group by column1;
``` | How to count words in specific column against matching words in another table | [
"",
"sql",
"sql-server",
"t-sql",
"count",
""
] |
As a follow up to [In SQL / MySQL, what is the difference between "ON" and "WHERE" in a join statement?](https://stackoverflow.com/questions/2722795/in-sql-mysql-what-is-the-difference-between-on-and-where-in-a-join-statem) and [SQL join: where clause vs. on clause](https://stackoverflow.com/questions/354070/sql-join-w... | Absolutely they are different.
The fisrt query will only have `t2` rows that satisfy `t2.col=val`
The second query will include all `t2` rows and only list `t3` when `t2.col=val` | The queries are not equivalent. It is easy to construct a counter example:
```
create table t1 (id int not null, val int not null);
create table t2 (id int not null, val int not null);
create table t3 (id int not null, val int not null);
insert into t1 (id, val) values (1,1);
insert into t2 (id, val) values (1,1);
ins... | MySQL placement of conditions in on-clauses of multiple outer joins | [
"",
"mysql",
"sql",
"join",
"left-join",
"on-clause",
""
] |
Is there any way to figure out when a SQL query will **end** after it starts? In other words, is there any way to figure out how much time a query will take before query execution? (*rough* estimate is fine!)
```
ALTER IGNORE TABLE mytbl ADD UNIQUE (c);
```
I ran this query on innodb table that has 35 million records... | Excerpt from the [ServerFault](http://www.serverfault.com/questions/346838/estimating-mysql-query-runtime) solution:
The solution was to measure how fast the query was scanning rows in the table scan of the fact table. This is shown by the Handler\_read\_rnd\_next status variable. Here’s an easy way to watch it (innot... | The big problem here is that the most important factor (by far) in determining how long a query will take has *nothing* to do with the query itself. Rather, the biggest factor in determining the answer is the load placed on the database while the query is running, especially including load from other queries. For compl... | How to figure out when a SQL query will end? | [
"",
"mysql",
"sql",
"database",
""
] |
I have two tables as below:
`ObjName` and `RptName` is a composite key.
**Table 1:**
```
ObjName | RptName | FileName | Success
----------------------------------------
obj1 | rept1 | file1.csv| NULL
```
Table 2:
```
FileName | Success
-------------------
file1.csv | 1
file1.csv | 0
file1.csv | 0
```
Tab... | Try this:
```
UPDATE a
SET a.Success = COALESCE(b.Success, 0)
FROM table1 a
LEFT OUTER JOIN table2 b ON a.FileName = b.FileName AND b.Success = 1;
``` | ```
update t1
set success =
case
when exists (select * from t2 where FileName = t1.FileName and Success = 1) then 1
else 0
end
``` | Updating a table using JOIN by calculating result from multiple rows | [
"",
"sql",
"sql-server",
"sql-server-2008",
"join",
"sql-update",
""
] |
When i write query like:
```
SELECT DISTINCT City FROM Customers;
```
It is returning all different cities in Customers table.
But when i write query like:
```
SELECT DISTINCT City,* FROM Customers;
```
It is returning all the rows in Customers table(with city column first and all columns including city later in t... | The DISTINCT keyword doesn't apply to a single column, it applies to the entire record. If the rows of your table are not identically valued for all columns, they are not distinct.
Let's assume there is some unique column in your customers table, ID. If you just want the latest customer ID per city, you could try:
``... | It would only display all the rows if each row was unique in the database. The `DISTINCT` keyword says "eliminate exact duplicates" in the output set. In your second query, you're selecting `City`, then via the `*`, all of the columns in the table. Say you had columns `City, State, Zip`, then `City, *` is the same as `... | Usage of Distinct key word, SQL | [
"",
"sql",
"distinct",
""
] |
I have a query:
```
SELECT case
when Submission__bTracking = 'Phone' then 'Phone'
when Submission__bTracking = 'Web' then 'Web'
when Submission__bTracking = 'Email' then 'Email
when Submission__bTracking = 'Live__bTech__bSupport' then '@ Live Tech Support
when Submission__bTracking = 'Verbal' then 'Verbal Request'
wh... | You can use UNION and just add one more row in your result set:
```
YOUR QUERY
UNION ALL
select 'ALL' as Sub_Tracking,
COUNT(Submission__bTracking) as tickets FROM dbo.MASTER30
WHERE mrSUBMITDATE >= (CONVERT (date, CURRENT_TIMESTAMP -1))
AND mrSUBMITDATE < (CONVERT (date, CURRENT_TIMESTAMP))
``` | You could do
```
...previous lines omitted
GROUP BY Submission__bTracking
UNION
SELECT 'ALL' as Sub_Tracking, count(Submission__bTracking) as tickets
FROM dbo.MASTER30
WHERE mrSUBMITDATE >= (CONVERT (date, CURRENT_TIMESTAMP -1))
AND mrSUBMITDATE < (CONVERT (date, CURRENT_TIMESTAMP))
``` | Get SUM of query result WITHIN same query | [
"",
"sql",
"sum",
""
] |
hey i'm new to the sql language
i have a relation `Movie(title, year, length, inColor, studioName, producerC#)`
the question is (Which movies are longer than Gone With the Wind?)
i want to know if there a difference between these two answers and which one is correct and why
```
select title
from movie
where length... | `length > ANY (<select>)` means that `length` needs to be higher than one (or more) of the values returned by the select. This select could return more than one value. Replacing it with `> (<select>)` is only possible if you know that select to be a singleton select (ie it produces only one row). | If you know that the title is unique, then use:
```
select title
from movie
where length > (select length from movie where title = 'gone with the wind');
```
The use of `any` is a bit misleading because it implies that there could be more than one match.
If there is more than one match, I would use:
```
select ti... | is using 'ANY' here necessary (sql) | [
"",
"sql",
""
] |
I am having trouble writing the following query in MySQL. I have a table called `pizz0r_pizza_ingredients` which looks something like this:
```
| id | pizza_id | ingredient | amount | measure |
+----+----------+------------+--------+---------+
| 6 | 1 | 15 | 3 | 4 |
|178 | 17 | 1 ... | I like to handle these problems using `group by` and `having`:
```
SELECT `pizza_id`
FROM `pizz0r_pizza_ingredients`
GROUP BY `pizza_id`
HAVING SUM(ingredient = 15) > 0 AND
SUM(ingredient = 20) = 0;
```
You can add as many new requirements as you like. The `SUM()` expression counts the number of ingredients ... | Try this:
```
SELECT P1.pizza_id
FROM pizz0r_pizza_ingredients P1
LEFT OUTER JOIN pizz0r_pizza_ingredients P2 ON P1.pizza_id = P2.pizza_id AND P2.ingredient IN (20, 21)
WHERE P1.ingredient = 15 AND P2.id IS NULL
GROUP bY P1.pizza_id;
``` | Multiple row conditions in WHERE clause | [
"",
"mysql",
"sql",
"join",
"group-by",
"relational-division",
""
] |
I have not used concatenation in SQL much and don't know how I would do this.
Say I have an Email column containing a few email addresses (varchar).
Then I have another column for LastLogin (datetime).
```
john@gmail.com
Frank@yahoo.com
Donny@apple.com
```
How would a query look for sorting firstly by the lastLogin ... | You can use `charindex()` and `substring()`:
```
order by lastLogin,
substring(email, charindex('@', email) + 1, len(email))
```
If you want the *date* component of the login:
```
order by cast(lastLogin as date),
substring(email, charindex('@', email) + 1, len(email))
``` | Assuming you're using MySQL, the following query should work for you:
```
SELECT * FROM YourTable ORDER BY lastLogin, SUBSTRING_INDEX(email, '@', -1);
```
You provide to SUBSTRING\_INDEX the name of the column, your delimiter and the number of occurrences of the delimiter as -1, in order to get everything on the left... | How can I order a query by the domains of email addresses? | [
"",
"sql",
"sql-server",
"sql-order-by",
"concatenation",
""
] |
Say I have two tables: table1 as follows
```
Name |Surname| col1
------------------------
Bob |Smith | BS1
Mary Jane|Jones | MJ1
```
and table2 as follows:
```
Name |Surname | col2
------------------------------
Bob |Keller Smith | BS2
Mary |Jones | MJ2
```
What I would like i... | Try this:
```
SELECT tableb.Name, tableb.Surname, tablea.col1, tableb.col2
FROM table1 as tablea
LEFT JOIN table2 as tableb
ON (tablea.Name LIKE '%' + tableb.Name + '%' OR tableb.Name LIKE '%' + tablea.Name + '%')
AND (tablea.Surname LIKE '%' + tableb.Surname + '%' OR tableb.Surname LIKE '%' + tablea.Surname +... | I think you want an `INNER JOIN`.
Also note that the percent signs are only recognized on the right hand side of the `LIKE` operator. Joining `Name` with `Surname` also doesn't seem right
```
SELECT
a.Name, b.Surname, a.col1, b.col2
FROM
table1 AS a
INNER JOIN table2 AS b ON
a.Name LIKE '%' + b.Name + '%... | SQL Join with wildcards | [
"",
"sql",
"join",
""
] |
I need help with the algorithms/ database design for my current working on web-based application (I apologize for the long question in advance)
**Application description:**
I am building a customer check-in station (it's basically just a monitor that displays a webpage and was connected to a scanner) where customers ... | Some rambling thoughts:
You could assign users a PIN and use that to make the account unique. Presumably to insure that it is unique you would have to assign it, you can't let them invent one. (You could let them invent one and then verify it's unique. That might be good to allow people to use numbers that have some m... | Have each customer tell you two "security question" style data: Location of birth, favorite dish, ... These can serve as uniquifiers.
You can then prevent duplicates from being entered because in case there is a colliding registration the customer must simply chose a different question. | Will First Name + Last Name + Date Of Birth combination be unique enough? | [
"",
"sql",
"asp.net",
"database",
"algorithm",
"database-design",
""
] |
I have 2 MySQL tables consisting of the following information:
**table1** (basic information)
```
name | url
a | www.a.com
b | www.b.com
c | www.c.com
```
**table2** (time series data)
```
name | status | date
a | ok | 22/12/14
b | ok | 22/12/14
c | ok | 22/12/14
a | ok | 21/12/... | That's a tricky one. What you can do is join the second table twice - one to find the "newest" lines and the second time to get the actual data.
```
SELECT t1.name, t1.url, t2.status, t2.date
FROM table1 t1
LEFT JOIN (SELECT name, max(date) as mx from table2 GROUP BY name) as X ON X.name = t1.name
LEFT JOIN table2 t2 ... | I specialize in such time-sensitive designs and here is what I do. Your second table is a `Versioned` table in that, like source control systems, when the data is changed, the old data remains, just a new copy is made with the date the change was made. A small change can add full bi-temporal functionality, but that's n... | Join one table with the most recent rows of another | [
"",
"mysql",
"sql",
"join",
""
] |
I'm trying to replicate a SQL database in Cassandra, but, while I had no problem creating the tables, I found that I cannot find an example easy to understand that shows how I can create foreign keys in Cassandra.
So, If I have this in SQL:
```
CREATE TABLE COOP_USUARIO (
CI VARCHAR2 (13 BYTE) NOT ... | Simple answer is: There is no CQL code for the same purpose.
CQL does not have a concept of foreign keys or any concept of constraints between tables in the same way that you can't do joins between tables.
If you need a constraint between tables then you would need to handle this in code. | "one table for each expected query). With that type of approach, there is no need for foreign key"
this seems a bit misleading. there are consistency risks with fully denormalizing in
Cassandra... best way to insure against consistency issues is doing statements in batches with an all or nothing commit using the apply... | How to create foreign key in Cassandra CQL | [
"",
"sql",
"cassandra",
"foreign-keys",
"foreign-key-relationship",
"cql",
""
] |
I need to calculate due date / end date for SLAs. As input values I have the start date and a timespan (in minutes). This calculation needs to take into account business hours, weekends, and holidays.
I've seen a lot of examples where the input is start date and end date, but have been struggling finding anything simi... | You need a table with valid business hours, with the weekends and holidays excluded (or marked as weekend/holiday so you can skip them.) Each row represents one day and the number of working hours for that day. Then you query the business hours table from your start date to the first (min) date where the sum(hours\*60)... | This is the best I could do, still uses a loop but uses date functions instead of incrementing a minutes variable. Hope you like it.
```
--set up our source data
declare @business_hours table
(
work_day varchar(10),
open_time varchar(8),
close_time varchar(8)
)
insert into @business_hours values ('M... | Calculating due date using business hours and holidays | [
"",
"sql",
"sql-server-2005",
""
] |
I would like to write a regexp\_like function which would identify if a string consists of two repeating characters. It would only identify a string that has alternating numbers and only consisting of two unique numbers, but the unique number cannot repeat, it must alternate.
**Requirement :**
Regular expression shou... | I think you want the following:
```
WITH t1 AS (
SELECT '787878787' AS str FROM dual
UNION
SELECT '787878788' AS str FROM dual
UNION
SELECT '7878787878' AS str FROM dual
UNION
SELECT '78' AS str FROM dual
)
SELECT * FROM t1
WHERE REGEXP_LIKE(str, '^(.)(.)(\1\2)*\1?$')
AND SUBSTR(str,... | You might do something like this -
```
SQL> WITH DATA AS(
2 SELECT '787878787' str FROM dual UNION ALL
3 SELECT '787878788' FROM dual
4 )
5 SELECT *
6 FROM DATA
7 WHERE REGEXP_LIKE(str, '(\d+?)\1')
8 AND SUBSTR(str, 1,1) = SUBSTR(str, -1, 1)
9 /
STR
---------
787878787
SQL>
```
Since you are... | Oracle RegExp_Like for Two Repeating Digits | [
"",
"sql",
"regex",
"oracle",
""
] |
I have a table with 20 columns. The first is my primary key. The remaining columns are attributes about the primary key. I need to evaluate each column on a row by row basis. If a attribute column has a value other than null, then do some further processing.
The way I am familiar with doing this in TSQL would be a whi... | You could unpivot the table and filter out things that are not NULL:
```
select pk, col, val
from (select pk, col, val
from table t
unpivot (val for col in (attr1, attr2, . . . )) as unpivot
) u
where val is not null;
```
This will provide a list of the columns and associated non-NULL values. Note: i... | I think the best approach would be to first define if any column actually has a null value. For that you could use something like the following;
```
Select DATALENGTH(null,'Attr1','Attr2') // Add all the colums. This will return null. All of the columns must be the same type.
```
This will return null. Let's say that... | TSQL Technique for attribute evaluation | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I want to get the maximum id from table with ought use of any function like max or else.I need simple pure query.Any one help me to solve this problem .
We simply write
```
select max(id) from table
```
but i don't want to use **max()** | Use `ORDER BY` and `LIMIT`
```
SELECT id
FROM table
ORDER BY id DESC
LIMIT 1
``` | **ORDER BY** with **LIMIT** will do the job for u just fine
```
SELECT id FROM table
ORDER BY id DESC LIMIT 1;
```
But as you asked the question from interview's point of view , they may even ask you to do the same without using **LIMIT** , **TOP** or ***max()*** .
In thay case you should go with *subquery* approa... | How to get Max of ID without use of MAX() | [
"",
"mysql",
"sql",
"select",
"sql-order-by",
"max",
""
] |
Given the following table structures:
```
countries: id, name
regions: id, country_id, name, population
cities: id, region_id, name
```
...and this query...
```
SELECT c.name AS country, COUNT(DISTINCT r.id) AS regions, COUNT(s.id) AS cities
FROM countries AS c
JOIN regions AS r ON r.country_id = c.id
JOIN cities AS... | First of all, the [other post](https://stackoverflow.com/q/2436284/244826) you reference is not the same situation. In that case, the joins are like [A -> B and A -> C], so the weighted average (which is what that calculation does) is correct. In your case the joins are like [A -> B -> C], so you need a different appro... | How about leaving the rest and just adding one more join for the population
```
SELECT c.name AS country,
COUNT(distinct r.id) AS regions,
COUNT(s.id) AS cities,
pop_regs.sum as total_population
FROM countries AS c
LEFT JOIN regions AS r ON r.country_id = c.id
LEFT JOIN cities AS s ON s.region_... | SUM For Distinct Rows | [
"",
"mysql",
"sql",
"select",
"group-by",
"sum",
""
] |
I have a requirement where I need to convert all SQL Server stored procedures into HANA stored procedures. I have come across a function ISNUMERIC in T-SQL and I am not getting the equivalent of it in HANA.
After searching the web, I found that HANA does not have built in ISNUMERIC equivalent function. Then I tried wr... | SAP HANA does not come with a `ISNUMERIC()` function.
However, this question had been asked and answered multiple times on SCN:
E.g. <http://scn.sap.com/thread/3449615>
or my approach from back in the days:
<http://scn.sap.com/thread/3638673>
```
drop function isnumeric;
create function isNumeric( IN checkString NVAR... | From SAP HANA 1.0 SPS12 you can use regular expressions in SQL. You can use `LIKE_REGEXPR` function to check if specific string contains letters i.e.:
```
SELECT
CASE WHEN '0001A' LIKE_REGEXPR '[A-Z]' THEN 0 ELSE 1 END
FROM
DUMMY;
``` | What is the equivalent of T-SQL ISNUMERIC function in HANA Sqlscript? | [
"",
"sql",
"sql-scripts",
"hana",
""
] |

How would I SELECT the USER\_ID where there is a value or "Retailer" and "Colorado". In other words, the query should result in 5. | You can use aggregation and a `having` clause:
```
select user_id
from table t
group by user_id
having sum(value = 'Retailer') > 0 and
sum(value = 'Colorado') > 0;
``` | You can try this
```
SELECT user_id
FROM table_name T
WHERE value IN ('Retailer','Colorado')
GROUP BY user_id
HAVING COUNT(user_id)>1
``` | SQL Select unique user_id from single table | [
"",
"mysql",
"sql",
""
] |
I have a table `hastags`
```
id|tweet_id| tag |time
1 1 hell
2 2 hellyeah
3 3 hell
4 4 stackoverflow
5 5 hell
6 6 hellyeah
7 7 bellrings
8 7 nomorehell
8 7 nomorehell
```
I want to select the count of *most used* `tags` above a *... | I chose `2014-12-29` as an example of a specific time
```
select tag,
sum(`time` > '2014-12-29') as sum_greater,
sum(`time` < '2014-12-29') as sum_smaller
from hashtags
group by tag
order by sum_greater desc, sum_smaller desc
limit 3
``` | ```
SELECT tag, count(*) as anz FROM hastags GROUP BY tag ORDER BY anz DESC
``` | Select distinct rows by count in descending order | [
"",
"mysql",
"sql",
"select",
"count",
"distinct",
""
] |
I use [this query](https://data.stackexchange.com/stackoverflow/query/201514/find-answers-to-flag) on SEDE. I have just been editing the `WHERE p.CreationDate > '2014-12-21T00:00:00.001'` like every week to select the last week's records only. So for example previous edits were just changing to 12-21 from 12-14 from 12... | To find `previous sunday` use this piece of code.
```
select DateAdd(dd, -1, DateAdd(wk, DateDiff(wk, 0, getdate()), 0)) [Previous Sunday]
```
`Where clause` should be something like.
```
Select ... from tablename
WHERE DATEDIFF(DAY, p.creationDate, DateAdd(dd, -1, DateAdd(wk, DateDiff(wk, 0, getdate()), 0))) <= 7
... | There are several solutions, similar to this.
Replace the GetDate in your where clause with some thing like
```
Cast(DateAdd(day,-DatePart(weekday,GetDate())+1,GetDate()) as Date)
```
where the +1 is adjusted larger or smaller to move to the specific day of the week you want to start with. The +1 causes this to beca... | How to write a query that selects last specific day and goes back 1 week from there? | [
"",
"sql",
"sede",
""
] |
I am writing a sp for getting the data for the next 6 months for a particular date field,
```
SELECT CR.[Id] AS ClaimId
,CR.[BOLNumber]
,CR.[PRONumber]
,CR.[ClaimNumber]
,CR.[CompanyName]
,c.NAME AS CarrierName
,CR.[DateFiled]
,CONVERT(VARCHAR(10),CR.[DateFiled], 103) AS DateFiledString
... | You can try
```
CONVERT(DATE, CR.ClaimDate) < DATEADD(MONTH,6,CONVERT(DATE, CR.ClaimDate))
```
only date is considered here. | Use [**BETWEEN**](http://msdn.microsoft.com/en-IN/library/ms187922.aspx) keyword to specify date range.
```
WHERE CR.CustomerId = @AccountUserId AND
CR.Status = @statusType AND
CR.ClaimDate BETWEEN GETDATE() AND DATEADD(month,6,CR.ClaimDate)
``` | Adding months in where clause in sql | [
"",
"sql",
"where-clause",
""
] |
I´m trying to fill the gaps after using group by using an aux table, can you help?
**aux table to deal with days with no orders**
```
date quantity
2014-01-01 0
2014-01-02 0
2014-01-03 0
2014-01-04 0
2014-01-05 0
2014-01-06 0
2014-01-07 0
```
**group by result from "orders" table**
```
date qua... | Without knowing how you create your `group by result` table, what you're looking for in an `outer join`, perhaps with `coalesce`. Something like this:
```
select distinct a.date, coalesce(b.quantity,0) quantity
from aux a
left join yourgroupbyresults b on a.date = b.date
```
Please note, you may or may not need ... | Using your results it would be something like:
```
SELECT a.date
,COALESCE(b.quantity,0) as quantity
FROM auxtable a
LEFT JOIN groupbyresult b
ON a.date = b.date
```
You can also do your grouping in the same query as the left join:
```
SELECT a.date
,COALESCE(COUNT(b.somefield),0) as quantity
FROM auxt... | MYSQL fill group by "gaps" | [
"",
"mysql",
"sql",
"group-by",
"left-join",
""
] |
I have a (MySQL) table that looks like this:
```
`radiostation_id` varchar(36) NOT NULL,
`song_id` varchar(36) NOT NULL,
`date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`length` int(4) NOT NULL
```
What I want to do is to find every same `song_id` that has been played within an interval of 15 minutes. It cou... | It seems to me that you want a song that is played within a certain 15 minutes regardless of the day. There are [date and time functions](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html) you can use to parse the information you want. For example, you can use `TIME()` to extract the time portion of y... | It's not entirely clear what you are asking.
If you want to find occurrences of the *same* `song_id`, where a second row with the same `song_id` has a date value within 15 minutes of the first row, one way to get that would be a query like this:
```
SELECT t.song_id
FROM looks_like_this t
WHERE EXISTS ( SELECT 1
... | Selecting multiple values within a timestamp interval | [
"",
"mysql",
"sql",
""
] |
I got result from query:
```
TITAL PCS RGH_CTS VALUE
----- --- ------- ------------
SEND 10 49.8550 198742.94400
BID 15 76.7070 327461.76300
FINAL 19 88.5630 337954.15600
```
I want this output - How to solve this?
```
| TITAL | SEND | BID | FINAL |
-------... | You need to Combine `Pivot` and `Unpivot` to get the result.
First `Unpivot` the table to get the data in single column using `Cross Apply`.
Next `Pivot` the result of previous step to get the result.
```
SELECT Tital,
[SEND],
[BID],
[FINAL]
FROM (SELECT t.TITAL AS tt,
c.TITAL,... | As per NoDisplayName, you'll need a do a full transpose, by first UNPIVOT ing, and then re-PIVOTing the data. You can also UNPIVOT data with the keyword with the same name:
```
SELECT Criteria as TITAL, [SEND], [BID], [FINAL]
FROM
(
SELECT
*
FROM
Result
UNPIVOT
(
SomeColumn
... | how to create pivot query for this result? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2005",
"pivot",
""
] |
Is there a way to split a string in HANA?
Something similar to the equivalent in SQL Server: `SELECT * FROM dbo.fnSplitString('valueA,valueB', ',')` | Try this,
[Refer Here](http://scn.sap.com/thread/3482620)
```
CREATE PROCEDURE SPLIT_TEST(TEXT nvarchar(100))
AS
BEGIN
declare _items nvarchar(100) ARRAY;
declare _text nvarchar(100);
declare _index integer;
_text := :TEXT;
_index := 1;
WHILE LOCATE(:_text,',') > 0 DO
_items[:_index] := SUBSTR_BEFORE(:... | Another way of splitting a string is with an outbound variable using table types:
```
CREATE TYPE UTIL_VARCHAR_LIST AS TABLE
(
VarcharValue Varchar(5000)
);
CREATE PROCEDURE UTIL_SPLIT_STRING
(
IN iv_split_string Varchar(5000),
IN iv_split_character Varchar(1) DEFAULT ',',
OUT ot_string_list UTIL_VARC... | HANA: Split string? | [
"",
"sql",
"hana",
""
] |
I've got two tables in MS Access that keep track of class facilitators and the classes they facilitate. The two tables are structured as follows:
tbl\_facilitators
```
facilID -> a unique autonumber to keep track of individual teachers
facilLname -> the Last name of the facilitator
facilFname -> the First name of the... | (The following applies when every row is SQL DISTINCT, and outside SQL code similarly treats NULL like just another value.)
Every base table has a statement template, aka *predicate*, parameterized by column names, by which we put a row in or leave it out. We can use a (standard predicate logic) shorthand for the pred... | I would do it as above by joining to the tbl\_facilitators table twice but you might want to make sure that every class really does require a 2nd facilitator as the second join should be an outer join instead. Indeed it might be safer to assume that it's not a required field. | How to get matching data from another SQL table for two different columns: Inner Join and/or Union? | [
"",
"sql",
"ms-access",
"inner-join",
"union",
"self-join",
""
] |
I have a fairly complex requirement I would like to solve using SQL in a Postgres DB. I'm sure this would be addressed in any order management system however I cannot find anything of a similar nature.
I have the following table (and values):
```
CREATE TABLE TABLE1 (
ID varchar(8),
ORIG_ID varchar(8),
... | ```
Delete from table1
WHERE status in ('FILLED','EXPIRED','REJECTED','CANCELLED')
OR (status in ('PARTIAL','NEW') AND validity not in ('GTD','GTC'))
OR (status = 'REPLACED' and orig_ID not in
(select ORig_ID from table1 where status in ('PARTIAL','NEW')));
```
<http://sqlfiddle.com/#!15/9e465/28/0> | what is your PostgreSQL version ?
anyways here is what I come up with
```
delete from TABLE1 where
STATUS in ('FILLED','EXPIRED','REJECTED','CANCELLED') or
STATUS in (select STATUS from TABLE1 where STATUS in ('PARTIAL','NEW')
and VALIDITY!='DAY') OR
STATUS in (select status from TABLE1 where STATUS ='REPL... | Deleting rows in a single database table based on the values of other rows | [
"",
"sql",
"postgresql",
"postgresql-9.3",
""
] |
I have a query below, I want it to sort the data by `id`, but it doesn't sort at all.
```
Select distinct ec.category,ec.id
from print ec
order by ec.id asc
```
What could be the reason?
this is the output :
 | Looking at your data, the column data type is a `varchar`, aka 'text'.
If it is text, it sorts like text, according to the place the character occurs in the character set used.
So each column is ordered on the first character, then the second, etc. So `2` comes after `11`.
Either make the column a numeric data type,... | The difference lies in the way `varchar` and `number` are sorted. in your case, since you have used `varchar` data type to store `number`, the sorting is done for the `ASCII` values.
**NUMBERS when sorted as STRING**
```
SQL> WITH DATA AS(
2 SELECT LEVEL rn FROM dual CONNECT BY LEVEL < = 11
3 )
4 SELECT rn, ... | why Order by does not sort? | [
"",
"sql",
"oracle",
""
] |
I have the following SQL statement that shows the total sales amount for customers in cities who have done at least 2 orders. But let say I only want to show the the city/cities where someone has done at least 2 orders, and that there are two customers living in this city/cities, so what I want to do is to pick out the... | Try using a subquery. I know this looks a bit nasty but must be working.
**Turns out that you have a duplicate Ordernr (1306) for the same CustomerNr in your Order1 example. I am assuming that this might not be the case in your real data.**
```
SELECT c.CityName,
(Select SUM(order2.quantity * products.Price) from or... | I have interpretted your question as " I need the sum of ALL sales by city, for any city where a single customer has placed more than one order."
```
select
c.City,
SUM(p.Price * o2.Orderquantity) AS 'TotalSalesAmount'
from
(select c.City
from @t_Customers c
inner join @t_Order1 o1
on o1.... | Total sales amount for customers in cities | [
"",
"sql",
"sql-server",
""
] |
I have a table like so:
```
id min max version data
1 1 10 1 a
2 11 20 1 b
3 21 30 1 c
4 1 10 2 a
5 11 20 2 b
6 21 30 2 c
```
min, max represent values of `key`. Eac... | You could take the first row ordered by ver desc...
```
select * from range_table where 5 between `min` and `max` order by ver desc limit 1;
``` | If you care about performance, then, depending on the size and/or selectivity of the columns, you can add an index to the min or max column. If the number of versions remain low for each min-max, then your query will be optimized. | Efficiently SELECT a DB row marked as "latest version" and while matching a given interval | [
"",
"mysql",
"sql",
"range-query",
""
] |
Here is the query I'm running to get the counts of each value, for each key of a given object:
```
SELECT key, value, COUNT(value)
FROM keyval kv
WHERE object_id = 123456
GROUP BY kv.key, kv.value
ORDER BY kv.key, kv.value;
```
The table I'm querying off of is very simple. It's just:
```
object_id BIGINT
key V... | Try this but beware the situation where red and blue both have count of 26... both will be returned.
```
with cte as
(select k,v,count(v) c
from #kvp
group by k,v)
select results.*
from
cte restults
inner join (select k, max(c) m from cte group by k) filter
on restults.k = filter.k
where ... | I would use row\_number in a subquery or a cte:
```
select
[key],
value,
cnt
from (
select
[key],
value,
count(*) as cnt,
row_number() over(partition by [key] order by count(*) desc) rnk
from keyval
where object_id = 123456
group by
[key],
... | Is it possible to maximum occurences of a value for each key in my table all in one query? | [
"",
"sql",
"postgresql",
"amazon-redshift",
""
] |
So I have a simple table that holds `comments` from a `user` that pertain to a specific blog `post`.
```
id | user | post_id | comment
----------------------------------------------------------
0 | john@test.com | 1001 | great article
1 | bob@test.com | 1001 | nice post
2 | john@t... | You can use `GROUP BY` and `HAVING` to find pairs of `user` and `post_id` that have multiple entries:
```
SELECT a.*
FROM table_name a
JOIN (SELECT user, post_id
FROM table_name
GROUP BY user, post_id
HAVING COUNT(id) > 1
) b
ON a.user = b.user
AND a.post_id = b.post_id
``` | `DISTINCT` removes all duplicate rows, which is why you're getting unique rows.
You can try using a `CROSS JOIN` (available as of Hive 0.10 according to <https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Joins>):
```
SELECT mt.*
FROM MYTABLE mt
CROSS JOIN MYTABLE mt2
WHERE mt.user = mt2.user
AND mt.post... | SQL - find all instances where two columns are the same | [
"",
"sql",
"hive",
"hiveql",
""
] |
When I need to update a table through a stored procedure I use something like the following for this which usually works for me (using SQL Server 2012):
```
UPDATE LogTable
SET title = @title,
summary = @summary,
post = @post,
departmentID = @departmentID
WHERE postID = @postID
```
Howe... | ```
UPDATE A
SET title = b.title,
summary = b.summary,
post = b.post,
departmentID = b.departmentID
FROM LogTable A
JOIN (SELECT title=[Xml_Tab].[Cols].value('(title)[1]', 'nvarchar(100)'),
summary=[Xml_Tab].[Cols].value('(summary)[1]', 'nvarchar(500)'),
... | Try following query and check whether it is working or not:
```
UPDATE
LogTable
SET
title = Temp.Cols.value('@title','nvarchar(100)'),
summary = Temp.Cols.value('@summary', 'nvarchar(500)'),
post = Temp.Cols.value('@post', 'nvarchar(max)'),
departmentID = Temp.Cols.value('@departmentID', 'int')
F... | How to use XML input for Update / Set statement in SQL Server? | [
"",
"sql",
"sql-server",
"xml",
"stored-procedures",
"sql-update",
""
] |
I am having an issue while using `GetDate()`, for some reason is not returning the right time (it is 7 hours ahead from the actual time) I am using `AZURE` and the Database is configured with the right location (West US). I will appreciate any help!
I tried to run this script:
```
SELECT id,
status,
Acc... | Azure SQL Databases are always UTC, regardless of the data center. You'll want to handle time zone conversion at your application.
In this scenario, since you want to compare "now" to a data column, make sure `AcceptedDate` is also stored in UTC.
[Reference](http://blogs.msdn.com/b/cie/archive/2013/07/29/manage-timez... | The SQL databases on the `Azure` cloud are pegged against `Greenwich Mean Time(GMT) or Coordinated Universal Time(UTC)` however many applications are using `DateTime.Now` which is the time according to the regional settings specified on the host machine.
Sometimes this is not an issue when the DateTime is not used for... | SQL GetDate() returns wrong time | [
"",
"sql",
"azure-sql-database",
"getdate",
""
] |
I need help with a sql query.
I have these 2 tables:
`player_locations:`
```
ID | playerid | location <- unqiue key
---|-----------------------
1 | 1 | DOWNTOWN
```
and `users:`
```
ID | playername | [..]
----|--------------------
1 | example1 | ...
```
I need a select to get the `users.playernam... | This is just a simple `INNER JOIN`. The general syntax for a [**JOIN**](http://dev.mysql.com/doc/refman/5.0/en/join.html) is:
```
SELECT stuff
FROM table1
JOIN table2 ON table1.relatedColumn = table2.relatedColumn
```
In your case, you can relate the two tables using the `id` column from users and `playerid` column f... | Here is the solution.
```
SELECT
playername
FROM users
WHERE id = (SELECT id FROM player_locations WHERE location='DOWNTOWN')
``` | SQL SELECT name by id | [
"",
"mysql",
"sql",
"select",
"join",
""
] |
Having two issues at the moment:
1) The below example of wrapping an OS/400 API with an external SQL stored procedure which is further wrapper in a SQL user defined table function both compiles and runs without error, **but it returns blanks and zeroes for the job information when passing '\*' for the job name (i.e. c... | I use this on i 6.1 to call the QDBRTVFD API:
```
CREATE PROCEDURE SQLEXAMPLE.DBRTVFD (
INOUT FD CHAR(1024) ,
IN SZFD INTEGER ,
INOUT RTNFD CHAR(20) ,
IN FORMAT CHAR(8) ,
IN QF CHAR(20) ,
IN "RCDFMT" CHAR(10) ,
IN OVRPRC CHAR(1) ,
IN SYST... | Were you aware that IBM has already wrapped the Get Job Info API?
All Services by version / release
<https://www.ibm.com/developerworks/community/wikis/home?lang=en#!/wiki/IBM%20i%20Technology%20Updates/page/DB2%20for%20i%20-%20Services>
Get Job Info
<https://www.ibm.com/developerworks/community/wikis/home?lang=e... | Looking for a working example of any OS/400 API wrapped in an external SQL stored procedure wrapped in a user defined SQL function | [
"",
"sql",
"api",
"stored-procedures",
"db2",
"ibm-midrange",
""
] |
I am building a sql query with a large set of data but query is too slow
I've got 3 tables; `movies`, `movie_categories`, `skipped_movies`
The `movies` table is normalized and I am trying to query a movie based on a category while excluding ids from `skipped_movies` table.
However I am trying to use WHERE IN and WH... | Assuming that (movie\_id,category\_id) is unique in movies\_categories table, I'd get the specified result using join operations, rather than subqueries.
To exclude "skipped" movies, an anti-join pattern would suffice... that's a left outer join to find matching rows in skipped\_movies, and then a predicate in the WHE... | Most IN/NOT IN queries can be expressed using JOIN/LEFT JOIN, which usually gives the best performance.
Convert your query to use joins:
```
SELECT m.*
FROM movies m
JOIN movie_categories mc ON m.id = mc.movie_id AND mc.category_id = 1
LEFT JOIN skipped_movies sm ON m.id = sm.movie_id AND sm.user_id = 1
WHERE sm.movi... | Mysql very slow subquery optimizing | [
"",
"mysql",
"sql",
"database",
"performance",
"subquery",
""
] |
I would like to update the table using case statement the query is like this...
```
select case(@columnname) when 'name1' then
begin
update table
set
pay1=pay1* 100
... | You'll have to swap the syntax around. The case statement will be applied for every value you want to update...
```
UPDATE table SET
pay1 = CASE WHEN @columnname IN('name1') THEN pay1 * 100 ELSE pay1 END,
pay2 = CASE WHEN @columnname IN('name1', 'name2') THEN pay2 * 20 ELSE pay2 END,
pay3 = CASE WHEN @colu... | Use this.
```
update table
set pay1 = CASE WHEN @columnname = 'name1'
THEN pay1* 100
ELSE pay1
set pay2 = CASE WHEN @columnname = 'name1'
OR @columnname = 'name2'
... | updating multiple columns using case statement in sql server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2012",
"sql-update",
""
] |
I have below 2 tables:
**table1**
```
objName | rptName | srcTblName | srcFileName | srcDateColName
--------------------------------------------------------------
obj1 | rpt1 | srcTbl1 | srcFile1.csv| srcDate
```
**table2**
```
FileName | FileSize
------------------------
srcFile1.csv | 2009
```
The b... | The answers given by Hadi and Sarath seem to be working, But the cursor seems to affect the performance. So I did this using TEMP Table as below:
```
DECLARE @OBJECT_NAME VARCHAR(50) = 'ObjName'
BEGIN
DECLARE @Query NVARCHAR(1000),@COUNT INT, @MAX_Count INT, @rptName VARCHAR(255)
DECLARE @tblName varchar(100),@... | Since you have to execute tablename and datecolumn from a table, you have to use dynamic sql
```
SELECT * INTO tableN FROM
(
SELECT '01/JAN/2014' EntryDate
UNION ALL
SELECT '24/JAN/2014'
UNION ALL
SELECT '13/MAR/2014'
)TAB
SELECT * INTO tableO FROM
(
SELECT '11/APR/2014' Modified_Date
UNION ALL
SELECT '18/MAY/2014'
... | Finding max(date) from the resultant query output | [
"",
"sql",
"sql-server-2008",
"join",
"sqldatetime",
""
] |
In SQL Server I have a table `CustomerAddr` and a column named `Stnumber`. I have non-integer values that I want to delete. I would like to delete the rows of the non-integer values. I use this query that shows the results of the non-integer values:
```
Select *
From [CustomerAddr] [Stnumber]
Where ISNUMERIC ([Stnum... | try this
Before Deleting Confirms records using Select
```
select * From [CustomerAddr] Where ISNUMERIC ([Stnumber]) = 0
```
then use this
```
delete From [CustomerAddr] Where ISNUMERIC ([Stnumber]) = 0
``` | The where clause needs to be rewritten.
> WHERE ISNUMERIC StNumber = '0';
`ISNUMERIC` is a built-in function. `StNumber` is a column that you are comparing to '0'. These are not compatible.
You can write it like this:
```
WHERE ISNUMERIC (StNumber) <> 1;
```
If you meant non-number, then I would use the above.
Bu... | SQL Server delete multiple rows | [
"",
"sql",
"sql-server",
"database",
"sql-delete",
""
] |
I have this database Diagram :

the diagram is represent a database for Insurance Company.
the `final_cost` table represent the cost that the company should paid to repair a car
the table `car` has the field `car_type` which take one of the followi... | You can have access to anything and everything from a subquery if you use it right. The best way to build a complicated query is to start simply, seeing what data you have and usually the answer, or the next step, will be obvious.
So let's start by displaying all the accidents for 2013. We aren't interest in the indiv... | You could try either orderby or better yet, use the Max Function <http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions085.htm> | Retrieve records from multiple Records returned by Sub-Query | [
"",
"sql",
"oracle",
"oracle11g",
"group-by",
"sql-order-by",
""
] |
```
CREATE TABLE Prescription (
pre_id NUMBER(10),
pssn CHAR(11),
phy_ssn CHAR(11),
date CHAR(11),
quantity INTEGER,
trade name CHAR(20),
pharm id CHAR(11),
drop_off_time CHAR(10),
pick_up_time CHAR(10),
status CHAR (15),
PRIMARY KEY(pre_id),
FOREIGN KEY (pssn) REFEREN... | date CHAR(11)
Date is a reserved word in SQL. It cannot be declared as a column in the way you did.
Please change the column name and it will work. | If you execute the statement in `SQL*Plus`, you can easily find the error and fix it.
```
SQL> CREATE TABLE Prescription (
2 pre_id NUMBER(10),
3 pssn CHAR(11),
4 phy_ssn CHAR(11),
5 date CHAR(11),
6 quantity INTEGER,
7 trade name CHAR(20),
8 pharm id CHAR(11),
9 ... | Error while creating a table in oracle 11g | [
"",
"sql",
"oracle",
"create-table",
""
] |
I have three tables: `users`, `account` and `accountinfo` and I am trying to make a trigger that will add the id from users to the `UserID` column in the account table. Here is what I tried:
```
CREATE TRIGGER catchUser BEFORE INSERT ON defaultdatabase.users
FOR EACH ROW
BEGIN
INSERT INTO defaultdatabase.account(User... | You need to specify the delimiter:
```
delimiter //
CREATE TRIGGER catchUser BEFORE INSERT ON defaultdatabase.users
FOR EACH ROW
BEGIN
INSERT INTO defaultdatabase.account(UserID) VALUES (new.id);
END; //
delimiter ;
``` | Try this:
```
CREATE TRIGGER catchUser BEFORE INSERT ON defaultdatabase.users
FOR EACH ROW
BEGIN
INSERT INTO defaultdatabase.account(UserID) VALUES (new.id)
END;
``` | Using MySQL Database Triggers | [
"",
"mysql",
"sql",
"database",
"database-trigger",
""
] |
I need to return the unique records between two tables. Ideally, an UNION would solve my problem but both tables contain an object field which gives me an error(cannot ORDER objects without MAP or ORDER method) when I do UNION/distinct.
So, I was wondering if I can do a UNION ALL(to avoid the error) to get all the rec... | I actually solved the problem using analytic function+row\_num. The query will choose the first record for each set of duplicates hence returning only the unique records.
```
select * from
(
select ua.*,row_number() over (partition by p_id order by p_id ) row_num from
(
select * from table1
u... | How about this :
```
SELECT DISTINCT A.* FROM
(
Select * from Table1
union all
Select * from table2
) A;
```
(or)
```
SELECT col1,col2,col3...coln FROM
(
Select col1,col2,col3...coln from Table1
union all
Select col1,col2,col3...coln from table2
) A
GROUP BY A.col1,col2,col3...coln;
``` | How to return unique records between two tables without using distinct and union? | [
"",
"sql",
"oracle11g",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.