Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have this mysql syntax:
```
INSERT INTO `utilizatori`(
utilizator
)
SELECT
'Mama'
FROM
`utilizatori`
WHERE
NOT EXISTS (SELECT `utilizator` FROM `utilizatori` WHERE utilizator='Mama')
```
`utilizatori` is a table, `utilizator` is a column, `Mama` is a value
This syntax will insert a value in table only if... | I would make the task easier, clearer by making `utilizator` field `unique`.
That way when you add new rows with existing value `'Mama'` for `utilizator` in this case: mysql returns error with the code: `1062`, and don't let user have multiple rows with `Mama` in the table.
So when you run query:
```
INSERT INTO `ut... | Try to use group by :
```
INSERT INTO `utilizatori`(
utilizator
)
SELECT
'Mama'
FROM
`utilizatori`
WHERE
NOT EXISTS (SELECT `utilizator` FROM `utilizatori` WHERE utilizator='Mama')
group by utilizator
``` | Some problems with INSERT INTO statement | [
"",
"mysql",
"sql",
""
] |
SQL Server 2008 - I have a table with 10 columns and many rows in which i want to delete with a condition like delete all rows which are in particular column those are less than 75 characters (about 10 words) | The easiest solution is to use the SQL function called `len` used like this: `len(nameOffield)`
In your case simply add the function to you where clause in the delete command like this:
```
DELETE FROM yourTableName where len(aParticularColumn) < 75
```
Update to answer: if your `aParticularColumn` is of datatype `t... | As @ogixologist said...
```
DELETE FROM table_name where len (column_name) < 75
```
And here i did by using CTE check it out !!!!!!!!!
```
;with cte
as
(
SELECT column_name, temp = LEN ( CAST ( column_name As nvarchar(4000) ) ) from table_name
)
delete from cte where temp<=75;
```
* You can cast to... | How to delete rows which contain less than 75 characters (about 10 words) in a particular column | [
"",
"sql",
"database",
"sql-server-2008",
"sql-delete",
""
] |
I'm trying to implement a simple query that should look like this:
```
select * from property join entity_area on property.id=entity_area.entity_id and entity_area.area_id=1 where property.price>300000 limit 12
```
Pretty straightforward: I want to get the joined result and then to limit to 12.
In Sequelize i'm usin... | Actually I found a solution myself. I think this is a bug in sequelize framework.
In the node\_modules/sequelize/lib/dialect/abstract/query\_generator.js there is a "selectQuery" function which has the following line:
```
subQuery = limit && (options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiA... | ```
models.property.findAll(
{
where: [...],
include: [{...}],
limit:12
},
{
subQuery:false
})
``` | Sequelize with NodeJS can't join tables with limit | [
"",
"sql",
"node.js",
"sequelize.js",
""
] |
I am working on Hibernate query. This query works fine with MySQL but fails in Oracle and postgreSQL.
```
SELECT MIN(t.startTime) AS StartTime,
MAX(t.endTime) AS EndTime,
(SELECT SUM(t2.occurances) from table2 as t2)
from table1 as t1
```
And I am getting error-
> ORA-00937: not a single-group group function
How do... | Just add `GROUP BY` for third column:
```
SELECT MIN(t1.startTime) AS StartTime,
MAX(t1.endTime) AS EndTime,
(SELECT SUM(t2.occurances) FROM table2 t2) as occurances
FROM table1 t1
GROUP BY 3
```
This query returns one row.
**EDIT:**
Alternatively you can use additional aggregate function (for example `MAX`), t... | This works fine for MySQL because of MySQL extensions to the `group by`. Unfortunately, subqueries are not treated as "constant"s by the compiler when it looks at aggregation queries. So, this is just another expression not in the `group by` clause.
Here is a way to write the query that is compatible for all three dat... | Oracle ORA-00937: not a single-group group function in Subquery | [
"",
"sql",
"oracle",
"hibernate",
"oracle11g",
"oracle10g",
""
] |
I'm trying to display a start and end time for a SQL report. I always want to display the previous month period to look like:
> Start Time: Aug 1st 2014 00:00:00
>
> End Time: September 1st 2014 00:00:00
If the report was run in Oct it would give `Sept1-Oct1`. Not sure how to actually display that as a `Datetime` var... | In a `DATETIME` format, that would be
```
SELECT
DATEADD(month, DATEDIFF(month, 0, GETDATE())-1, 0) AS StartTime,
DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) AS EndTime
```
If you want to play around with character formats, you can do a bunch of things, like
```
SELECT
DATENAME(MONTH,StartTime) + ... | I apologize if i misunderstood but is this what you are looking for?
```
SELECT CAST(DATEADD(MONTH,-1,[date]) AS VARCHAR(12)) + '-' + CAST([date] AS VARCHAR(12)) FROM table
```
If you were to insert into your table a SMALLDATETIME such as
'2014-09-23 10:28:00'
then what would be produced is:
'Aug 23 2014 -Sep 23 2... | Displaying specific SQL Datetime | [
"",
"sql",
"datetime",
"sql-server-2005",
""
] |
I want to find Missing Numbers in a table..Table Like this.
```
Sno Branch
1 ABC
2 ABC
3 ABC
5 ABC // 4th sno is missing
6 ABC
8 ABC // 7th sno is missing
10 ... | You can use a CTE to build a table of all the branches and the full range of numbers for each. Then left join that to the main table to find what is missing. This will allow you to get consecutive missing numbers, e.g. 3, 4 and 5 missing. You can adjust `@minid` and `@maxid` to whatever you want your range to be. If `@... | Assuming that each branch has it's own set of sno numbers, this works:
```
select sno-1 as sno, branch
from t1
where sno-1 NOT in (select sno from t1 as t2 where t1.branch = t2.branch)
and sno > 1
;
```
Which you can check here: <http://sqlfiddle.com/#!3/daa81d/3>
If sno is a unique key, let me know and I will revis... | How to find Missing Numbers in a table using sqlserver? | [
"",
"sql",
"sql-server",
""
] |
I have a table with ip's and a view date and for websites with a website id
```
+------------+-----------+---------------------+
| website_id | ip | view_date |
+------------+-----------+---------------------+
| 123 | 123123123 | 2014-01-01 10:23:00 |
+------------+-----------+-----------------... | ```
select ip, sum(session) + 1 as session
from (
select
t.*,
if(@previp = ip and timestampdiff(minute, @prevview, view_date) >= 30, 1, 0) as session,
@previp := ip,
@prevview := view_date
from
Table1 t
, (select @prevview := (select view_date from Table1 order by ip, view_date limit 1),... | Here's my solution
I do a count to find out the number of rows for a given website id and ip address that occur between the date and the date -30 minutes. If its 0 assign a 1 meaning its a new session else give it a 0. Then do a sum.
**[SQL Fiddle Demo](http://sqlfiddle.com/#!2/51b21/3)**
```
select website_id,
... | Count the number of user sessions | [
"",
"mysql",
"sql",
""
] |
I have a table like this below and i need the result to be like this when i run the query
**Results**
```
title | count
----------------
foo | 3
bar | 2
```
**Table**
```
customer_id | title
-------------------
55 | foo
22 | foo
55 | bar <-- duplicate
23 | bar
55 | ... | The trick is to count the `distinct` customer ids, so you won't count the double Foo for customer 55.
If you need to, you can order the results by that count too, or you can just leave out the `order by` clause.
```
select
title,
count(DISTINCT customerid) as `count`
from
yourTable
group by
title
order by... | It's as easy as this:
```
select A.title, count(*) as count -- an usual count(*)
from
(select distinct customer_id, title -- this query removes the duplicates
from table) A
group by A.title -- an usual group by
``` | SQl - select columns and group them | [
"",
"sql",
""
] |
Hi i have a complicated condition. I have a table lets say **'Test'**
```
ID Partner Type Amount
143854 CSTC Purchase -0.81
144029 CSTC Purchase -0.69
144030 CSTC Purchase -1.33
144031 CSTC Purchase -0.47
144032 CSTC Purchase -1.8
149527 CSTC div 1574.48
14952... | Miller was close the left was breaking it
```
WITH TestWithRowNumber AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY ID ASC) AS RowNumber
FROM Test
)
Select *
From TestWithRownumber FirstRow
join TestWithRownumber secondrow
on secondrow.RowNumber = firstrow.RowNumber + 1
and secondrow.type = 'Pur... | please remember a table is a set and a set has no order neither top to bottom or left to right.What if someone inserts a row for type = div again ??. However try the below code to see if it is working or not
```
DECLARE @T TABLE (ID INT,[Partner] VARCHAR(10), [Type] VARCHAR(20),Amount decimal (10,2))
INSERT INTO @T
V... | Select complete next row based on the current row | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
Lets say I have a table with a column named KEY.
I want to find all KEYs which are in the table exactly 3 times.
How can I do that?
I managed to get a list of how many entries I have for each KEY, like this:
```
select count(*) from my_table group by KEY;
```
but how can I filter it to show only those who have the ... | ```
select KEY
from my_table
group by KEY
having count(*) = 3
``` | The `having` clause filters after grouping (`where` filters before).
```
select `key`
from my_table
group by `KEY`
having count(*) = 3;
``` | How can I filter an SQL table to show only keys with exactly N entries? | [
"",
"sql",
"select",
""
] |
From what I understand after reading the related SO answers and official docs, I may have a column type mismatch situation or absency of defining a required INDEX situation. However I couldn't solve my case.
Table below is being created successfully
```
CREATE TABLE `parts` (
`partnum_rev` varchar(255) COLLATE utf8_u... | The `foreign key` clause is wrong - your table is called `parts` (plural!), not `part`. Just use the correct table name:
```
FOREIGN KEY (`partnum_rev`) REFERENCES parts(`partnum_rev`) ON UPDATE CASCADE
``` | It looks like you have a typo where you missed an "s" in **parts**. Try the following line:
```
FOREIGN KEY (`partnum_rev`) REFERENCES parts(`partnum_rev`) ON UPDATE CASCADE
``` | MySQL 5.0.11 Error Code #1215: cannot add foreign key constraint | [
"",
"mysql",
"sql",
"foreign-keys",
"constraints",
""
] |
I currently have this `WHERE` clause that includes the following parameters.
```
WHERE
Project ID=110
AND ((CAST(saa.Date AS DATE) >= '09/24/2014' AND CAST(saa.Date AS DATE) <= '09/24/2014') OR saa.Date IS NULL))
```
The tricky part here is that the `saa.Date is NULL` section is going to pull up ALL `Null` V... | I'll base my answer in @AHiggins's but adding performance an readability
-- [sergability](https://stackoverflow.com/questions/799584/what-makes-a-sql-statement-sargable)
-- avoiding `cast`
-- [using `between`](http://msdn.microsoft.com/en-US/en-es/library/ms187922.aspx)
```
WHERE
ProjectID=110 AND
(
... | You do know that
```
>= '09/24/2014'
AND <= '09/24/2014'
```
is the same as
= '09/24/2014'
```
where ProjectID=110
AND CAST(saa.Date AS DATE) = '09/24/2014'
OR (
saa.Date IS NULL
AND
(
CAST(sa.StartDateTime AS DATE) = '09/24/2014'
OR
... | Using Case in a Where Clause for Dates | [
"",
"sql",
"t-sql",
""
] |
I'd appreciate if someone could help.
I have two tables that have no relationship:
Table\_1
```
ID NAME VALUE
1 abc 10
2 def 20
3 def 20
```
Table\_2
```
ID2 NAME2 VALUE2
5 ghi 30
6 gkl 40
```
I want to have a select statement that would show the data ... | You need to add a `join` condition. In this case, by using `row_number()` to add a sequential number on each side. Then `full outer join` to get all the records:
```
select t1.id, t1.name, t1.value, t2.id as id2, t2.name as name2, t2.value as value2
from (select t1.*, row_number() over (order by id) as seqnum
fr... | Try this:
```
with Table_1(ID, NAME, VALUE) as (
select 1, 'abc', 10 union all
select 2, 'def', 20 union all
select 3, 'def', 20
), Table_2(ID2, NAME2, VALUE2) as (
select 5, 'ghi', 30 union all
select 6, 'gkl', 40
), prep_table_1 (ID, NAME, VALUE, rn) as (
select id, name, value, row_number() over(order b... | Select data from two tables with no join condition, t-sql | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
These are my tables
## **Table1**
* price
* city\_category\_id
* city\_product\_id
Here are three rows"
```
price | city_category_id | city_product_id
------+------------------+--------------------------
1500 | CHDELCLAPTOPDELL | CHDELCLAPTOPDELLVOSTR8
1200 | CHDELCLAPTOPDELL | CHDELCLAPTOPDELLVOSTR816
1000 | CH... | As I understand you want something like this:
```
DECLARE @sellers_product TABLE (price INT, Category_id VARCHAR(100), product_name VARCHAR(100))
INSERT INTO @sellers_product SELECT 1500, 'DELL', 'Vostro123'
INSERT INTO @sellers_product SELECT 1200, 'DELL', 'Vostro1234'
INSERT INTO @sellers_product SELECT 1000, 'DEL... | ```
;WITH CTE_RESULT AS
(
SELECT price, city_category_id, city_product_id, -- USE THE SELECT COLUMNS HERE
ROW_NUMBER() OVER (PARTITION BY city_product_id --USE THE DISTINCT COLUMN HERE
ORDER BY price ASC -- CHANGE THE ORDER HERE) ROW_NO
FROM #TABLE1
)
SELECT price, city_category_id, city_product_id F... | Find distinct values in SQL when subquery returns more than one row? | [
"",
"mysql",
"sql",
"sql-server",
""
] |
The goal is to count; how many user\_id's have more then one record.
the result would be: 2
*(only one record should return)*
**THE DATA**
user\_id | value
12 | value1
25 | value2
25 | value3
17 | value4
17 | value5
**Thank you all for your quick response!** | I'm not sure whether I get your question right, but shouldn't the following work?
```
SELECT user_id, count(*)
FROM mytable1
GROUP BY user_id
HAVING count(*) > 1
```
-> Result all user\_id, with more then one entry
or if you wanna count how many entries are not unique..
```
SELECT COUNT(*) AS AreDublicate ... | To arrive at a single number you need an inner and outer query, like so:
```
SELECT COUNT(*) FROM (
SELECT user_id
FROM mytable1
GROUP BY user_id
HAVING count(*) > 1
) iq
``` | sql - count (if more then one) through a case | [
"",
"sql",
""
] |
I have a booking table with the following information:
BookingID,(unique, not null)
StartDate, (not null)
EndDate (not null)
I need to calculate the number of nights someone remained in residence which I can do with a DATEDIFF between EndDate and StartDate. However, if someone is in residence for the entire month dur... | I would first to create a lookup table with all the month with 31 days
Such as
```
DECLARE @month TABLE (start_date date,end_date date)
INSERT INTO @month VALUES ('2014-07-01','2014-07-31'),('2014-08-01','2014-08-31'),('2014-10-01','2014-10-31'),('2014-12-01','2014-12-31')
//populate all months in your calculat... | Retrieve the integer part of the datediff divided by 31 :
```
SELECT DATEDIFF(day,'2014-07-25', '2014-09-02') - DATEDIFF(day,'2014-07-25', '2014-09-02') / 31
``` | Sql Server 2008 Calculate nights between two dates but remove 31st night | [
"",
"sql",
"sql-server",
"sql-server-2008",
"datediff",
""
] |
How to create a table with a column which is unique, not null and not empty(Check)?
I tried below Query
```
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Address nvarchar(255),
City nvarchar(255),
CHECK (P_Id>0)
)
```
When i try to create a table with bot... | ```
CREATE TABLE tab
(
id INT,
notnullandnotemptystr VARCHAR(10) NOT NULL UNIQUE CHECK (DATALENGTH(notnullandnotemptystr) > 0)
)
``` | It should be some thing like this.
```
CREATE TABLE [dbo].[TABLE1](
[COL1] [nvarchar](50) NOT NULL UNIQUE
)
ALTER TABLE [dbo].[TABLE1] WITH CHECK
ADD CONSTRAINT [CK_TABLE1] CHECK (([COL1]<>N''))
``` | SQL Server Create Table With Column Unique Not Null and Not Empty(Check) | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"unique",
""
] |
I was searching for querys but i cant find an answer that helps me or if exit a similar question.
i need to get the info of the customers that made their last purchase between two dates
```
+--------+------------+------------+
| client | amt | date |
+--------+------------+------------+
| 1 | 2440.... | Something in this format, replace date1 and date 2 with the real values.
```
SELECT client, max(date)
from table
group by client
having max(date) between date1 AND date2
``` | There is more than one way to do this. Here is one of them.
```
select * from
(
select client, max(date) maxdate
from table
group by client ) temp
where maxdate between '2014-02-11' and '2014-03-06'
``` | Get the MAX date between a range | [
"",
"mysql",
"sql",
""
] |
I have millions of items where I need to set whether they exist or not for many different configurations that will change over time.
I have four parameters.
1. `Production`
2. `14.15`
3. `Both-Local-General`
4. `Exists`
I want to create a table where the column name looks like `Production,14.15,Both-Local-General,Ex... | This is a bad idea. Why not have a table called "Configurations" with two fields "Parameters" and "Value". Then Create/Update/Delete rows instead of columns. To do it the other way seems like a complete misuse of an RDBMS. | Its more efficient to create a table with a single column for the parameter names and use a [Pivot](https://stackoverflow.com/questions/24470/sql-server-pivot-examples) or [Case When](https://stackoverflow.com/questions/5846007/sql-query-to-pivot-a-column-using-case-when) to display it as you have mentioned when queryi... | Best Practice to Use Multiple Parameters for SQL Column names? | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
```
Table A Table B
ID Name ID Name Last_Name
1 John 1 John Depp
2 Henry 2 David Henry
3 Ken
```
I was try to select the name in a statement with these condition:
1. If the `NAME` in `TableA` able to map wi... | you can use CASE TO make more readable
```
SELECT A.ID NO, CASE WHEN A.Name = B.Name THEN B.LAST_NAME
WHEN A.Name = B.LAST_NAME THEN A.NAME
WHEN A.Name = B.Name AND A.Name = B.LAST_NAME THEN A.NAME END AS REALNAME
FROM TABLEA A, TABLEB B
``` | You can use inner and outer joins rather than your exists and not exists subqueries, which may perform better:
```
select a.id, b.last_name as realname
from tablea a
join tableb b
on a.name = b.name
union all
select distinct a.id, a.name
from tablea a
join tableb b
on a.name = b.last_name
union all
sel... | Select statement with inner join | [
"",
"mysql",
"sql",
"select",
"inner-join",
""
] |
I need to search for Article Tag strings that are sub-strings of a user entered string.
So in the below example, if a user searched for "normal", the query should return Article 1 and Article 3, as article 3 has a wildcard tag "norm\*".
If I searched for "normalization" then i should get back articles 3 and 4.
Let me ... | The easiest way to do it, but perhaps not the most efficient, is to replace all `*` by `%` in your table and use `LIKE` statment :
```
SELECT
Tag
FROM
Article
WHERE
'normal' LIKE REPLACE(Tag, '*', '%')
```
See an example in [SqlFiddle](http://sqlfiddle.com/#!2/3a928/3/0) | I think this query should work, although I didn't test it beyond your sample data.
Also, you didn't specify what database you're using and I just tried it on MS SQL, but it should be easy to adapt to other databases as it only relies on charindex and left (or substring) and those functions should be available on most ... | SQL Query to do a reverse CONTAINS search? | [
"",
"sql",
"regex",
""
] |
I have below query to support employee pagination sorted by employee name
```
SELECT rowNumAlias
,Employee.employeeId
,Employee.NAME
FROM (
SELECT row_number() OVER (
ORDER BY Employee.NAME ASC
) rowNumAlias
,employeeId
,NAME
FROM Employee
) employeeData
INNE... | You can try like this:
```
SELECT * FROM (
SELECT (SELECT row_number() OVER (ORDER BY e2.NAME ASC) FROM Employee e2 WHERE Employee.employeeId = E2.employeeId) rowNumAlias,
,Employee.employeeId
,Employee.NAME
FROM Employee
) e3 WHERE e3.rowNumAlias BETWEEN ? AND ?
``` | You can try to use CTE for this.
```
;WITH employeeData as
(
SELECT row_number() OVER (ORDER BY Employee.NAME ASC) rowNumAlias,
employeeId,
NAME
FROM Employee
)
SELECT employeeData.rowNumAlias,
employeeData.employeeId,
employeeData.NAME
FROM employeeData
INNER JOIN Employee ON Employee.employeeId = em... | Performance tuning of this query? | [
"",
"sql",
"sql-server",
"database",
"sql-optimization",
""
] |
I have three tables like this.
**userLogin**
```
userID userPassword
c01 chutop
c02 213jkd
```
**SystemUser**
```
userID FName LName CategoryID
c01 Sidy Kamal 2
c02 Bindu Namal 1
c03 Sandy Khan 3
```
**SystemUserCategory**
```
CatID Ca... | Here's my answer.
```
SELECT userFName,UserLName,CatName
FROM userLogin INNER JOIN SystemUser ON (userLogin.userID=SystemUSer.userID) INNER JOIN SystemUserCategory ON (SystemUser.userCatID=SystemUserCategory.catID)
WHERE UserLogin.userID='c002' AND UserLogin.userPassword='ryan';
```
Apply the necessary username and p... | You must use inner join instead of selecting from multiple tables.
Like this:
```
select userFName, userLName,catID
from userLogin UL inner join SystemUser SU
on Ul.userId = SU.userId inner join SystemUserCategory SUC
on SU.CatID = SUC.CatID
``` | Get data from three tables in a single query | [
"",
"sql",
"sql-server",
"select",
""
] |
How does one in oracle find the greatest of three columns in say 10 rows?
The requirement is I have three dates column and I have need to find greatest of three columns in 10 rows. I know greatest will find in one row.
How? | How about
```
select max(greatest(date1, date2, date3, date4)) from my_table;
``` | you can use `greatest` again in your `order by`
```
select * from (
select greatest(c1,c2,c3,c4) from mytable
order by greatest(c1,c2,c3,c4) desc
) t1 where rownum = 1
``` | SQL query to find greatest in columns and rows | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I have created a betting database and I am trying to determine who are the best and worst betters. The easiest way I determined to do this is get the sum of the winnings by a user and subtract that by the sum amount they have bet
My first SQL query is
```
SELECT fromuser,SUM(itemsgiven::int)
FROM transactions
WHERE t... | You could use this query:
```
SELECT usr, SUM(subtotal) AS total
FROM (
SELECT fromuser AS usr, SUM(itemsgiven::int) AS subtotal
FROM transactions
WHERE transtype='Bet Placed'
GROUP BY fromuser
UNION ALL
SELECT touser AS usr, -1*SUM(itemsgiven::float) AS subtotal
FROM transactions
WHER... | You can do this with `UNION`:
```
SELECT user_id, SUM(itemsgiven) as total_itemsgiven
FROM
(
SELECT fromuser user_id, - itemsgiven::int itemsgiven
FROM transactions
WHERE 'Bet Placed'
UNION
SELECT touser user_id, itemsgiven::int itemsgiven
FROM transactions
WHERE 'Bet Won'
) t
GROUP BY user... | Subtracting multiple rows from two sql queries | [
"",
"sql",
"postgresql",
""
] |
I have two a table and a view . The table if of two rows of datatypes nvarchar and money. I have being updating the table by selecting from the view like below.
```
Insert into MyTable
Select * from MyView
```
Recently, this update fails due to an error "String or binary data would be truncated." However, when i ... | looks like the data in some column in table MyView exceeds the limit of the corresponding one in table MyTable | String or binary data would be truncated happened because the data coming from the MyView is larger than the column size in MyTable
Use
```
Select Max(Len(FieldName)) From MyTable
```
to check the maximum length of the nvarchar field in the MyTable
Or you can use Left when inserting data something Llike this
```
In... | How to select record of different data type from sql column | [
"",
"sql",
"sql-server",
""
] |
I am working on a Project in which i have a date(i.e 01-01-2013) on which a item was taken on lease for some months like 60, 70 months. It is different for different customers. I want to send a email to all the customers to renew the lease whose lease date is going to be end after 2 days. I am not able to get the expir... | you need to use [DATE\_ADD()](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-sub)
where you add lease duration to lease start date
that will result in end-lease-date
then subtract [DATE\_SUB()](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-sub) 2 da... | Here is the function you're looking for:
```
DATE_ADD(taken_date,INTERVAL nb_months MONTH)
```
This function will give you the expiration date corresponding to the `taken_date` on which i add the desired number of months.
Hope this will help. | How to get future date if i have the past date and the number of months after which i want the date? | [
"",
"mysql",
"sql",
"date",
""
] |
I am selecting from two tables, a product table and a shipping table, and building the table below, but I'd like to divide the product $ value by the number of rows per ID so that the product $ is split between all the rows it appears on. Is there a way to do this in the select statement as I'm building the table?
Wha... | It is simpler to use [windowing functions](http://msdn.microsoft.com/en-us/library/ms189461%28v=sql.90%29.aspx) instead of subqueries:
```
SELECT
[ID]
,[Product $] / COUNT(*) OVER(PARTITION BY [ID])
,[Shipping $]
FROM MyTable
``` | Before joining product & shipping table, you can calculate product price based on the count (as in the inner query) and then you can inner join it with shipping table. From the post-view, you can use the following query as a reference:
```
SELECT ps.id
,t1.new_c
,ps.shipping
FROM product_shipping ps
INNER JOIN... | In SQL, how can I divide a value by the number of rows it is in? | [
"",
"sql",
"sql-server",
""
] |
I'm using a stored procedure to search in my database and filtering the results on a parameter and I need to filter on unknown multiple parameters.
How can I write a stored procedure that handles this??
Here is my stored procedure :
```
CREATE PROCEDURE ComplaintRefListOnDistrict
@District nvarchar(max) = ''
AS... | I was telling to use this kind of dynamic SQL.
```
CREATE PROCEDURE ComplaintRefListOnDistrict
@District nvarchar(max) = ''
AS
BEGIN
SET NOCOUNT ON;
declare @sql nvarchar(max)
set @sql = 'SELECT
ComplaintFullID, CustomerName, Customer_Address, CustomerEmail,
... | First add a helper function, that will split the string you pass to it into rows.
```
CREATE FUNCTION SplitString
(
@string NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS
@output TABLE(Data NVARCHAR(MAX))
BEGIN
DECLARE @start INT, @end INT
SELECT @start = 1, @end = CHARINDEX(@delimiter, @stri... | Handle multiple parameters in SQL Server | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I have a sql select:
```
SELECT employee.name, employee.surname, department.name FROM employee INNER JOIN deparment
ON employee.id_department=department.id WHERE department.name = 'security'
```
But I wanna select **only 5 records**. If I can do this using the SQL tools?
And If I wana select **>= 5 records** (more ... | Here is the SQL
```
SELECT employee.name, employee.surname, department.name
FROM employee INNER JOIN deparment
ON employee.id_department=department.id
WHERE department.name = 'security'
LIMIT 5;
```
To know more about [LIMIT](http://www.mysqltutorial.org/mysql-limit.aspx)
---
## Edit
I believe **>= 5 records** m... | ```
SELECT employee.name, employee.surname, department.name FROM employee INNER JOIN deparment
ON employee.id_department=department.id WHERE department.name = 'security'
limit 5;
``` | How to select from DB only 5 records. Use MySQL | [
"",
"mysql",
"sql",
""
] |
```
SELECT
u.*,
GROUP_CONCAT(DISTINCT f.shot_id SEPARATOR ",") AS ownFavorites,
GROUP_CONCAT(DISTINCT st.shot_id SEPARATOR ",") AS ownStars,
GROUP_CONCAT(DISTINCT s.id SEPARATOR ",") AS ownShots,
( SELECT AVG(p.count)
FROM points p
... | Don't forget GROUP BY in the subqueries:
```
SELECT
u.*,
COALECSE(a.average, 0) attention,
COALESCE(p.total, 0) popular,
GROUP_CONCAT(DISTINCT f.shot_id) AS ownFavorites,
GROUP_CONCAT(DISTINCT st.shot_id SEPARATOR ",") AS ownStars,
GROUP_CONCAT(DISTINCT s.id SEPARATOR ",") AS ownShots
FROM
... | Try turning the selects into a subselect join.
```
FROM users u
LEFT OUTER JOIN shots s ON s.user_id = u.id
LEFT OUTER JOIN favorites f ON f.user_id = u.id
LEFT OUTER JOIN stars st ON st.user_id = u.id
LEFT OUTER JOIN ( SELECT AVG(p.count) AverageOfP, p.shot_id
FROM points p
WHERE ... | Pass Value to Subselect | [
"",
"mysql",
"sql",
""
] |
I'm trying to filter some values and I need to know if they can be between two dates or not, but I could not create a SQL to do this.
I have the following date: `May 10 2010`.
I need to find if this date can be between two dates if I add some years to it.
**Example1**: can this date be between `January 15 2014` and ... | This is a bit tricky in SQL Server. I think the best way is to normalize the dates to Jan 1, based on when the period begins. Then you can safely use `datediff()` to add the appropriate year value.
Something like this:
```
select (case when dateadd(year, datediff(year, newdate, newstart), newdate)
... | You can try something like this:
```
declare @intervals table (StartDate date, EndDate date);
declare @date date = '2010-05-10';
insert into @intervals values
('2014-01-15', '2014-06-20'),
('2014-05-15', '2014-06-20'),
('2013-12-15', '2014-06-20');
select case when dateadd(year,year(EndDate)-year(@date),... | How do I get a date between two dates? | [
"",
"sql",
"sql-server",
""
] |
So I have 4 tables that are connected via foreign keys namely result, position, student, candidates
What i need to achieve is this:
output:
```
------------------------
s_fname | count(c_id)
-----------------------
Mark | 2 -> President
France| 2 -> President
```
.. to count as to how man... | This is untested, but should return your intended result.
What it does is joins all of your tables on the related `foreign keys`, effectively giving a wide table of all of your columns. Then we limit on the `candidates` that are running for the `President` position. Since we need to `group` because of the `count aggre... | # Code:
```
SELECT s_fname AS [Student Name], COUNT(A.c_id) AS [Count], po_name AS [Position]
FROM results AS A INNER JOIN candidates AS B ON A.c_id=B.c_id
INNER JOIN student AS C ON A.sid=C.sid
INNER JOIN positioning AS D ON B.pos_id=D.pos_id
WHERE B.pos_id = 1
GROUP BY s_fname
``... | How to write this basic sql statement | [
"",
"mysql",
"sql",
""
] |
I have the following Query....
```
SELECT DISTINCT
p.ProductID, p.ProductName,
od.Quantity, o.Shipcountry, o.ShippedDate
FROM
Products p, [Order Details] od, Orders o
WHERE
p.ProductID = od.ProductID
AND od.OrderID = o.OrderID
AND o.ShippedDate < '1997-01-01'
AND ShipCountry = 'Spain'
... | The `OR` statement is messing up your results in your `WHERE` criteria. You can solve it with `IN` or using parentheses:
```
SELECT DISTINCT p.ProductID, p.ProductName, od.Quantity,o.Shipcountry,o.ShippedDate
FROM Products p
JOIN [Order Details] od ON p.ProductID=od.ProductID
JOIN Orders o ON od.OrderID=o.Order... | The problem is the `or` statement. But, you should rewrite the query using explicit joins. Also, `IN` will help fix the problem with the `or`:
```
SELECT DISTINCT p.ProductID, p.ProductName, od.Quantity,o.Shipcountry,o.ShippedDate
FROM Products p JOIN
[Order Details] od
ON p.ProductID = od.ProductID IN
... | Can't get my SQL query to comply with date request | [
"",
"sql",
"sql-server",
""
] |
I'm trying to run a query that retrives all records in a table that exists in a subquery.
However, it is returning all records insteal of just the ones that I am expecting.
Here is the query:
```
SELECT DISTINCT x FROM T1 WHERE EXISTS
(SELECT * FROM T1 NATURAL JOIN T2 WHERE T2.y >= 3.0);
```
I've tried testi... | You need a correlated subquery, not a join in the subquery. It is unclear what the right correlation clause is, but something like this:
```
SELECT DISTINCT x
FROM T1
WHERE EXISTS (SELECT 1 FROM T2 WHERE T2.COL = T1.COL AND T2.y >= 3.0);
```
Your query has a regular subquery. Whenever it returns at least one row, the... | **Q: Why is EXISTS evaluating true for all the records in T1?**
**A:** Because the subquery returns a row, entirely independent of anything in the outer query.
The `EXISTS` predicate is simply checking whether the subquery is returning a row or not, and returning a boolean TRUE or FALSE.
You'd get the same result wi... | MySQL WHERE EXISTS evaluating to true for all records | [
"",
"mysql",
"sql",
"subquery",
"where-clause",
"exists",
""
] |
I recently started to support a project for which databases are maintained in SQL Server 2008 R2.
There is a SQL server agent DBMR job which was running fine until couple of days back. Now it's been failing with error " Could not find stored procedure 'XXX' ". When I looked in the master database, that procedure is no... | Thank you all for your suggestions/answers.
One of our engineers tried to install a different DBMR version and this deleted some of the jobs, SP's etc. Sorry if wasted your time. | ```
SELECT * FROM sys.fn_dblog(NULL, NULL);
```
using above query you will be able to identify the dropped stored procedure details
```
SELECT CONVERT(varchar(max), SUBSTRING([RowLog Contents 0], 33, LEN([RowLog Contents 0]))) AS Script FROM fn_dblog(NULL, NULL) WHERE Operation = 'LOP_DELETE_ROWS' AND Context = 'LCX_... | SQL Server Agent Job failing | [
"",
"sql",
""
] |
I have a situation, where I get a result set and based on the values from the result set I need to delete records, from another table.
Example :
```
ResultSet rs = SELECT col FROM TableA;
```
Now I dont know whether `rs.getString(1)` is `null` or not.
so if it is null i have to do :
```
DELETE FROM TableB WHERE co... | If you use the normal comparison operator, it always returns false if one of the operands is null.
So you have to explicitly check for null values:
```
DELETE FROM TableB
WHERE
col2 = rs.getString(1) OR -- Neither are NULL and they have the same value.
(col2 IS NULL AND rs.getString(1) IS NULL) -- or Both are n... | Something like:
```
DELETE FROM TableB
WHERE ISNULL(col2,'VALUEISNULL') = ISNULL(rs.getString(1),'VALUEISNULL')
```
'VALUEISNULL' may be whatever you want that would not be a valid value for that field. | How to distinguish between NULL and NOT NULL during comparison | [
"",
"sql",
"compare",
"isnull",
""
] |
DBA does not like that I am using case statements with sub-queries. Is there another approach I could take to improve performance? This update statement is a part of stored proc.
```
UPDATE dbo.CMN_PersonsFerpa
SET
IsWorkEmailFerpa = (CASE WHEN (SELECT EmailType FROM dbo.CMN_PersonsEmailLinks WHERE C... | The goal would be to eliminate sub-queries. You could do so by building up a temp table before the update, or by using proper linking. Without knowing your data schema it is hard to help you design something, but here is a shot:
```
update p set
IsWorkEmailFerpa = case when e.EmailType = 'Work' then @IsFERPA else... | Why wouldn't you use a join? Correlated subqueries work row by row like a cursor and almost never should be used. | Improve this SQL Query for better performance | [
"",
"sql",
"sql-server",
"subquery",
"case-statement",
""
] |
```
Name varchar, Value int, Active bit
-----------------------------------
'Name1',1,1
'Name2',2,1
'Name1',3,0
'Name2',4,0
'Name3',1,1
'Name4',1,1
```
I want to return where `Active` is anything but prioritize when it's `0` so I want to return this:
```
'Name1',3
'Name2',4
'Name3',1
'Name4',1
```
I tried this, but ... | Your question is a little confusing, but if I'm understanding it correctly, you need to use a `group by` statement:
```
select name,
max(case when active = 0 then value end) value
from yourtable
group by name
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!3/93c89/1)
---
With your edits, you can use `coalesce` and... | You can order by fields not contained in the select clause
```
Select Name, Value
From Table
ORDER BY Active, Name, Value
```
But you cannot use `SELECT DISTINCT` at the same time.
If you use "select distinct" there is the possibility that some rows will be discarded, when this happens there is no longer any viable... | Returning distinct prioritizing results with order by | [
"",
"sql",
"sql-server-2008",
""
] |
I have table with the columns partner, post, postvariation
Now I'd like to know how many postvariations per post every partner has in average. I tried the following, however it is not working
```
SELECT partner,
COUNT(DISTINCT post),
COUNT(DISTINCT postvariation),
AVG(COUNT(DISTINCT post,postvariation))
FROM post... | Here is the query you're looking for:
```
SELECT P.partner
, COUNT(DISTINCT P.post) AS nb_post
, COUNT(DISTINCT P.postvariation) AS nb_postvariation
, COUNT(DISTINCT P.postvariation) / COUNT(DISTINCT P.post) AS avg_postvariation
FROM posts P
GROUP BY P.partner
ORDER BY P.id DESC;
```
Here is the same quer... | Well you need to use division to find average.
## **Query**
```
SELECT partner, post, postvariation, (postvariation/post) as result
FROM
(
SELECT partner,
COUNT(DISTINCT post) as post,
COUNT(DISTINCT postvariation) as postvariation
FROM posts
GROUP BY partner
ORDER BY id DESC
) AS new_table
``... | MySQL Nested AVG over SUM | [
"",
"mysql",
"sql",
""
] |
How can I replace one char from a SQL Server `Select` command without changing the value in the table itself?
Example:
```
Select Col_Name
from TABLE
```
returns
```
**RANDOM/ANSWER**
```
How do I modify the `Select` query to get `**RANDOM-ANSWER**` instead? So the `/` is replaced by `-`. But the data in the tabl... | The [`replace`](http://msdn.microsoft.com/en-us/library/ms186862.aspx) function should do the trick:
```
SELECT REPLACE(my_column, '/', '-')
FROM my_table
``` | ```
Select Col_Name, REPLACE(Col_Name, '/', '-') AS New_Column
from TABLE
``` | Replacing / with - in SQL Server using Select Command | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a table in PostgreSQL 9.2 that has a `text` column. Let's call this `text_col`. The values in this column are fairly unique (may contain 5-6 duplicates at the most). The table has ~5 million rows. About half these rows contain a `null` value for `text_col`. When I execute the following query I expect 1-5 rows. I... | A **[partial index](https://www.postgresql.org/docs/current/indexes-partial.html) is a good idea** to exclude half the rows of the table which you obviously do not need. Simpler:
```
CREATE INDEX name_idx ON table (text_col)
WHERE text_col IS NOT NULL;
```
Run `ANALYZE table` after creating the index. (`autovacuum` d... | ~~I figured it out~~. Upon taking a closer look at the `pg_stats` view that `analyze` helps build, I came across this excerpt on the [documentation](http://www.postgresql.org/docs/9.2/static/view-pg-stats.html).
### Correlation
> Statistical correlation between physical row ordering and logical
> ordering of the colu... | PostgreSQL does not use a partial index | [
"",
"sql",
"database",
"performance",
"postgresql",
"indexing",
""
] |
I have a a large customer database where customers have been added multiple times in some circumstances which is causing problems. I am able to use a query to identify the records which are an exact match, although some records have slight variations such as different addresses or given names.
I want to query across 1... | You are just missing the magic of [`CUBE()`](http://technet.microsoft.com/en-us/library/bb522495%28v=sql.105%29.aspx), which generates all the combinations of columns automatically
```
DECLARE @duplicate_column_threshold int = 5;
WITH cte AS (
SELECT
field1,field2,...,field10
,duplicate_column_count = (SELEC... | You might try something like
```
Select field1, field2, field3, ... , field10, count(1)
from customerdatabase
group by field1, field2, field3, ... , field10
order by field1, field2, field3, ... , field10
```
Where `field1` through `field10` are ordered by the "most identifiable/important" to least. | SQL - Find duplicate fields and count how many fields are matched | [
"",
"sql",
"sql-server",
"count",
"duplicates",
""
] |
I'm working on a SQL request for an internal search engine (MySQL db). I want to allow users to search for exact expressions, so when they search for `"foo bar"` they get the documents containing `foo` AND `bar` and not just `foo` or `bar`.
The `search_documents_words` table:
```
| word_id | doc_id | word |
---------... | Assuming that your search keyword is in array
```
$search = array('foo','bar');
$keywords = '';
foreach($search as $values) {
$keywords .= "'.$values.',";
}
$keywords = rtrim($keywords,","); // creating words as 'foo','bar'
```
then execute this query
```
$query = "SELECT B.*
FROM search_documents_words... | The subquery can be build like this:
```
$keywords = array('foo','bar');
foreach($keywords as $key)
{
$conditions[] = "word='".$key."'";
}
$condition = implode(" AND ",$conditions);
```
Then execute this sql query:
```
$query = "SELECT *
FROM search_documents
WHERE doc_id
IN (SELEC... | How to select rows with same ID sharing a group of values? | [
"",
"mysql",
"sql",
""
] |
I have 4 stored procedures. I need to take the result of the first stored procedure (2 temp tables) and pass it into the second stored procedure. These temp tables need to be used in the from clause in the second stored procedure.
Similarity the third and fourth stored procedures need results from the previous stored ... | Regarding this comment, "it was 1 Sp but we broke it into 4 so its easier to alter if needed", I suggest that you break it up even more. In other words, implement encapsulation.
Have a separate stored procedure for each time you want to select data from the actual tables. Do not populate temp tables in these procedure... | Your question sounds more like an answer than a question. Just do as you described.
You don't need to *pass* the data in the temp tables from one procedure to the next. The data is just there. In one procedure you write to the temp table and in the next procedure you read from the temp table.
I would also not create ... | Is there a way to pass temporary tables across the stored procedures | [
"",
"sql",
"stored-procedures",
""
] |
```
select
distinct on (productid)p.product,
pb.productid,
pb.mrp,
pb.ptr,
pb.ssr,
pt.patent
from prod_batch pb
inner Join prod_patent pt using(patentid)
inner Join prods p using(productid)
where(qty - iqty) > 0
```
this selects returns correctly and getting what actually I want... | You can try like this
Choice - 1
```
select * from (
select
distinct on (productid)p.product,
pb.productid,
pb.mrp,
pb.ptr,
pb.ssr,
pt.patent
from prod_batch pb
inner Join prod_patent pt using(patentid)
inner Join prods p using(productid)
where(qty - iqty) > 0
order by
pr... | DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. [...] Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. [...] The DISTINCT ON expression(s) must match the leftmost OR... | Error when adding ORDER BY in Select Query | [
"",
"sql",
"postgresql",
"sql-order-by",
"distinct",
""
] |
Although one can use composite primary keys, for the case below, is it really a bad practice? The consensus on Stackoveflow *seems to go both ways on this issue*.
Why?
---
I want to store payments for the orders in a separate table. The reason is that, an order can have many items which are handled in a separate tab... | There is no conclusion that composite primary keys are bad.
The best practice is to have *some* column or columns that uniquely identify a row. But in some tables a single column is not enough by itself to uniquely identify a row.
SQL (and the relational model) allows a composite primary key. It is a good practice is... | This question is dangerously close to asking for opinions, which can generate religious wars. As someone who is highly biased toward having auto-increasing integer primary keys in my tables (called something like `TablenameId`, not `Id`), there is one situation where it is optional.
I think the other answers address w... | Composite Primary Keys : Good or Bad? | [
"",
"sql",
"database",
"database-design",
"relational-database",
""
] |
I'm doing a SQL Union syntax and I wanted to have a result like this:
```
+---------------+-----+---------+
|trkBusinessUnit| New | Pending |
+---------------+-----+---------+
| AIIB 2 0 |
| Credit Control 1 3 |
| Direct Center 1 2 |
| Financial Ins 1 1 |
| Motor... | There are (or has been) some syntax issues in the previous answers, but the intent of both earlier answers is correct, you need to use a `GROUP BY` query and NOT use `UNION` - which simply does not do what you were hoping/expecting.
UNION or UNION ALL work ROW by ROW, and absolutely do NOT merge by COLUMN
So, the MyS... | If I understand you correctly, you don't have to use an union.
Try:
```
SELECT
trkBusinessUnit,
COUNT(CASE WHEN trkStatus = 'New' THEN 1 ELSE NULL END) as New,
COUNT(CASE WHEN trkStatus = 'Pending' THEN 1 ELSE NULL END) as Pending
FROM tblDTPTracker
GROUP BY trkBusinessUnit
``` | Combining data in SQL Union syntax | [
"",
"mysql",
"sql",
"union",
""
] |
I am trying to search through a table column for: **`<o:p />`** to then replace it to **`</p>`**
I know it to be the REPLACE function but unsure how to correctly format the query. | To replace values in a column you would do this:
```
update tablename set
columnname = replace(columnname, '<o:p />', '</p>')
WHERE columnname LIKE '%<o:p />%'
``` | ```
update table
set column=replace(column,'<o:p />', '</p>')
where condition
``` | SQL Replace instance of word with another | [
"",
"mysql",
"sql",
""
] |
I am trying to match the first name varchar (50) and last name varchar(50) from table A to the first name varchar(50) and last name varchar(50) on table B. The issue is that both table contain a lot of shortened first names like the name Andrew in table A and there might be a matching record with the last name but the ... | Provided you use a 3rd Table to hold you Long/Short Names as so.
```
CREATE TABLE TableNames
([Id] int, [OfficialName] varchar(7), [Alias] varchar(7))
;
INSERT INTO TableNames
([Id], [OfficialName], [Alias])
VALUES
(1, 'Andrew', 'Andy'),
(2, 'Andrew', 'Andrew'),
(3, 'William', 'Bill'),
(4, 'Wi... | Create a third table that associates Long-form and short-form names.
For examle:
```
Long Form Short Form
Andrew Andy
Andrew Drew
David Dave
William Will
William Bill
William Billy
William Willy
``` | Matching First and Last Name on two different tables | [
"",
"sql",
"sql-server",
"regex",
""
] |
I have a table, `SELECT * FROM data`
```
id pred name visual link, for your convenience
--------------------
1 null One
20 null Two <--+
21 20 Three -^
30 null Four <--+
31 30 Five -^ <--+
32 31 Six ... | ```
SQL> select id
2 , pred
3 , name
4 , connect_by_root id init
5 , connect_by_root name initname
6 , sys_connect_by_path(id,' -> ') scbp
7 from data
8 connect by prior id = pred
9 start with pred is null
10 /
ID PRED NA... | Please try to use following expression to get name of the root element:
```
substr(SYS_CONNECT_BY_PATH(name, '/'), instr(SYS_CONNECT_BY_PATH(name, '/'), '/', -1)+1)
```
Replace delimiter '/' if needed.
```
SELECT id, pred, CONNECT_BY_ROOT id init, LEVEL, CONNECT_BY_ISLEAF "IsLeaf",
substr(SYS_CONNECT_BY_PATH... | How to get to the "final predecessor" with a CONNECT BY query? | [
"",
"sql",
"oracle",
"hierarchical-data",
"connect-by",
""
] |
I'm using SQL Server 2008R2 in this problem. Here's an example dataset:
```
WIRE_ID FROM TO CLASS
05485 0.000 1.520 PL
05485 1.520 3.050 PL
05485 3.050 22.250 SL
05485 3.050 22.250 SP
05485 22.250 33.530 SL
05485 22.250 33.530 QT
05485 33.530 43.... | As others have said, using a temp table instead of a table variable will make a world of difference to the performance. I assume however, you've only used the table variable to pose your example and in reality you have a proper user table that contains all this data.
My query will find the islands, but will provide sl... | Using temporary tables instead of CTE's with large datasets will improve the performance, but without your dataset I'm unable to test the performance of this.
Here's your queries using temp tables:
```
Declare @WIRE_CLASS Table(WIRE_ID varchar(25),
[FROM] float,
[... | Finding Islands With Group and Interval Data | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
"aggregate",
"gaps-and-islands",
""
] |
I have transactional data that looks like this
```
Account ProductCategory
1 a
1 a
1 b
2 c
2 d
2 d
```
I need to find the ProductCategory that appears most per customer. Results:
```
Account ProductCategory
1 a
2 ... | Most databases support the ANSI-standard window functions, particularly `row_number()`. You can use this with aggregation to get what you want:
```
select Account, ProductCategory
from (select Account, ProductCategory, count(*) as cnt,
row_number() over (partition by Account order by count(*) desc) as seq... | This can be done using analytic SQL , or just using count over group. The syntax depends on the RDBMS, as asked by Michael .
you can try following SQL :
```
select * from
(select account, ProductCategory, ct , ROW_NUMBER() OVER (partition by account, ProductCategory ORDER BY ct DESC ) As myRank
from (select account... | Max count by customer and category | [
"",
"sql",
"count",
"max",
""
] |
The table structure remains same after truncate statement and only records get deleted (with auto commit). Then what is the reason that truncate is a DDL statement ? | I'd add here some explanation:
By default, when truncating a table , you are not just removing rows, you are implicitly telling Oracle Database to also perform the following tasks:
Deallocates all space used by the removed rows except that specified by the MINEXTENTS storage parameter
Sets the NEXT storage parameter ... | `TRUNCATE` resets the high water mark of the table, effectively eliminating all the previously existing rows. Treating it as a DDL statement allows it to be super-fast, as it allows it to function without retaining undo (rollback) information like DML statements. | Why is truncate a DDL statement? | [
"",
"sql",
"oracle",
"ddl",
""
] |
I am running this code to import data from Access to Excel and getting a run-time error:
```
"syntax error in FROM clause."
```
The table in Access has four columns: `Date`, `Time`, `Tank`, `Comments`, and I want to import `Time` and `Tank`, based on a date in the spreadsheet.
I want to order these columns in the or... | Start with a `SELECT` statement which Access will accept. Use a string variable to hold the statement. Then you can `Debug.Print` the variable and inspect the statement text in the Immediate window. For troubleshooting, you can also copy the statement text from there and paste it into SQL View of a new Access query.
H... | Do you have an example of your SQL request?
I think there's a problem in the date's format...
you should try to wrap your date (`RpDate`) whith this char `#`, like this :
```
.Open "Select [Time], [Tank] FROM [UnitOneRouting] WHERE [Date] = #" & RpDate & "# ORDER BY Tank, Time", cn, adOpenStatic, adLockOptimistic, a... | Import Data into Excel from Access Table, Syntax error in FROM Clause | [
"",
"sql",
"excel",
"vba",
"ms-access",
""
] |
Given the following SQL table:
```
CREATE TABLE [dbo].[posts]
(
[id] [int] IDENTITY(1,1) NOT NULL,
[user_id] [int] NOT NULL,
[date_posted] [datetime] NOT NULL,
[date_modified] [datetime] NOT NULL,
[content] [text] NOT NULL,
CONSTRAINT [PK_posts] PRIMARY KEY CLUSTERED ( [id] ASC )
)
```
How can I re... | You can get the most recent modified post for every user by using `row_number()`
```
select * from (
select * ,
row_number() over (partition by user_id order by date_modified desc) rn
from posts
) t1 where rn = 1
```
**Edit** it appears you're using mysql, which doesn't support `row_number()`. You can use... | Try This
```
Select
Id
,[User_id]
,[Date_Posted]
,[Date_Modified]
,[Content]
From [dbo].[posts] posts
where date_modified = (select Max(date_modified) from posts2
where posts.[User_id] = posts2.[User_id])
``` | SQL - Retrieve id of most recently modified posts | [
"",
"sql",
""
] |
Q: For each customer list the CustomerID and total number of orders placed.
I believe that I can execute this query with these three tables
```
Customer_T Order_T OrderLine_T
+------+------+------+- +---------+-----------+-------+ +---------+-----------------+
|CustID|... | **For each customer list the CustomerID and total number of orders placed**
This only requires 2 tables (customers and orders)
```
SELECT
Customer_T.CustomerID
, COUNT(Order_T.OrderID) orders_per_customer
FROM Customer_T
LEFT OUTER JOIN Order_T ON Customer_T.CustomerID = Order_T.CustomerID
GROUP BY
Cu... | May this would help you get right answer.
```
SELECT ord.CustID, count(ord.CustID) AS OrderCount, cust.CNAMR
FROM Customer_T cust JOIN Order_T ord
ON ( ord.CustomerID=cust.CustomerID)
JOIN OrderLine_T ordLine
ON ( ord.OrderID=ordLine.OrderID)
GROUP BY ord.CustID ORDER BY OrderCount Desc
```
but it would ... | SQL query over three tables returning an aggregate answer | [
"",
"sql",
"sql-server",
""
] |
My situation:
I have the following view to retrieve data from:
```
|ID | START_DATE | END_DATE |
|80 | 09-JAN-2013 15:01:52 | 20-SEP-2014 15:01:52 |
|82 | 09-SEP-2014 15:01:52 | 25-SEP-2014 15:01:52 |
```
What I want is something like this:
```
|TOTAL_TIME_IN_HOURS| MONTH| YEAR |
| 200 ... | Try this:
```
with t(ID, START_DATE, END_DATE) as (
select 80, to_date('09/01/2013 15:01:52', 'DD/MM/YYYY HH24:MI:SS'), to_date('20/09/2014 15:01:52', 'DD/MM/YYYY HH24:MI:SS') from dual union all
select 82, to_date('09/09/2014 15:01:52', 'DD/MM/YYYY HH24:MI:SS'), to_date('25/09/2014 15:01:52', 'DD/MM/YYYY HH24:MI:... | Another recursive solution, which will require at least Oracle 11gR2:
```
with t(id, start_date, end_date) as
(select 80, to_date('09/01/2013 15:01:52', 'DD/MM/YYYY HH24:MI:SS'), to_date('20/09/2014 15:01:52', 'DD/MM/YYYY HH24:MI:SS') from dual
union all
select 82, to_date('09/09/2014 15:01:52', 'DD/MM/YYYY HH... | Select amount of hours per month where start and end date spans across different years | [
"",
"sql",
"oracle",
""
] |
I trying to re-write this Microsoft Access IF statement as a CASE statement in SQL Server 2008:
```
Status: IIf(
IIf(B.[Online Class Completion Date] Is Null,
Null,
DateDiff("w",A.[Trust Start Date],B.[Online Class Completion Date])
) <=6,
"Pass",
... | First off:
`CONVERT(DATETIME,LEFT(B.[Online Class Completion Date],2)+'/'+SUBSTRING(B.[Online Class Completion Date],4,2)+'/'+RIGHT(B.[Online Class Completion Date],4),103) IS NULL` Will never be TRUE since it will contain '//' at the very minimum. Just test that field is NULL, no reason to convert.
Furthermore, becau... | This would be the appropriate nested case structure, but you would still need to clean up the dateDiff functionality in SQL-Server.
```
CASE WHEN B.[Online Class Completion Date] IS NULL
THEN NULL
ELSE CASE WHEN DateDiff( 'w', A.[Trust Start Date], B.[Online Class Completion Date] ) <= 6
THEN ... | Case statement SQL | [
"",
"sql",
"sql-server",
"if-statement",
"case",
""
] |
Following on from my earlier question here [Case statement for Order By clause with Desc/Asc sort](https://stackoverflow.com/questions/25949837/case-statement-for-order-by-clause-with-desc-asc-sort) I have a statement like this:
```
SELECT
*
FROM
TableName
WHERE
ORDER BY
CASE @OrderByColumn WHEN 1 THEN F... | Do you need this?
```
ORDER BY
CASE @OrderByColumn WHEN 1 THEN Forename END DESC, Date, Location,
CASE @OrderByColumn WHEN 2 THEN Surname END ASC
``` | You can write multiple cases, even if they all have the same condition.
```
ORDER BY
CASE @OrderByColumn WHEN 1 THEN Forename END DESC,
CASE @OrderByColumn WHEN 1 THEN Date END,
CASE @OrderByColumn WHEN 1 THEN Location END,
CASE @OrderByColumn WHEN 2 THEN Surname END ASC
```
Actually, you don't sp... | CASE Statement for Order By Clause with Multiple Columns and Desc/Asc Sort | [
"",
"sql",
"sql-server-2012",
""
] |
I have this table:
```
**ID StartDate EndDate**
1 01/01/2012 03/01/2012
2 28/09/2013 02/10/2013
3 12/06/2011 15/06/2011
```
And I need to have this table:
Date
```
**ID Date**
1 01/01/2012
1 02/01/2012
1 03/01/2012
2 28/09/2013
2 29/09/2013
2 30/09/2013
2 01/10/2... | You can do this by using your source date table as below
```
declare @request int
set @request = 1
;with Dates as (
SELECT @request as reqId,StartDate as reqDate, EndDate
FROM yourDateTable
UNION ALL
SELECT reqId+1,DATEADD(DAY,1,reqDate),Dates.EndDate
FROM Dates
WHERE DATEADD(DAY,1,reqDate)... | Use recursive query
```
CREATE TABLE #ranges
(
Id INT ,
startDate DATE ,
ENdDate DATE
)
INSERT #ranges
( Id, startDate, ENdDate )
VALUES ( 1, '2014-5-2', '2014-5-5' ),
( 2, '2014-8-29', '2014-9-3' ),
( 3, '2014-10-2', '2014-10-8' );
WITH
cte
AS ( ... | Insert a series of dates into sql startdate and enddate inputs | [
"",
"sql",
"sql-server",
"date",
"between",
""
] |
I have a table of answers (tbAnswers). And I have a table which stores who upvotes an answer (tbContentRanking) which has a record for every time an answer has been upvoted.
I'm querying tbAnswers to get answers for each question and I want the answers with the most upvotes (most records in tbContentRanking) to be at ... | Another solution is the next:
Instead of computing the num. of upvotes using a subquery you could [denormalize](http://en.wikipedia.org/wiki/Denormalization) `tbAnswers` table by adding a column named `UpvotesNum`. This means that every upvote action will "touch" two rows:
1. One row in `tbContentRanking` table (beca... | You want to use a GROUP BY clause:
```
SELECT QuestionID, CreateDateTime, Count(AnswerID) as theCount
FROM tbContentRanking
WHERE QuestionID = #arguments.questionID#
GROUP BY QuestionID, CreateDateTime
ORDER BY Count(AnswerID), CreateDateTime
``` | Ordering forum answers based on quantity of upvotes | [
"",
"sql",
"sql-server",
"coldfusion",
"coldfusion-10",
""
] |
I am trying to insert rows if they don't exist (for specific values) in this table.
My table where I insert is insertTable:
```
date (date)
created (datetime)
category (varchar)
companyId (int)
price (decimal 6,3)
```
I select my rows from an inner join between two tables doing :
```
declare @currentDateTime dateti... | You problem statement cannot be accurate
rate is not defined
you are missing created
and you are comparing date to @currentDateTime
```
SELECT @currentDate, @currentDateTime, '30 Day'
, company.companyId, product.price
FROM product
JOIN company
ON product.companyid = company.companyid
and product... | I think you must modify your subquery in `NOT EXISTS`: `@currentDateTime` change to `@currentDate` and `rate.companyid` change to `company.companyid` (because when insert `insertTable.date` gets value of `@currentDate` and `insertTable.companyid` gets value of `company.companyid`):
```
...
AND NOT EXISTS(
SELE... | SQL Query: insert if not already exists from 2 tables | [
"",
"sql",
"t-sql",
""
] |
basically I want to be able to select monday and friday for every week in the year.
So for example this week coming i want 9/29/2014 and 10/3/2014, but i want this for every week in the year. | Here's one way (you might need to check which day of the week is setup to be the first, here I have Sunday as the first day of the week)
You can use a table with many rows (more than 365) to `CROSS JOIN` to in order to get a run of dates (a tally table).
My sys columns has over 800 rows in, you could use any other ta... | You can use a suitable table with numbers, like the master..spt\_values table as basis for the range generation:
```
;WITH dates AS (
SELECT DATEADD(DAY,number,CAST('2014-01-01' AS DATE)) d
FROM master..spt_values WHERE TYPE = 'p'
AND number < 366
)
SELECT
Week = DATEPART(WEEK, d),
DayOfWeek... | How to select every Monday date and every Friday date in the year | [
"",
"sql",
"sql-server-2012",
""
] |
I have two tables. A category table with the columns: `name` and `category`. And an entry table with the columns: `entry` and `entry_name`. The `name` and `entry_name` columns share the same names (foreign key relationship). I could like to do a count of all the entries made in the entry table but only for a specific c... | Create a result with your entries and categories, then filter with where:
```
SELECT COUNT(*)
FROM entries e
LEFT JOIN categories cat
ON e.entry_name = cat.name
WHERE cat.category = ?
``` | Try this:
```
select count(1)
from caterogy c inner join entry e on (c.name = e.entry_name)
where c.category = 'SPECIFIC_CAT'
``` | join between two database values | [
"",
"mysql",
"sql",
"join",
""
] |
I am having all employees(manager and employees) under one table called Employee. Table looks as follows,
## **Table**
```
+-------+------------+---------+---------+------------+
|emp_id | name | dept_id | salary | manager_id |
+=======+============+=========+=========+============+
| 1 | Sally | 1 ... | You need to do left self-join on the table. The left join will ensure that there is a row for every manager even if there are no employees under them. You need to use the `COUNT()` aggregate on a field from the employee side of the join that will be `NULL` if the manager has no employees. `COUNT()` doesn't actually cou... | The correct solution likely involves *fixing* the scheme as any approach will *fail* for a "sub-manager" (who is managed and thus has a manager\_id) but does not currently manage anybody.
Anyway, if the above limitation is acceptable, then people are managers *if* either
* They have a NULL manager\_id (as stated in a... | SQL Self Join with null values | [
"",
"mysql",
"sql",
""
] |
I'm trying to load a Image control from a image blob saved previously in a sql database.I have testd so many ways and i can't make it work. The image blob is saved as:
```
qry.SQL.Text := 'update tbl set pic = :blobVal where id = :idVal';
qry.Parameters.ParamByName('blobVal').LoadFromFile('c:\sample.jpg', ftBlob);
qry... | There a a lot of treads here about loading images to as database, but I did not find one with update or insert parameters.
You might simply assign a graphic object to your parameter.
If you want to store different graphic types you should add a column
keeping the Information which kind of graphic should be stored (e.g... | To load a BLOB field into an image, you need to use TDataSet.CreateBlobStream.
```
var
Stream: TStream;
JPG: TJpegImage;
begin
JPG := TJpegImage.Create;
try
Stream := Qry.CreateBlobStream(Qry.FieldByName('BLOBVAL'), bmRead);
try
JPG.LoadFromStream(Stream);
finally
Stream.Free; // edited... | Delphi load image save as blob in a sql database | [
"",
"sql",
"image",
"delphi",
"blob",
""
] |
I am very much confused about this GROUP BY & Union statements.
Right Now I am getting this O/P.

But I want my output to look like this:
```
Vendor Name Purchase Order Req Qty Inward Qty
------------------------------... | You don't need to create temp table. Just remove vendor\_name from GROUP BY, and add MAX(vendor\_name).
```
SELECT
MAX(vendor_name) AS vendor_name,
purchase_order_no,
SUM(ISNULL(InwardQty,0)) AS InwardQty,
SUM(ISNULL(ReqQty,0)) AS ReqQty
FROM
(
SELECT
vendor_name,
pm.purchase_ord... | I don't know if this is the best solution but I would create a temp table (@a):
```
declare @a table (
purchase_order_no varchar(100),
TotalReqQty int,
TotalInwardQty int )
```
insert the result of:
```
SELECT purchase_order_no,
SUM(ReqQty),
SUM(InwardQty)
FROM table
group by purchase_order_no
```
And aft... | Group by & Union In Sql | [
"",
"sql",
"sql-server",
"group-by",
"sql-server-2012",
"union-all",
""
] |
I have an old query that was using `*=` operator. Right now, the query has where clause like below
```
Table1.Column1 *= Table2.Column1
AND Table1.Column2 *= Table3.Column1
if (some conditions in C# script) //this whole clause is generated by C# function based on different conditions
AND Table1.Column3 *= Table4.Colu... | There are a few things you should update in this query:
1. Use Table Alias in select clause instead of complete table names.
2. `TBL_Customer_Contact_Master` is being joined based on condition:
objListCustomerFilter[ Constants.IS\_CALLING\_CUSTOMER ] != null ||
objListCustomerFilter[ Constants.IS\_PAYEE\_CUSTO... | The difference is in how additional `where` clause filters are applied for columns in the outer joined tables.
With this:
```
select *
from a
left outer join b on a.id = b.id
where
b.other_col = 'test'
```
The result will contain only rows where the row in `b` was found and the `other_col` column in `b` has ... | Understanding join order for 3 or more tables | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
I have a stored procedure in which I am trying to conditionally select a specific table depending on a provided `tinyint` parameter. This is my code:
```
ALTER PROCEDURE [dbo].[GetAllStuff]
@countryId tinyint
AS
BEGIN
SET NOCOUNT ON;
DECLARE @marketSpecific TABLE
SET @marketSpecific =
(CASE ... | You can write a dynamic query as:
```
create PROCEDURE [dbo].[GetAllStuff]
@countryId tinyint
AS
BEGIN
SET NOCOUNT ON
DECLARE @IntVariable int
DECLARE @SQLString nvarchar(500)
DECLARE @marketSpecific varchar(100)
/* Assign parameter value to local variable to avoid parameter sniffing */
SE... | You can't choose a table to use in a CASE statement. You could do something like this:
```
IF @countryId = 1
SELECT * FROM test_sv
ELSE IF @countryId = 2
SELECT * FROM test_dk
ELSE IF @countryId = 3
SELECT * FROM test_no
... etc.
```
But this method might produce some odd query plans and affect performa... | Conditionally select table by CASE | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I have table with field `category` that contains entries like the following:
```
germany_bundesliga
germany_2nd_bundesliga
england_premier_leauge
england_championship
spain_liga
spain_liga_adelante
```
and so on...
i would like to get this output:
```
gemany
england
spain
...
```
Is it possible with an SQL query? | This is what you want right?
```
select distinct SUBSTRING_INDEX(value,'_',1) from category;
```
[SQLFIDDLE](http://sqlfiddle.com/#!2/8a48aa/22) | Something to think about...
```
SELECT SUBSTRING_INDEX('germany_2nd_bundesliga','_',1);
``` | Make SQL query that rename output entries | [
"",
"mysql",
"sql",
"substring",
""
] |
I need to delete few records which I got from a subquery.
Let's say that the `EMP` table has columns `EMPNAME`, `EMPSALARY` and the primary key is a combination of `EMPNAME,EMPSALARY`.
```
delete from emp
where exists (
select *
from EMP ***** //query which fetch few records from EMP table);
```
Th... | Your query would look something like
```
delete from emp
from emp e
where exists (select *
from EMP
WHERE e.EMPNAME = EMPNAME
AND e.EMPSALARY = EMPSALARY
AND <another Condition>) --<-- Condition on which you want to delete rows
``` | you can directly give condition in where clause
```
delete from emp where <conditions>;
```
else you can do in this way
```
DELETE FROM Table1 T1
WHERE EXISTS (SELECT column1 FROM table2 T2
WHERE T1.column1 = T2.column1
AND T1.Column2 = T2.column2 );
``` | delete records which are selected from select query on the same table | [
"",
"sql",
"sql-server",
"oracle",
"oracle-sqldeveloper",
""
] |
I get a lot of database information from clients in excel spreadsheets. I frequently need to insert/update this data back into the database.
I often use excel to generate the insert and update statements via concatenating a bunch of cells together. Sometimes the data includes text cells which can have single quotes in... | The best solution I have found is to use the following:
```
=SUBSTITUTE(A1, "'", "''")
```
This will replace all single quotes with two single quotes which, in T-SQL statements escapes the character and treats it as string data. | Needed to do something similar so I could "escape" double quotes:
```
=CONCATENATE(CHAR(34),"hello",CHAR(34))
```
Result:
[](https://i.stack.imgur.com/iaGTH.png) | Excel escaping quotes or apostrophes in cell values | [
"",
"sql",
"excel",
"replace",
"apostrophe",
"substitution",
""
] |
I am brand new to sql my company just kinda threw me head long into this and said do it. So any help is greatly appreciated. I am trying to get a date to come out in the format of mm/dd/yyyy hh:mm:ss AM/PM so for example a date of 09/26/2014 11:04:54 AM. I have tried using the code:
```
Select Convert(nvarchar,EntryDa... | Since you're on SQL 2012 the format function should work:
```
declare @date datetime = '2014-09-26 11:04:54'
select FORMAT(@date,'MM/dd/yyyy hh:mm:s tt')
```
result: `09/26/2014 11:04:54 AM`
In your case it would be:
```
Select FORMAT(EntryDate,'MM/dd/yyyy hh:mm:s tt')
From DB1
``` | ```
DECLARE @Date_Value DATETIME = GETDATE();
SELECT CONVERT(VARCHAR(10), @Date_Value, 101) + ' '
+ LTRIM(RIGHT(CONVERT(CHAR(20), @Date_Value, 22), 11))
RESULT: 09/26/2014 5:25:53 PM
```
## Your Query
```
SELECT CONVERT(VARCHAR(10), EntryDate, 101) + ' '
+ LTRIM(RIGHT(CONVERT(CHAR(20), EntryDate, ... | Date format returned as mm/dd/yyyy hh:mm:ss AM/PM | [
"",
"sql",
"date",
"datetime",
"sql-server-2012",
""
] |
I have MySQL table with a date of birth. And I want to query the rows which based on age for current date. So following is the query for the table with date range.
```
SELECT * FROM `user` WHERE `dob` > '1980-01-20' AND `dob` < '1990-01-20';
```
How can we convert this query to search with age range for the current d... | You could use the `year` function to extract the year part of the current date. So, for example, if you're looking for users between the ages of 24 and 34:
```
SELECT *
FROM `user`
WHERE (YEAR(NOW()) - YEAR(`dob`)) BETWEEN 24 AND 34
``` | Here is the query you're looking for:
```
SELECT U.*
,DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),U.dob)), ‘%Y’)+0 AS age
FROM `user` U
WHERE DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),U.dob)), ‘%Y’)+0 BETWEEN 20 AND 30
```
In this example, you'll have every users with age in the range `20-30`.
Hope this will help you | MySQL query by age range on a table which have date of birth | [
"",
"mysql",
"sql",
"select",
"where-clause",
""
] |
I have following three tables representing a tree structure. Every row in `#A` is ancestor of zero or more rows in `#B`. Similarly every row in `#B` is ancestor of zero or more rows in `#C`. Table `#B` contains a column `value`. I need to find sum of `value` for all rows in `#B` whose belong to an input ancestor.
For ... | You don't need table #A here, because the IDs are in table #C and the values in table #B. That is all you need. No need to join either. Simply select the IDs needed from #C, then use them to select from #B.
```
select sum(value)
from #B
where id in
(
select b_id
from #C
where a_id = 'A1'
);
``` | You could do this:
```
SELECT SUM(#B.value)
FROM #B
WHERE EXISTS
(
SELECT NULL FROM #C
INNER JOIN #A ON #C.a_id = #A.id
WHERE #B.id = #C.b_id
AND #A.id = 'A1'
)
```
Then you will only sum up the `#B` values where they exists in the other tables
The result will be: 84 | Summing the distinct elements of query result | [
"",
"sql",
"t-sql",
""
] |
I have two tables
```
EMPLOYEE (Fname, Lname, Ssn, Salary, Dno)
DEPARTMENT (Dname, Dno, Location)
```
I want to list the names of all employees making the least in their department
I have come up with this
```
select min(E.Salary) from EMPLOYEE E group by E.Dno;
```
but how do I join the EMPLOYEE table with it an... | Analytic functions would be best but this would also work:
```
select *
from employee e
where salary = (select min(x.salary) from employee x where x.dno = e.dno)
``` | A simple way to do it is to check that no one with a lower salary exists in the same department;
```
SELECT e1.*
FROM employee e1
WHERE NOT EXISTS(
SELECT 1 FROM employee e2 WHERE e1.dno = e2.dno AND e1.salary > e2.salary
);
```
[An SQLfiddle to test with](http://sqlfiddle.com/#!4/d456d/1). | Retrieve the names of employees who is making least in their departments | [
"",
"sql",
"oracle",
""
] |
I have this query
```
SELECT DISTINCT u.fbid, u.name,r.points
FROM users u, players_records r
WHERE u.fbid = r.user_id
ORDER BY r.points DESC LIMIT 5
```
I want to get the top players but only different 5 players, this query is not working it shows duplicated users ids
any help ?
Result for the a... | It sounds like you want the maximum point per user. So you could do it something like this:
```
SELECT
users.fbid,
users.name,
maxRecords.points
FROM
users
JOIN
(
SELECT
MAX(players_records.points) AS points,
players_records.user_id
FROM
play... | You could just select max score and group by user.
```
SELECT u.fbid, u.name, MAX(r.points) max_points
FROM users u, player_records r
WHERE u.fbid = r.user_id
GROUP BY u.fbid, u.name
ORDER BY max_points DESC LIMIT 5
``` | DISTINCT Is not working in inner join | [
"",
"mysql",
"sql",
""
] |
I have this table

What I want to do is that Select the `attr_id` WHERE a DISTINCT `name_en-GB` appears and then SET that selected `attr_id` for that `name_en-GB`
I can do this by writing individual queries but I want to know is there any way I can ... | I have finally done this
```
UPDATE sc_product_phrase
JOIN (
SELECT
`caption`,
min(design_phrase_id) AS minai,
required
FROM
sc_product_phrase WHERE LENGTH(`options`) < 1
GROUP BY
`caption`
) tt ON sc_product_phrase.`caption... | You can do
```
UPDATE table1
SET attr_id = CASE `name_en-GB` WHEN 'Bride Name' THEN 142
WHEN 'Child Grade' THEN 270 END
WHERE `name_en-GB` IN('Bride Name', 'Child Grade')
```
Here is **[SQLFiddle](http://sqlfiddle.com/#!2/d65eb/1)** demo | Issue with updating a table | [
"",
"mysql",
"sql",
""
] |
I have the following sql statement:
```
SELECT MODEL, COLOR, SUM(SALES)
FROM SALES
WHERE MODEL='chevy'
GROUP BY MODEL;
```
When I run this statement, I have an error message saying " "sales.color" must appear in the GROUP BY clause or be used in an aggregate function"
I don't understand why COLOR has to appear in Gr... | Color must appear in the group by because you are doing an aggregate select. Essentially the problem here is it doesn't know what rows to sum the sales across. You are selecting out the sum of sales for each model and the color of each model so you either need to remove the color from the selected columns if you want t... | ```
SELECT MODEL, COLOR, SUM(SALES)
FROM SALES
WHERE MODEL='chevy'
GROUP BY MODEL,COLOR;
```
[SQL Server: Difference between PARTITION BY and GROUP BY](https://stackoverflow.com/questions/2404565/sql-server-difference-between-partition-by-and-group-by) | Aggregation with Group by | [
"",
"sql",
""
] |
Here is my pseudo query:
```
SELECT col1, col2 FROM table WHERE number IN(number1,number2,number3);
```
**EXAMPLE**
```
SELECT name, description FROM products WHERE 5 IN(category_id);
```
NOTE: Let's assume that one of the rows in the table has **category\_id = 2,5,7**
**THE PROBLEM**
my query works if the row ha... | **EDIT** The expression examples in this answer are based entirely on a string context, that is, comparison of character datatypes. These examples do NOT take into account implicit datatype conversions, and the quirky MySQL semantics of string to numeric conversion, e.g. `'2,5,7'+0` evaluates to integer value 2. See th... | [`IN`](http://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_in) works on a *set* of values, not a single comma-separated string value. Each separate *value* supplied to IN is *one element* in the set.
MySQL offers a non-standard [`FIND_IN_SET(str, strlist)`](http://dev.mysql.com/doc/refman/5.7/en/... | Why does num IN("num1,num2") atop at first comma? | [
"",
"mysql",
"sql",
"sql-in",
""
] |
I have a table named **Documents**, with the fields **Document\_ID**(primary key) and **Cluster\_ID** , now i want all the Document\_ID that have same Cluster\_ID, on basis on Document\_ID (passed as parameter), default value of Cluster\_ID is '-1'.
eg: **dbo.Documents**
```
Document ID ******** Cluster_ID
- 1**... | Try this query
```
SELECT
Document_ID,
Cluster_ID
FROM Documents
WHERE Cluster_ID =
(
SELECT
Cluster_ID
FROM Documents
WHERE Document_ID = @Document_ID
)
AND Cluster_ID <> -1
UNION
SELECT
Document_ID,
Cluster_ID
FROM Documents
WHERE Document_ID = @Document_ID
AND Cluster_ID = -1
... | Please try this.
here **@doumentId** is parameter which you need to pass.
```
DECLARE @Cluster_ID int
SET Cluster_ID = (
SELECT Cluster_ID
FROM
FROM Documents
WHERE Document_ID = @documentId
)
IF Cluster_ID > 0
BEGIN
SELECT *
FROM Documents
WHERE Cluster_ID = (
SELECT Cluster_ID
... | Query to get records from table on basis of one field and to check that if the field is not -1 | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I keep getting the following message every time I try to run this code in oracle. The code is as follows:
```
DROP TABLE movie;
CREATE TABLE movie (movie_id NUMBER(5) PRIMARY KEY,
title VARCHAR2(45) NOT NULL,
description VARCHAR2(250) NOT NULL,
released_by NUMBER(3) NOT NULL,
released_on DATE NOT NULL);
INSERT INTO ... | Escape single quotes:
```
INSERT INTO movie (movie_id, title, description, released_by, released_on)VALUES('4', 'Godzilla', 'The legendary tale of Godzilla comes roaring back to life. This time, it''s the modern era, and Godzilla is a giant lizard who has been made fearsome through the interference of radiation.', '1'... | Try Oracle's quoting mechanisms :
The mechanism is invoked with a simple "q" in PL/SQL only.
The syntax is q'[...]', where the "[" and "]" characters can be any of the following as long as they do not already appear in the string.
> •!
>
> •[ ]
>
> •{ }
>
> •( )
>
> •< >
Here For Example ,
```
INSERT INTO movie (m... | ORA-01756: quoted string not properly terminated when I try to execute my code | [
"",
"sql",
"oracle",
"insert",
""
] |
I had a select statement which selected the oldest set of data in a table with an Inner Join
```
SELECT DateAndTime
,Val
,NumIndex
,TagName
,floattable.TagIndex
FROM taglogging.floattable
INNER JOIN tagtable ON tagtable.TagIndex = floattable.TagIndex
WHERE DateAndTime = oldest;
```
This works well and... | In your second query, the select statement should have only one column name in respect of `Val` column.
Your query should be like this:
```
DELETE from taglogging.floattable WHERE Val IN
(SELECT Val
FROM taglogging.floattable
INNER JOIN tagtable ON tagtable.TagIndex = floattable.TagIndex
W... | `Operand should contain 1 column(s)` tells everything. Btw, this is not a syntax error, it is a semantic error, so your syntax has to be correct.
MySQL is complaining `SELECT DateAndTime, Val, NumIndex, TagName, floattable.TagIndex` is fetching more than one column. The `IN` operator requires exactly ONE column to be ... | MySQL Syntax error on a delete from a select set? | [
"",
"mysql",
"sql",
"select",
"dataset",
"syntax-error",
""
] |
I have a procedure that outputs a list of rows with your standard basic `SELECT` statement using a few `joins` and `where` clauses.
```
Employee Value
--------------------------
Tommy Elliott Damage
Tommy Elliott Overage
Tommy Elliott Damage
Tommy Elliott Shortage
Tommy Elliott Damage
Tommy Elliott ... | The analytic version of `COUNT()` can add these as column values *and* preserve the detail you want. Assuming your query starts like this:
```
SELECT
Employee,
Value
FROM ... and the rest of your query
```
... add the counts like this:
```
SELECT
Employee,
Value,
COUNT(*) OVER (PARTITION BY Employee) AS Th... | ```
select T.Employee, COUNT(T.Employee)
from
(
your query
)T
group by T.Employee
``` | Count the number of occurrences in a procedure | [
"",
"sql",
"sql-server",
""
] |
```
SELECT * FROM #TempMatrixTable
WHERE TIME >='07:00:00' and TIME <= '23:00:00'
ORDER BY dateperiod
```
In the above code am fetching data from 7 to 23 for each date its working fine.But when i try to fetch the data from 23 to 7 reverse of it am not able to get the result.Please provide solutio... | When you are getting the times between 23 and 07, you are actually getting two time intervals; between 23 and 24, and between 00 and 07:
```
select
*
from
#TempMatrixTable
where
TIME >='00:00:00' and TIME < '07:00:00' or
TIME >='23:00:00' and TIME <= '23:59:99.9999'
order by
dateperiod
```
Naturally you do... | I think you want `or` instead of `and`:
```
SELECT *
FROM #TempMatrixTable
WHERE TIME >='23:00:00' OR TIME <= '07:00:00'
ORDER BY dateperiod;
``` | Fetching each date data for a specified time imterval in sql | [
"",
"sql",
""
] |
How can I remove the Status = Pending with the Date of less than the currentdate in my query... This should be a select statement
```
Status Date
Pending 9/5/2014
Pending 9/30/2014
Complete 8/28/2014
Error 8/20/2014
``` | Since you say you wish to remove the data where Status is 'Pending' before the current date, I assume you want to delete that data. Here's the deletion query.
```
DELETE FROM my_table
WHERE status = 'Pending'
AND date < CAST(GETDATE() AS DATE);
```
However, since you mention that you need a select statement, here's t... | You can use
```
SELECT status, date FROM Test
WHERE status <> 'Pending'
AND date < CAST(GETDATE() AS DATE)
```
<http://sqlfiddle.com/#!6/755f0/1> | How can I remove the Status = Pending with the Date of less than the currentdate in a select statement | [
"",
"sql",
"t-sql",
"sybase",
""
] |
My stored procedure is trying to write a record in to a database on another Server. The statement is here:
```
IF @Builds > 0
BEGIN
SET @DPU = @Failures / @Builds
INSERT INTO SQL05.ManufacturingPortal.dbo.OPC.WriteRequests (ID, RegisterID, Value, RequestedDate, IsCompleted)
VALUES(@PLCID, 'F... | Correct four-part table name is server.database.schema.tablename - you have some excess parts there.
Looks like table name is OPC.WriteRequests? If yes, then you have to use brackets: `SQL05.ManufacturingPortal.dbo.[OPC.WriteRequests]`
But maybe you just have some part of name incorrect? | The accepted answer is correct, in that the example given literally has too many prefixes. In the example, one prefix had a dot in its name, and needs to be set off by square brackets (or better yet, have a name that conforms to convention).
In my case, it actually wanted to be run on the server where the INTO table w... | The object name contains more than the maximum number of prefixes. The maximum is 3 | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a question related to SQL.
Can I display a custom message in MySQL phpMyAdmin, something like this:
```
SELECT * FROM table_name
PRINT 'The message that I want to write!';
```
I tried to do it with PRINT syntax, because I found something like that, but it doesn't work. Do you have some ideas? | Put the text in the `SELECT` statement
```
SELECT *, 'PRINT' FROM foo;
```

If you're wanting to print a long message, and want a different column name, simply use an alias by using `AS`.
```
SELECT *, 'The message i want to print' AS msg FROM foo;... | You can simulate a print with the select statement like this:
```
SELECT 'some text'
``` | Can I display a message in MySQL? | [
"",
"mysql",
"sql",
""
] |
I need to update a table with pre-calculated values from tables where data can be added/updated/deleted.
I could use
```
insert into precalculated(...)
select ... from ...
on duplicate key update ...
```
to add/update the pre-calculated table but is there an optimized method to delete the obsolete rows ? | I may have found my solution using rename.
so basically, I will do a simple insert select to the temporary table and then
```
rename precalculated to precalculated_temprename, precalculated_temp to precalculated, precalculated_temprename to precalculated_temp;
truncate precalculated_temp;
```
need some tests but it ... | I think you should create a stored procedure that deletes the data of your related tables if and only if the records fulfill a condition.
There's not enough information in your question to design the procedure, but I can give you a little example:
```
delimiter $$
create procedure delete_orphans()
begin
declare i... | insert ... select ... on duplicate key update + delete obsolete rows | [
"",
"mysql",
"sql",
"insert-update",
""
] |
I have two MySQL queries that are finding MAX() values from nearly identical queries. I was hoping there was a way to combine the queries for better performance.
```
SELECT name, MAX(version) AS highest
FROM publish
WHERE name IN ('alpha', 'beta') AND deprecated = TRUE
GROUP BY name;
SELECT name, MAX(version) AS clos... | You can use conditional aggregation to combine your queries
```
SELECT name, MAX(case when open = FALSE then version end) AS closed,
MAX(case when deprecated = TRUE then version end) AS highest
FROM publish
WHERE name IN ('alpha', 'beta')
GROUP BY name;
``` | You can try UNION
```
SELECT name, MAX(version) AS highest
FROM publish
WHERE name IN ('alpha', 'beta') AND deprecated = TRUE
GROUP BY name
UNION ALL
SELECT name, MAX(version) AS closed
FROM publish
WHERE name IN ('alpha', 'beta') AND open = FALSE
GROUP BY name;
```
But an optimized solution would be to use CASE (for... | Combine sql queries that want different filtered max values | [
"",
"mysql",
"sql",
""
] |
So we have the following relational database for movie ratings:
```
mysql> select * from ratings;
+-----+-----+------+
| uid | mid | rid |
+-----+-----+------+
| u1 | m1 | 4 |
| u1 | m2 | 3 |
| u2 | m2 | 5 |
| u2 | m3 | 4 |
| u3 | m1 | 4 |
| u3 | m2 | 5 |
| u3 | m3 | 2 |
+-----+--... | ```
SELECT R.uid from ratings R
JOIN
(SELECT distinct mid
FROM ratings
WHERE uid='u1') T
ON R.mid = T.mid
group by R.uid
having count(R.mid) = 2;
+-----+
| uid |
+-----+
| u1 |
| u3 |
+-----+
2 rows in set (0.15 sec)
``` | A query of this form will return the specified result.
```
SELECT o.user_id
FROM ( SELECT COUNT(DISTINCT u.movie_id) AS cnt
FROM ratings u
WHERE u.user_id = '1234'
) c
CROSS
JOIN ( SELECT m.user_id
, m.movie_id
FROM ratings m
WHERE m.user_id = '1234'... | Complex query: find all users who rated at least 2 common movies rated by u1 | [
"",
"mysql",
"sql",
""
] |
all. I had a SQL Server table with a column named "Name". I want to query the rows if the "Name" substract the last char are in a list.
Here is my SQL query but it tell me error: Invalid length parameter passed to the LEFT or SUBSTRING function.
```
select * from MyTable where substring(Name, 1, len(Name) - 1) in ('AB... | You should check the length of your "Name" first, if the name is empty, substring(Name, 1, len(Name) - 1) will throw error. | How about doing something like this?
```
select t.*
from mytable t
where name like 'ABC_' or name like 'DEF_';
``` | How to: substring of a column in a list | [
"",
"sql",
"sql-server",
"substring",
""
] |
I created a table using the following query:
```
CREATE Table articulo
(
id_art int NOT NULL,
nom_art varchar (25) DEFAULT 'XXXXXXXXXXXXX',
prec_art decimal (10,5) DEFAULT 0.000,
peso_art decimal (10,5),
existencia float,
color_art int, CONSTRAINT chk_color1 CHECK (color_art between 0 and 20),
um_art varchar (1... | Check constraint does not work work as expected in mysql. check the bug report <http://bugs.mysql.com/bug.php?id=3464>.
You can have an alternative solution like follows to set a default value
```
CREATE TRIGGER trig_color_art_check BEFORE INSERT ON articulo
FOR EACH ROW
BEGIN
IF (NEW.color_art < 0 OR NEW.color_art... | In many cases, you can replace a CHECK constraint with a table and a foreign key constraint. This case is one of them.
```
create table art_color (
color_art integer not null,
primary key (color_art)
);
insert into art_color values
(0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10),
(11), (12), (13), (14), (1... | MySQL Constraint Check | [
"",
"mysql",
"sql",
"constraints",
""
] |
I want to display the department no. and the number of employees in each department from `EMP` table in a single row. I had one query which display the result in separate rows.
```
select deptno, count(*) from emp
group by deptno;
Dptno Count(*)
10 5
20 3
30 4
```
I want to display the result as a ... | You can try this -
**Schema**
```
DECLARE @emp TABLE ([deptno] int NULL, [deptcount] int NULL);
INSERT @emp ([deptno], [deptcount]) VALUES (10, 5), (20, 3), (30, 4);
```
**Query**
```
SELECT STUFF((
SELECT ' ' + CAST([deptno] AS VARCHAR) + ' ' + CAST([deptcount] AS VARCHAR)
FROM @emp
FOR XML P... | Since pivot doesn't support several aggregates in SQL Server:
```
with t as (
select 10 id, 15 su union all
select 10 id, 10 su union all
select 10 id, 5 su union all
select 20 id, 135 su union all
select 20 id, 100 su union all
select 20 id, 15 su union all
select 30 id, 150 su union all
select 30 id, 1000 su ... | Multiple rows show in a single row using query in sql? | [
"",
"sql",
"sql-server",
""
] |
I have a question which looks easy but I can't figure it out.
I have the following:
```
Name Zipcode
ER 5354
OL 1234
AS 1234
BH 3453
BH 3453
HZ 1234
```
I want to find those rows where the ID does not define clearly one row.
So here I want to see:
```
OL 1234
AS 1234
HZ 1234
``... | I think this is what you want
```
select zipcode
from yourTable
group by zipcode
having count(*) > 1
```
It selects the zipcodes associated to more than one record
to answer your updated question:
```
select zipcode
from
(
select name, zipcode
from yourTable
group by name, zipcode
)
group by zipcode
having co... | Try this:
```
select yt.*
from YOUR_TABLE yt
, (select zipcode
from YOUR_TABLE
group by zipcode
having count(*) > 1
) m
where yt.zipcode = m.zipcode
``` | Find not unique rows in Oracle SQL | [
"",
"sql",
"oracle",
"having-clause",
""
] |
I have a calendar table which stores rows of dates and an indication of wether that date is a holiday or working day.
How can I select the date that is 5 working days into the future from the `2014-12-22` so the selected date will be `2014-12-31`
```
Date_Id Date_Date Date_JDE Is_WorkingDay
20141222 2014-... | You can use a [CTE](http://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx) like this...
```
;WITH cteWorkingDays AS
(
SELECT Date_Date, ROW_NUMBER() OVER (ORDER BY Date_Date) as 'rowNum'
FROM TableName
WHERE Is_WorkingDay = 1
and Date_Date > '20141222' -- this will be a param I suppose
)
SELECT... | ```
...;
WITH DatesCTE AS
(
SELECT Date_Id,
Date_Date,
Date_JDE,
Is_WorkingDay,
ROW_NUMBER() OVER(ORDER BY Date_Date) AS rn
FROM DatesTable
WHERE Is_WorkingDay = 1
AND Date_Date > '2014-12-22'
)
SELECT Date_Date
FROM DatesCTE
WHERE rn = 5
```
**... | TSQL Calendar table, count 10 workings days from date | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Say there is a database for students and professors (a very simple one) and the relational database is the following:
```
GradStudent (_id_, name, gradStuff)
UndergradStudent (_id_, name, underGradStuff)
Professor (_id_, name)
Teaches(_prof_id_, _stud_id_)
```
Considering that the relational database above is meant t... | > I cannot figure out how to make a foreign key from two different tables.
You mean, a foreign key to/referencing two different tables. But there is no such foreign key in this design.
We declare an SQL FOREIGN KEY for a table to say that (ie to tell the DBMS that) the values for a list of columns are also values of ... | If by "fetch the student id for the Teaches table", you mean you want Teaches.stud\_id to be a FK that references "GradStudent or Undergradstudent as is the case", you can't. The target of a FK must be a key of a table that is not a view. You have no such table, ergo you have no such key either.
Only way I see is to c... | How to implement total disjoint specialization in database? | [
"",
"sql",
"database",
"relational-database",
""
] |
I have 2 tables, `article` and `image`.
In order to extract all articles of a particular user, I need to:
* query all the articles
`SELECT * FROM article WHERE userid=100;`
* then loop through these articles, and extract their images with:
`SELECT * FROM image WHERE articleid = currentArticleId;`
How can I ach... | You could use a join or a subquery.
---
[Subquery:](http://dev.mysql.com/doc/refman/5.0/en/subqueries.html)
The subquery (The second query contained in brackets) will be executed and the ID(s) that are returned will be used to identify which rows from the initial query to grab. So if you imagine the subquery returns... | You can read more about select statements, joins, etc. here:
[MySQL Reference - Select Syntax](http://dev.mysql.com/doc/refman/5.0/en/select.html)
```
SELECT *
FROM image
JOIN article ON article.id = image.articleid;
``` | select from 2 tables in a single query | [
"",
"mysql",
"sql",
""
] |
I want to create a condition in where clause, that can imitate left join. For example:
```
From Table1, Table2 Where table1.ID *= table2.ID
```
needs to be written as
```
From Table1, Table2
Where Table1.ID = Table2.ID AND (some condition to get the rows from table1 where match does not exist)
```
I want to do this... | In general, a `where` clause cannot increase the number of rows in the result set. So, you cannot formally reproduce a `left join` in the `where` clause.
That said, it is possible that this would do what you want:
```
From Table1, Table2
Where (Table1.ID = Table2.ID or
not exists (select 1 from table2 t2 where... | ```
CREATE TABLE Table1
(`Name` varchar(5), `Age` int)
;
INSERT INTO Table1
(`Name`, `Age`)
VALUES
('PVJ', 10),
('EPF', 12),
('CISCO', 13)
;
CREATE TABLE Table2
(`Name` varchar(3), `Age` int)
;
INSERT INTO Table2
(`Name`, `Age`)
VALUES
('PVJ', 10),
('EPF', 12),
('DVF', 13)
se... | Creating a left join condition using where clause in sql | [
"",
"mysql",
"sql",
"left-join",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.