Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a table named WORKOUTS having column named "install\_time" and "local\_id". Both are having column type integer. They are UNIQUE keys .I have written two queries like below :
```
SELECT * from workouts where install_time = 123456 and local_id > 5
SELECT * from workouts where install_time = 987643 and local_id ... | It depends what you mean by **"combine both these queries"**. If you want a result set where the results of both the above queries are returned, you can try the `OR` operator. The following assumes that the `date` field is the same for both the `local_id`s.
```
SELECT * FROM workouts
WHERE date = xyz
AND (
(install... | ```
SELECT *
FROM workouts
WHERE
(install_time = 123456 AND local_id > 5 AND date = xyz)
OR
(install_time = 987643 AND local_id > 19 AND date = xyz)
```
Also be careful when using the OR keyword. You have to put your parenthesis carefully.
Here is more info on the subject <http://www.w3schools.com/sql... | Combining two SELECT queries from same table but different WHERE clause | [
"",
"sql",
"postgresql",
""
] |
My goal is to test if the grp's generated by one query, are the same grp's as the output of the same query. However, when I change a single variable name, I get different results.
Below I show an example of the **same query** where we know the results are the same. However, if you run this group, you will find one que... | The problem is nondeterminism in your row numbering.
There are many examples in this table where `(word_count * word_count * corpus_date)` is the same for several corpuses. So when you partition by `word` and order by `test2`, the ordering you use for assigning row numbers is nondeterministic.
When you run the same s... | I noticed you are always asking tough questions and then you are tough on accepting or even voting for answer.
That’s Ok! And I want to try again so let’s go to subject:
Looks like using aliases in the same SELECT statement is undocumented and not supported
Note below in [SELECT clause](https://cloud.google.com/bigque... | Google Bigquery inconsistent when variable names changes in ORDER BY clause | [
"",
"sql",
"google-bigquery",
"partitioning",
"ranking",
"in-operator",
""
] |
The question I am working on is as follows:
What is the difference in the amount received for each month of 2004 compared to 2003?
This is what I have so far,
```
SELECT @2003 = (SELECT sum(amount) FROM Payments, Orders
WHERE YEAR(orderDate) = 2003
AND Payments.customerNumber = Or... | I cannot test this because I don't have your tables, but try something like this:
```
SELECT a.orderMonth, (a.orderTotal - b.orderTotal ) AS Diff
FROM
(SELECT MONTH(orderDate) as orderMonth,sum(amount) as orderTotal
FROM Payments, Orders
WHERE YEAR(orderDate) = 2004
AND Payments.customerNumber = Ord... | Q: How do I subtract two declared variables in MySQL.
A: You'd first have to DECLARE them. In the context of a MySQL stored program. But those variable names wouldn't begin with an at sign character. Variable names that start with an at sign **@** character are user-defined variables. And there is no DECLARE statement... | How do I subtract two declared variables in MYSQL | [
"",
"mysql",
"sql",
""
] |
I need to check if the format stored in an SQL table is YYYY-MM-DD. | try this way
```
SELECT CASE WHEN ISDATE(@string) = 1
AND @string LIKE '[1-2][0-9][0-9][0-9]/[0-1][0-9]/[0-3][0-9]'
THEN 1 ELSE 0 END;
```
@string is date. | You dont store specific format (i think ms sql stores it as two integers), you select your format for output. And when I say you select, I mean you have your default (mostly set automatically when installing MS SQL or whatever you use based on your country, timezone, etc - you can change this) and those which you choos... | Check if format is YYYY-MM-DD | [
"",
"sql",
"sql-server",
""
] |
Here is my testing table data:
Testing
```
ID Name Payment_Date Fee Amt
1 BankA 2016-04-01 100 20000
2 BankB 2016-04-02 200 10000
3 BankA 2016-04-03 100 20000
4 BankB ... | Here is another method, but I think you have to run tests on your data to find out which is best:
```
SELECT
t.*,
CASE WHEN EXISTS(
SELECT * FROM testing WHERE id <> t.id AND Name = t.Name AND Fee = t.Fee AND Amt = t.Amt
) THEN 'Y' ELSE 'N' END SameDataExistYN
FROM
testing t
;
``` | There are several approaches, with differences in performance characteristics.
One option is to run a correlated subquery. This approach is best suited if you have a suitable index, and you are pulling a relatively small number of rows.
```
SELECT t.id
, t.name
, t.payment_date
, t.fee
, t.amt
... | How do I Compare columns of records from the same table? | [
"",
"mysql",
"sql",
"subquery",
"self-join",
"nested-select",
""
] |
I have this query which basically goes through a bunch of tables to get me some formatted results but I can't seem to find the bottleneck. The easiest bottleneck was the `ORDER BY RAND()` but the performance are still bad.
The query takes from 10 sec to 20 secs without `ORDER BY RAND()`;
```
SELECT
c.prix AS prix,... | You're searching for dates in a very suboptimal way. Try this.
```
... c.datePub >= STR_TO_DATE('01-04-2016', '%d-%m-%Y')
AND c.datePub < STR_TO_DATE('30-04-2016', '%d-%m-%Y') + INTERVAL 1 DAY
```
That allows a range scan on an index on the `datePub` column. You should create a compound index for that table on `... | To begin with you have quite a lot of indexes but many of them are not useful. Remember more indexes means slower inserts and updates. Also mysql is not good at using more than one index per table in complex queries. The following indexes have a cardinality < 10 and probably should be dropped.
```
IDX_...E88B
IDX....6... | MySQL Slow query ~ 10 seconds | [
"",
"mysql",
"sql",
""
] |
I have Below Table named session
```
SessionID SessionName
100 August
101 September
102 October
103 November
104 December
105 January
106 May
107 June
108 July
```
I executed the following query I got the output as below.
```
Select SessionID... | I'd use a `case` expression, like:
```
order by case SessionName when 'August' then 1
when 'September' then 2
...
when 'Juty' then 12
end
```
August has 1 because "*in the application logic a session started with august*", easy to ... | To avoid any hassel with culture dependencies, you might get the month's index out of sys languages with a query like this:
(I'd eventually create a TVF from this and pass in the `langid` as parameter)
```
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) MyMonthIndex
,Mnth.value('.','varchar(100)') AS MyMonth... | Order By Month Name in Sql-Server | [
"",
"sql",
"sql-server",
"t-sql",
"sql-order-by",
""
] |
I have a subset of records that look like this:
```
ID DATE
A 2015-09-01
A 2015-10-03
A 2015-10-10
B 2015-09-01
B 2015-09-10
B 2015-10-03
...
```
For each ID the first minimum date is the first index record. Now I need to exclude cases within 30 days of the index record, and any record with a date greater than ... | working like in your example, #test is your table with data:
```
;with cte1
as
(
select
ID, Date,
row_number()over(partition by ID order by Date) groupID
from #test
),
cte2
as
(
select ID, Date, Date as DateTmp, groupID, 1 as getRow from cte1 where groupID=1
union all
select
... | ```
select * from
(
select ID,DATE_, case when DATE_DIFF is null then 1 when date_diff>30 then 1 else 0 end comparison from
(
select ID, DATE_ ,DATE_-LAG(DATE_, 1) OVER (PARTITION BY ID ORDER BY DATE_) date_diff from trial
)
)
where comparison=1 order by ID,DATE_;
```
Tri... | How to get next minimum date that is not within 30 days and use as reference point in SQL? | [
"",
"sql",
"sql-server",
"loops",
"while-loop",
""
] |
I need to create table from the return schema of sql query. Here, sql query has multiple joins.
Example - In below scenario, create table schema for column 'r' & 't'.
```
select a.x as r b.y as t
from a
JOIN b
ON a.m = b.m
```
I can not use 'select into statement' because I get an input sql select statement and need ... | If I'm reading your problem correctly, you're getting SQL from an external source and you want to run that into a table (maybe with data, maybe without). This should do:
```
use tempdb;
declare @userSuppliedSQL nvarchar(max) = N'select top 10 * from Util.dbo.Numbers';
declare @sql nvarchar(max);
set @sql = concat('
... | Use the into clause here. Like
```
Select col1, col2, col3
into newtable
from old table;
select a.x as r b.y as t
into c
from a
JOIN b ON a.m = b.m
``` | Create Table using Schema of SQL Query | [
"",
"sql",
"sql-server",
""
] |
I have a table looks like this:
```
method year segment
ABC 2014 AB
CAB 2014 AB
PAU 2013 AB
COR 2015 CD
PRK 2016 IK
```
All segments should have same year. So I need to identify how many of them has different year. Its a mistake.
Result should be
```
method year ... | let's say our table name is "MyTable"
this query will report segment with more then 1 year:
```
select distinct segment from MyTable
Group by segment
having count(distinct year)>1
```
then if you want all the other columns data you can join this result with the table itself
```
select Mytable.* from MyTable join (
... | Try this
```
SELECT *
FROM (
SELECT *,ROW_NUMBER() OVER(PARTITION BY [YEAR]
ORDER BY SEGMENT DESC) ROW_NO FROM @TABLE1
) T WHERE row_no <> 1
``` | sql one segment has many methods but all of them should have one date how to check for the ones that dont have | [
"",
"sql",
"sas",
""
] |
I want to get a part of text from my field `description`
Could someone offer some advice?
The whole string is `'Version100][BuildNumber:666][SubBuild:000]'` and the build number is what I want to single out (however the number may change).
I have tried `SUBSTRING` with `CHARINDEX` but I can't seem to figure it out.
... | You can try this:
```
SELECT SUBSTRING([description],CHARINDEX('BuildNumber:',[description])+12,
CHARINDEX(']',[description], CHARINDEX('BuildNumber:',[description]))
-(CHARINDEX('BuildNumber:',[description])+12))
FROM YOURTABLE
``` | little long, but you could do this.
```
DECLARE @Description VARCHAR(MAX)= '[Version100][BuildNumber:666][SubBuild:000]'
SELECT LEFT(STUFF(@Description, 1, PATINDEX('%BuildNumber%', @Description) + 11, '' )
,PATINDEX('%]%', STUFF(@Description, 1, PATINDEX('%BuildNumber%', @Description) + 11, '' )) - 1)
``... | How can I find part of a string between two words? | [
"",
"sql",
"sql-server",
""
] |
I have this table:
```
// votes
+----+---------+---------+
| id | user_id | post_id |
+----+---------+---------+
| 1 | 12345 | 12 |
| 2 | 12345 | 13 |
| 3 | 52344 | 12 |
+----+---------+---------+
```
Also this is a part of my query:
```
EXISTS (select 1 from votes v where u.id = v.user_id an... | You do not need two indexes serving similar purpose. Only one of them would be used during a `select` operation, and both will have to be modified on `insert, update` and `delete`. These are unnecessary overheads. Go with the unique index, since it serves both the purposes. A range scan is almost guaranteed when using ... | if you're trying to prevent multiple votes from the same `user_id` to the same `post_id`, then why don't you use a [`UNIQUE` constraint](http://www.w3schools.com/sql/sql_unique.asp)?
```
ALTER TABLE votes
ADD CONSTRAINT uc_votes UNIQUE (user_id,post_id)
```
with regards to whether you should remove your index, you sh... | A unique can be used as index? | [
"",
"mysql",
"sql",
"indexing",
""
] |
```
table: users
id
table: tasks
id
table: tasks_users
user_id
task_id
is_owner
```
I have a `users` table, a `tasks` table and a pivot table `tasks_users`.
I would like to select all the users given a `task_id` and ordering by `tasks_users.is_owner`.
How would I accomplish this? | Try something like this ...
```
select u.users
from users u
join tasks_users tu
on u.id=tu.user_id
join tasks t
on t.id=tu.task_id
where t.task_id=your_id
order by tu.is_owner
``` | I think it is simple
```
select u.id
from users u
inner join tasks_users tu on u.id = tu.user_id
inner join tasks t on t.id = tu.task_id
order by tu.is_owner;
``` | Using JOINS, ORDER BY, and pivot tables | [
"",
"mysql",
"sql",
"database",
"join",
""
] |
I have only been using PhpStorm a week or so, so far all my SQL queries have been working fine with no errors after setting up the database connection. This current code actually uses a second database (one is for users the other for the specific product) so I added that connection in the database tab too but its still... | So the short answer is that it cant read the table name as a variable even though its set in a variable above. I thought PhpStorm could work that out. The only way to remove the error would be to either completely turn off SQL inspections (obviously not ideal as I use it throughout my project) or to temporarily disable... | You can set the SQL resolution scope in `File -> Settings -> Languages & Frameworks -> SQL Resolution Scopes`.
[](https://i.stack.imgur.com/dT7C9.png)
This allows you to provide a default for the entire project and you can optionally define specific ... | PhpStorm unable to resolve column for multiple database connections | [
"",
"sql",
"oracle",
"phpstorm",
""
] |
How to get Oracle database version from **sqlplus**, Oracle SQL developer, SQL Navigator or other IDE? | Execute this statement from SQL\*Plus, SQLcl, Oracle SQL Developer, SQL Navigator or other IDE:
```
select * from product_component_version
```
And you'll get:
```
PRODUCT VERSION VERSION_FULL STATUS
-------------------------------------- ---------- ------------ ----------
Oracle Da... | Try running this query in SQLPLUS -
```
select * from v$version
``` | How to get Oracle database version? | [
"",
"sql",
"oracle",
"version",
""
] |
I have a table that contains 4 columns. I need to remove some of the rows based on the Code and ID columns. A code of 1 initiates the process I'm trying to track and a code of 2 terminates it. I would like to remove all rows for a specific ID when a code of 2 comes after a code of 1 and there is not an additional code ... | You can get the ids using logic like this:
```
select t.id
from t
group by t.id
having max(case when code = 2 then date end) > min(case when code = 1 then date end) and -- code 2 after code 1
max(case when code = 2 then date end) > max(case when code = 1 then date end) -- no code 1 after code2
```
It is then e... | The approach I took was to add up the Code per each ID. If it equals 3 exactly, it should be removed.
```
;WITH keepID as (
Select
ID
,SUM(code) as 'sumCode'
From #testInit
Group by ID
HAVING SUM(code) <> 3
)
Select *
From #testInit
Where ID IN (Select ID from keepID)
```
Your post showed keeping ID = 1 whic... | Conditional Row Deleting in SQL | [
"",
"sql",
"sql-server-2012",
"conditional-statements",
"sql-delete",
"delete-row",
""
] |
This potentially might be too large of a question for a complete solution, and I've got a bit of a strange set up. I'm using HP OO to create a text-based RPG just to practice getting used to database design on this platform.
So it's basically a flow script that runs once. When the script starts, a player (user) is cre... | There's nothing *guaranteeing* that the highest value in an identity column is the most recently created record. You should add a `date_created` column to your table and give it a default value of the current date and time (`current_timestamp` for a `datetime2` field). That actually does what you want.
OK, your questi... | ```
SELECT row FROM table WHERE id=(
SELECT max(id) FROM table
)
this should work
```
Make sure the id is unique (auto increments? great!) | Find a value based on the most recently created row in a table (SQL Server) | [
"",
"sql",
"sql-server",
""
] |
I am trying to select \* tasks that are not due. That been said, anything thats past this exact date **and time** should be selected taking in consideration that I have a separate columns for date and time.
Currently I am using this where **it does not** select all instances of today:
```
SELECT * FROM `tasks` WHERE ... | To get the behavior it seems like you're looking for, you could do something like this:
```
SELECT t.* FROM `tasks` t
WHERE t.`due_date` >= DATE(NOW())
AND ( ( t.`due_date` = DATE(NOW()) AND t.`due_time` >= TIME(NOW()) )
OR ( t.`due_date` > DATE(NOW()) )
)
```
The first cut is the compari... | ```
SELECT * FROM `tasks` WHERE `due_date` >= DATE(NOW()) AND `due_time` >= TIME(NOW());
```
DATE() extracts the year-month-date part, and TIME() the hours:mins:secs part
<http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html> | SQL: Select * WHERE due date and due time after NOW() without DATETIME() | [
"",
"mysql",
"sql",
"date",
"datetime",
"select",
""
] |
I have a query -
```
SELECT * FROM TABLE WHERE Date >= DATEADD (day, -7, -getdate()) AND Date <= getdate();
```
This would return all records for each day except day 7. If I ran this query on a Sunday at 17:00 it would only produce results going back to Monday 17:00. How could I include results from Monday 08:00. | Try it like this:
```
SELECT *
FROM SomeWhere
WHERE [Date] > DATEADD(HOUR,8,DATEADD(DAY, -7, CAST(CAST(GETDATE() AS DATE) AS DATETIME))) --7 days back, 8 o'clock
AND [Date] <= GETDATE(); --now
``` | That's because you are comparing date+time, not only date.
If you want to include all days, you can trunc the time-portion from `getdate()`: you can accomplish that with a conversion to **date**:
```
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -convert(date, getdate())
AND Date <= convert(date, getdate());
... | Getdate() functionality returns partial day in select query | [
"",
"sql",
"sql-server",
""
] |
I am executing this query in Oracle. I have added the screenshots of my data and the returned results but the returned result is wrong. It is returning 1 but it should return 0.52. Because the customer(see in attached screenshot) have codes 1,2,4,31 and for 1,2,4 he should get 0.70 value and for 31 he should get 0.75 a... | According to desired reasult comment, try this
```
SELECT [id]
,[name]
, r = max(CASE WHEN [code] IN (1,2,4) then 100 else 0 end)
+ max(CASE WHEN [code] IN (8) then 80 else 0 end)
FROM
-- your table here
(values (1, 'ali',4)
,(1, 'ali',1)
,(1, 'ali',8)
) as t(id, name,co... | You're **already** selecting from the `testcode` table - no need to do any subqueries in your `CASE` expression - just use this code:
```
SELECT
[id], [name],
SUM(CASE
WHEN [code] IN (1, 2, 4)
THEN 100
WHEN [code] = 8
THEN 80
END) AS [total]
FROM... | SQL Error "Cannot perform an aggregate function on an expression containing an aggregate or a sub query." | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2005",
"sql-server-2008-r2",
""
] |
I am working on performance tuning all the slow running queries. I am new to Oracle have been using sql server for a while. Can someone help me tune the query to make it run faster.
```
Select distinct x.a, x.b from
from xyz_view x
where x.date_key between 20101231 AND 20160430
```
Appreciate any help or suggestio... | First, I'd start by looking at why the `DISTINCT` is there. In my experience many developers tack on the `DISTINCT` because they know that they need unique results, but don't actually understand why they aren't already getting them.
Second, a clustered index on the column would be ideal **for this specific query** bec... | I would also add if you are pulling from a VIEW, you should really investigate the design of the view. It typically has a lot of joins that may not be necessary for your query. In addition, if the view is needed, you can look at creating an indexed view which can be very fast. | How to Performance tune a query that has Between statement for range of dates | [
"",
"sql",
"sql-server",
"oracle",
"performance",
"query-tuning",
""
] |
I'm looking for any way to be able to round or trunc the numbers to 2 digits after comma. I tried with `round`, `trunc` and `to_char`. But didn't get what I wanted.
```
select round(123.5000,2) from dual;
select round(123.5000,2) from dual;
```
Works fine, but when I have zero as second digit after comma, I get only ... | You can use [the `FM` number format modifier](http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements004.htm#SQLRF00216) to suppress the leading spaces, but note that you also then need to use `.00` rather than `.99`, and you may want the last element of the format model before the decimal point to be a zero... | Have you tried with a cast operation?
You can try for example with this, obviously substituting 30,2 with your desired precision.
```
SELECT CAST (someNumber AS DECIMAL(30,2)) FROM dual
```
You can find the documentation of the cast operation for the oracle sql [here](https://docs.oracle.com/javadb/10.8.3.0/ref/rref... | Rounding numbers to 2 digits after comma in oracle | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
So I have a situation where a table `Partners` has a one-to-one relationship with a table called `Regions` and also a one-to-many relationship with the same table through an intersection table called `Destinations`. My nice naming conventions below should help you figure out what I mean.
```
Regions
==========... | You need another `join`:
```
SELECT p.name AS partner_name,
rd.name AS partner_region,
rd.name AS destination_region
FROM Partners p INNER JOIN
Regions rp
ON p.region_id = rp.id INNER JOIN
Destinations d
ON p.id = d.partner_id INNER JOIN
Regions rd
ON d.region_id = rd.id;
... | You'll need to add another join from Destinations to Regions again:
```
SELECT Partners.name AS partner_name,
Regions.name AS partner_region,
Regions2.name AS destination_region
FROM
Partners INNER JOIN Regions ON Partners.region_id=Regions.id
INNER JOIN Destinations ON Pa... | How can I join on a table twice and reference a column name differently each time? | [
"",
"sql",
"sql-server",
"t-sql",
"database-design",
""
] |
I have a messages table that looks something like this:
```
| id | sender_id | recipient_id |
|-------------------|---------------| ...
| 1 | 23 | 20 |
| 2 | 11 | 5 | ...
| 3 | 20 | 23 |
| 4 | 23 | 20 | ...
| 5 | 7 ... | You can use `ROW_NUMBER`:
`ONLINE DEMO`
```
WITH CTE AS(
SELECT *,
ROW_NUMBER() OVER(
PARTITION BY
CASE WHEN sender_id < recipient_id THEN sender_id ELSE recipient_id END,
CASE WHEN sender_id > recipient_id THEN sender_id ELSE recipient_id END
ORDER... | ```
; WITH CTE(ID,SENDER_ID, RECIEPENT_ID) AS
(
SELECT 1,23,20 UNION
SELECT 2,11,5 UNION
SELECT 3,20,23 UNION
SELECT 4,23,20 UNION
SELECT 5,7 ,11
)
SELECT *, ROW_NUMBER() OVER (PARTITION BY ABS(SENDER_ID - RECIEPENT_ID) ORDER BY ID) RN FROM CTE
```
FROM THIS USE WHERE RN = 1 | How to find the first message between 2 parties in SQL? | [
"",
"sql",
"sql-server",
""
] |
I thought it was a bug but after reading this article <http://www.codeproject.com/Tips/668042/SQL-Server-2012-Auto-Identity-Column-Value-Jump-Is>, I found that it's a new feature of SQL Server 2012.
This feature increments your last identity column value by 1000(ints) for new rows(10000 for bigints) automatically.
[!... | Existing Identity columns will fail with "Server: Msg 8115, Level 16, State 1, Line 2 Arithmetic overflow error converting IDENTITY to data type int. Arithmetic overflow occurred." See <http://www.sql-server-performance.com/2006/identity-integer-scope/> for discussion.
There isnt a reason to suspect that Identity Jump... | Why don't you use Sequence in MS Server 2012.
Sample Code For Sequence will be as follows and you don't need ADMIN permission to create Sequence.
```
CREATE SEQUENCE SerialNumber AS BIGINT
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 9999999
CYCLE;
GO
```
In case if you need to add the leading '0' to Sequence the... | How new Identity Jump feature of Microsoft SQL Server 2012 handles the range of data type? | [
"",
"sql",
"sql-server",
"sql-server-2012",
"auto-increment",
"identity-column",
""
] |
I am new to Microsoft SQL Server and need a query to return all records listed in the WHERE clause even duplicates. What I have will only return 3 rows.
I am reading in and parsing a text file using c#. And with that text file I am creating a query to get results from a database and then using the results to rebuild t... | Try something like this
You need a inline table with your values and `JOIN` with your table instead of `IN` clause
```
SELECT tb1.*
FROM (VALUES ('000520'),
('000531'),
('000531'),
('000636')) tc (hdrcode )
JOIN table1 tbl1
ON tc.hdrcode = tb1.hdrco... | This is not how things work in SQL. A query will only return what is there. If you only have 3 rows in your table and only one of them has `HdrCode 000531` it will be returned only once by that kind of query.
---
If you only want to solve this specific example, you could use:
```
SELECT tbl1.HdrCode, tbl1.HdrName FR... | SQL query results Need to Return all records in WHERE clause even duplicates | [
"",
"sql",
"sql-server",
""
] |
I have an order table that looks like the below
```
order_id pre_pay_time pre_pay_amount pre_pay_type final_payment_time final_payment_amount final_payment_type
==============================================================================================================================
1 ... | You could do something like this....You alias your pre and final payment queries and then join them by datefield.
```
SELECT *
FROM ( SELECT calendar.datefield AS FinalDate,
IFNULL (SUM (orders.final_payment_amount), 0)
AS total_final_sales,
IFNULL (
... | You can do it with a UNION. The second query will be similar to the one you have for final payments and use the pre\_payment columns. Then connect them with a UNION and SUM with a HAVING clause. Here's a good example of how to do that: [Sum a union query](https://stackoverflow.com/questions/5613728/sum-a-union-query) | MySQL Multiple Joins to a Calendar Table For Payments Data | [
"",
"mysql",
"sql",
""
] |
I googled a lot, but I did not find the exact straight forward answer with an example.
Any example for this would be more helpful. | The primary key is a unique key in your table that you choose that best uniquely identifies a record in the table. All tables should have a primary key, because if you ever need to update or delete a record you need to know how to uniquely identify it.
A surrogate key is an artificially generated key. They're useful w... | A **surrogate key** is a made up value with the sole purpose of uniquely identifying a row. Usually, this is represented by an auto incrementing ID.
Example code:
```
CREATE TABLE Example
(
SurrogateKey INT IDENTITY(1,1) -- A surrogate key that increments automatically
)
```
A **primary key** is the identifying ... | What is the difference between a primary key and a surrogate key? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2005",
"sql-server-2012",
""
] |
I am using the below query to insert data from one table to another:
```
DECLARE @MATNO NVARCHAR(10), @GLOBALREV INT, @LOCALREP INT
SET @MATNO = '7AGME'
SET @GLOBALREV = 11
SET @LOCALREP = 1
INSERT INTO CIGARETTE_HEADER
VALUES
(SELECT *
FROM CIGARETTE_HEADER_BK1
WHERE MATERIAL_NUMBER = @MATNO
... | You don't need `VALUES` keyword:
```
INSERT INTO CIGARETTE_HEADER
SELECT * FROM CIGARETTE_HEADER_BK1
WHERE MATERIAL_NUMBER = @MATNO AND
GLOBAL_REVISION = @GLOBALREV AND
LOCAL_REVISION = @LOCALREP
```
It is also preferable to *explicitly* cite every field name of both tables participating in the `INSE... | You don't need to use the VALUES () notation. You only use this when you want to insert static values, and only one register.
Example:
INSERT INTO Table
VALUES('value1',12, newid());
Also i recommend writing the name of the columns you plan to insert into, like this:
```
INSERT INTO Table
(String1, Number1, id)
VALUE... | Insert into from select query error in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have this 2 simple tables
[](https://i.stack.imgur.com/y97OE.png)
I want to select unmatching data from SAMPLE1 by comparing FruitName in SAMPLE2
So far I have tried
```
SELECT * FROM SAMPLE1,SAMPLE2 WHERE SAMPLE1.FruitName NOT LIKE '%' + dbo.SAMPL... | ```
SELECT *
FROM SAMPLE1 s1
WHERE NOT EXISTS (
SELECT NULL
FROM SAMPLE2 s2
WHERE s1.FruitName LIKE '%' + s2.FruitName + '%'
)
``` | Maybe that help:
```
select SAMPLE1.* from SAMPLE1
Left join SAMPLE2 ON SAMPLE1.fruitName LIKE concat('%', SAMPLE2.fruitName, '%')
Where SAMPLE2.id is null
```
[SQLFiddle](http://sqlfiddle.com/#!9/5269ac/11/0) | Find unmatched data in SQL | [
"",
"sql",
"sql-server",
""
] |
Is it possible to display just certain table names in the query:
```
USE [WebContact]
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'memberEmails'
```
Most of the time I would need all the table names but there are curtain situations where I need just certain row names.
When I try doing th... | The column `ContactDateTime` may be a column in your table but it is not a column in the `INFORMATION_SCHEMA.COLUMNS` view.
Since it is not a column there, SQL Server is going to error out saying that it is invalid.
I think what you're trying to do is add another `WHERE` clause to your statement:
```
USE [WebContact... | if ContactDateTime is a column that you are looking for in table memberEmails then you can do this
```
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'memberEmails'
and COLUMN_NAME='ContactDateTime'
``` | SQL Server : getting certain table names from query | [
"",
"sql",
"sql-server",
"vb.net",
"information-schema",
"tablename",
""
] |
**EDIT**
*the values in the table can be negative numbers (sorry for the oversight when asking the question)*
Having exhausted all search efforts, I am very stuck with the following:
I would like to calculate a running total based on the initial value. For instance:
My table would look like:
```
Year Percent Co... | You can accomplish this task using a recursive CTE
```
;WITH values_cte AS (
SELECT [Year]
,[Percent]
,[Constant]
,CASE WHEN [v].[Percent] < 0 THEN
[v].[Constant] - (([v].[Percent] + 1) * [v].[Constant])
ELSE
[v].[Percent] * [v].[Constant]
END
... | In SQL Server 2012+, you would use a cumulative sum:
```
select t.*,
(const * sum(1 + percent / 100) over (order by year)) as rolling_sum
from t
order by t.year;
```
EDIT:
Ooops, I notice you really seem to want a cumulative product. Assuming `percent` is always greater than 0, then just use logs:
```
select... | sql (beginner) - use value calculated from above cell | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
Lets say I have a table like this:
```
--------------------------------------------------
| id | text |
--------------------------------------------------
| 01 | Test string <div src="0124"> |
--------------------------------------------------
| 02 | Another type <div ... | You can use SUBSTRING by finding the initial position of the number and then finding the length of the string:
```
SELECT SUBSTRING(text, (CHARINDEX('src=', text) + 5), (CHARINDEX(CHAR(34) + '>', text) - (CHARINDEX('src=', text) + 5))) AS text
FROM yourTable;
```
This will get your starting postion (notice I add 5 to... | Create function to get numeric
```
CREATE FUNCTION dbo.udf_GetNumeric
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlph... | Get dynamic length value in a string after a specific sub-string, | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I've got 2 tables:
adresses and a log of files (named send) i've sent.
For a given file, I want to get all adresses, and whether they received the file or not.
What I've got so far is this:
```
SELECT *
, CASE
WHEN send.fileid = 1 THEN 1
ELSE s... | ```
SELECT *
FROM adress
LEFT JOIN send ON send.adressid = adress.id
AND send.fileid =1
LIMIT 0 , 30
```
that seems to be it | One way of going about is is putting the condition in a subquery and letting the outer join do all the heavy lifting:
```
SELECT a.*, s.fieldid
FROM address a
LEFT JOIN (SELECT filedid, addressid
FROM send
WHERE fileid = 1) ON s.addressid = a.id
``` | Remove double entry from orignial table when joining | [
"",
"mysql",
"sql",
"join",
""
] |
How can I tell the LAG function to get the last "not null" value?
For example, see my table bellow where I have a few NULL values on column B and C.
I'd like to fill the nulls with the last non-null value. I tried to do that by using the LAG function, like so:
```
case when B is null then lag (B) over (order by idx) ... | if it is null all the way up to the end then can take a short cut
```
declare @b varchar(20) = (select top 1 b from table where b is not null order by id desc);
declare @c varchar(20) = (select top 1 c from table where c is not null order by id desc);
select is, isnull(b,@b) as b, insull(c,@c) as c
from table;
``` | You can do it with `outer apply` operator:
```
select t.id,
t1.colA,
t2.colB,
t3.colC
from table t
outer apply(select top 1 colA from table where id <= t.id and colA is not null order by id desc) t1
outer apply(select top 1 colB from table where id <= t.id and colB is not null order by id desc) t... | LAG functions and NULLS | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2016",
""
] |
correct syntax of upsert with postgresql 9.5, below query shows `column reference "gallery_id" is ambiguous` error , why?
```
var dbQuery = `INSERT INTO category_gallery (
category_id, gallery_id, create_date, create_by_user_id
) VALUES ($1, $2, $3, $4)
ON CONFLICT (category_id)
DO UPDATE SET
category_id = $... | The `ON CONFLICT` construct requires a `UNIQUE` constraint to work. From the documentation on [`INSERT .. ON CONFLICT` clause](http://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT):
> The optional `ON CONFLICT` clause specifies an alternative action to raising a **unique violation** or **exclusion... | As a simplified alternative to [the currently accepted answer](https://stackoverflow.com/a/36799500/3169029), the `UNIQUE` constraint can be anonymously added upon creation of the table:
```
CREATE TABLE table_name (
id TEXT PRIMARY KEY,
col TEXT,
UNIQUE (id, col)
);
```
Then, the upsert query becomes (s... | How to correctly do upsert in postgres 9.5 | [
"",
"sql",
"postgresql",
"upsert",
"postgresql-9.5",
""
] |
The following SQL statement selects all the orders from the customer with `CustomerID=4` ("Around the Horn"). We use the `Customers` and `Orders` tables, and give them the table aliases of `c` and `o`, respectively. (Here we have used aliases to make the SQL shorter):
```
SELECT o.OrderID, o.OrderDate, c.CustomerName
... | With the `SELECT` statement you tell which columns of the table(s) you need. If there are more tables with the same column names you have to specificy also the table name (tableName.columnName).
With the `FROM` statement you tell the tables from which you want to select the datas. In this query there are two tables se... | Here is a simpler version of the above code without using Alias (b/c that is what confused me in the start)... Without alias, it is much simpler to read this code as below:
```
SELECT OrderID, OrderDate, CustomerName
FROM Customers, Orders
WHERE Customers.CustomerID=Orders.CustomerID
``` | Having query in SQL aliases | [
"",
"sql",
""
] |
How do I look up DISTINCT values of one table, look for each name in another table and get both the values and their names as a result?
The Beleg table looks like this:
```
SELECT DISTINCT Ursprungskonto FROM Beleg
WHERE YEAR ( Valuta ) = 2016
```
gets me:
```
1000
1210
1220
1230
```
For each of these values, I ne... | You could try sub-query:
```
SELECT Kontonr , Name FROM Geldkonto
WHERE Kontonr in (SELECT DISTINCT Ursprungskonto FROM Beleg
WHERE YEAR ( Valuta ) = 2016)
``` | Instead of applying DISTINCT *after* the join you better do it *before*:
```
SELECT k.Kontonr, k.Name
FROM Geldkonto AS k
JOIN
(
SELECT DISTINCT Ursprungskonto
FROM Beleg
WHERE YEAR ( Valuta ) = 2016
) AS b
ON k.Kontonr = b.Ursprungskonto
```
This is similar to @rev\_dihazum's solution, simply using a j... | Combining two nested SELECT with DISTINCT? | [
"",
"sql",
"select",
"nested",
"filemaker",
""
] |
Have a ncarchar(MAX) field in SQL table. It has numbers such as 717.08064182582, 39.0676048113, etc. in which I need to only have 3 places after decimal. For instance 717.080, 39.067.
Without converting the field type, would like to get rid of those last n characters, however every row has different number of characte... | Try this
```
SELECT CAST(ColumnName AS DECIMAL(18,3))
```
Without converting it data type As per **@vkp** Comment
```
SELECT SUBSTRING(ColumnName ,0,CHARINDEX('.', ColumnName )+4)
``` | ```
select CASE WHEN CHARINDEX('.', Your_column) > 0
THEN SUBSTRING(Your_column, 1, CHARINDEX('.', Your_column) + 3)
ELSE Your_column
END
```
this is similar as previous answers but more faster and safer | SQL Server - Delete Values after Decimal (non-int field) | [
"",
"sql",
"sql-server",
"decimal",
"rounding",
"nvarchar",
""
] |
I'm using PostgreSQL. If I have an **id in** query say:
```
select * from public.record where id in (1,5,1);
```
this will only give me two rows, because the id 1 has a duplicate. But what if I want to display a set of records containing :
```
id | value
1 | A
5 | B
1 | A
```
Regardless of the reason why I... | You can do that by joining the values:
```
with ids (id) as (
values (1),(5),(1)
)
select r.*
from public.record r
join ids on r.id = ids.id;
```
If you need to keep the order of the parameter list, you need to add a column to sort on:
```
with ids (id, sort_order) as (
values
(1, 1),
(5, 2),
... | You can use `JOIN` on a subquery:
```
SELECT
r.id, r.value
FROM public.record r
INNER JOIN (
SELECT 1 AS id UNION ALL
SELECT 5 AS id UNION ALL
SELECT 1 AS id
) t
ON t.id = r.id
``` | Retrieve same number of records in an ID IN query even with a duplicate | [
"",
"sql",
"postgresql",
"duplicates",
""
] |
I got a numeric(8,0) date column, with values like `20130101`. I need to cast it to some date format and do some queries.
My test query looks like this
```
SELECT *
FROM hund
WHERE ISDATE(hund.hfdat) = 1
and cast((left(convert(varchar(8),hund.hfdat),4) +
substring(convert(varchar(8),hund.hfdat),5,2) + right(... | ```
hund.hfdat >= replace(CONVERT(date, DATEADD(year, -10, getdate())),'-','')
``` | It should be a simple double cast
```
DECLARE @WhyIsThisNumeric decimal(8,0) = 20130101
SELECT CAST(CAST(@WhyIsThisNumeric AS varchar(8)) AS datetime)
```
When you attempt to cast `20130101` (not `'20130101'`: it's a number, not a string) then it is evaluated as 20,130,101 days after 01 Jan 1900 which is an utterly i... | sql server casting some data | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I would like to get values without the smallest and the biggest ones, so without entry with 2 and 29 in column NumberOfRepeating.
[](https://i.stack.imgur.com/p8Pie.png)
My query is:
```
SELECT Note, COUNT(*) as 'NumberOfRepeating'
WHERE COUNT(*) <> MAX(COUNT(*))AND COUNT(*)... | ```
SELECT Note, COUNT(*) as 'NumberOfRepeating'
FROM Notes
GROUP BY Note
HAVING count(*) <
(
SELECT max(t.maxi)
FROM (select
Note, COUNT(Note) maxi FROM Notes
GROUP BY Note
) as t
)
AND
count(*) >
(
SELECT min(t.min)
FROM (select
Note, COUNT(Note) min FROM Notes
GROUP BY Note
) as t
)
```
try this cod... | One method would use `order by` and `limit`, twice:
```
select t.*
from (select t.*
from t
order by NumberOfRepeating asc
limit 99999999 offset 1
) t
order by NumberOfRepeating desc
limit 99999999 offset 1;
``` | How to write sql query to get items from range | [
"",
"mysql",
"sql",
""
] |
For instance, I have a datetime like this `'2016-04-02 00:00:00'` and another like this `'2016-04-02 15:10:00'`. I don't care about the time-part, I want them to match just by the date-part.
I have tried with `date()`, `to_date`, `datepart`, nothing works. | Truncating the date to day should do the trick. Documentation here:
<https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions201.htm>
For example
```
SELECT TRUNC(SYSDATE, 'DAY') FROM DUAL;
``` | Do it like this:
```
where yourField >= the start of your date range
and yourField < the day after the end of your date range
```
**Edit starts here:**
While you could use `trunc`, as suggested by others, bear in mind that filtering on function results tends to be slow. | How to transform Oracle DateTime to Date | [
"",
"sql",
"oracle",
""
] |
I'm having an issue with my stored procedure.
I am getting error:
> Cannot perform an aggregate function on an expression containing an
> aggregate or a subquery
Here's the part of my stored procedure where I believe the error occurs:
```
SELECT column_1, column_2,
SUM(CASE WHEN column_2 NOT IN (SELECT produ... | You'll get much better performance generally if you try to avoid correlated subqueries anyway:
```
SELECT
MT.column_1,
MT.column_2,
SUM(CASE WHEN P.product IS NULL THEN 1 ELSE 0 END) AS total
FROM
My_Table MT
LEFT OUTER JOIN Products P ON P.product = MT.column_2
WHERE
MT.is_rated = '1'
GROUP BY
... | ```
SELECT
column_1, column_2,
SUM(
CASE
WHEN table_products.product IS NULL THEN 1
ELSE 0
END
) AS Total
FROM my_table
left join table_products on my_table.column_2 = table_products.product
WHERE is_rated = '1'
GROUP BY column_1, column_2
``` | SQL Server Cannot perform an aggregate function on an expression containing an aggregate or a subquery | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table where monthly sales are recorded. See image for a sample of the table.[](https://i.stack.imgur.com/HI7oA.jpg)
So this data is partial, I have months 1-12 for every year since 2000. What I would normally do is query total sales for any o... | Group by year in order to get a result record per year. Order it by the sales sum descending and limit your results to 1 row, so you get the year with the maximum sales sum.
Additionally we use the analytic version of `AVG` to get the avarage over all sums with each year record (of which we show only one at last). Rem... | Here is a solution for the second part of your question. This will compute the average of sum of sales over all years:
```
SELECT avg(sum_sales)
FROM (
SELECT year as year, sum(total_sales) as sum_sales
FROM sales
GROUP BY year
) AS T;
```
For getting the year with the highest sales, you coul... | SQL SUM and Average Sale by Years | [
"",
"sql",
""
] |
I need to update `customdate1` column with the time from `starttime` column. The issue I'm having is formatting. The current format for `starttime` is HH:MM:SS.SSSSSSS I need it to be in HH:MM.
[](https://i.stack.imgur.com/UOmYN.jpg)
Thank you
Brian | I suggest that you first change your data type and then perform an update
```
ALTER TABLE TableName
ALTER COLUMN CustomDate1 time(0) not null
UPDATE tablename
SET customdate1 = (SELECT starttime)
FROM tablename);
```
If you don't want to store seconds you can change your data type to char(5) and... | ```
UPDATE tablename
SET customdate1 = (SELECT SUBSTRING(CONVERT(varchar, starttime, 108), 1, 5)
FROM tablename);
```
Try above one. Date will be truncated to 5 characters. `hh:mm` | Sql update column with time from | [
"",
"sql",
"sql-server",
""
] |
I have a code in sql which I am using. Not much familiar with postgresql. Below is the code which I want to convert to postgresql. I'm using dbeaver 3.5.4
```
Update tablename
set record_hash = cast(hashbytes('MD5',
coalesce(id, '') +
coalesce(name, '') +
coalesce(... | You can do it like this:
```
Update tablename
set record_hash = ('x'|| substr(
md5(
coalesce(id, '') ||
coalesce(name, '') ||
coalesce(created_date, '') ||
coalesce(last_m... | I assume that this `hashbyte()` thing generates a hash value.
To create a md5 checksum in Postgres you can use the md5() function, e.g.:
```
md5(concat(id::text, name, created_date::text, last_modified_date::date))
```
`concat()` will take care of null values automatically, no need for `coalesce()`
Unfortunately th... | Sql to postgresql | [
"",
"sql",
"postgresql",
""
] |
I am working on Terradata SQL. I would like to get the duplicate fields with their count and other variables as well. I can only find ways to get the count, but not exactly the variables as well.
Available input
```
+---------+----------+----------------------+
| id | name | Date |
+---... | You could use a [window aggregate function](http://www.info.teradata.com/htmlpubs/DB_TTU_13_10/index.html#page/SQL_Reference/B035_1145_109A/ch09.13.039.html), like this:
```
SELECT *
FROM (
SELECT id, name, other-variables,
COUNT(*) OVER (PARTITION BY id) AS duplicates
FROM users
... | As an alternative to the accepted and perfectly correct answer, you can use:
```
SELECT {all your required 'variables' (they are not variables, but attributes)}
, cnt.Count_Dups
FROM Table_NAME TN
INNER JOIN (
SELECT id
, COUNT(1) ... | SQL : Getting duplicate rows along with other variables | [
"",
"sql",
"database",
"teradata",
""
] |
I was handed a scenario that had the schema of
Product:
```
maker model type
A 1232 PC
A 1233 PC
A 1276 Printer
A 1298 Laptop
A 1401 Printer
A 1408 Printer
A 1752 Laptop
B 1121 PC
B 1750 Laptop
C 1321 Laptop
D 1288 Printer
D 1433 Printer
E 1260 PC
E... | One method uses `exists` and `not exists`:
```
select distinct p.maker, p.type
from product p
where exists (select 1
from product p2
where p2.maker = p.maker and p2.type = p.type and p2.model <> p.model
) and
not exists (select 1
from product p2
... | ```
SELECT maker, MIN(type) as type
FROM Product
GROUP BY maker
HAVING COUNT(DISTINCT type) = 1 AND COUNT(DISTINCT model) > 1;
``` | Looking for a more elegant way of solving this sql query | [
"",
"sql",
""
] |
Hey guys suppose I have a data frame
```
Year Month 1_month_sub 3_month_sub 12_month_sub
2014 1 3 1 1
2014 2 1 0 0
2014 3 1 0 0
2014 4 1 0 0
... | I speculate that the data is in a table and 1 month subs only exist for one month, 3 month for 3 months, and 12 months for 12 months.
And, further, I will assume that every month has a row.
You can do this in Postgres using a windowing clause on a cumulative sum:
```
select t.*,
(1_month_sub +
sum(3_m... | It is possible to do that without power features. Below has been tested on PostgreSQL and on MS SQL.
See on SQL Fiddle how it works: <http://sqlfiddle.com/#!15/74862/4/0>
Simple SQL Join
```
select
t1.Year,
t1.Month,
sum(case when ((t2.Year-2014)*12+t2.Month) <= ((t1.Year-2014)*12+t1.Month) and ((t2.Year-2014)*1... | Coalesing with lags/leads over rows? | [
"",
"sql",
"postgresql",
""
] |
I have a table A with ID col. Here is sample data -
```
ID
NT-QR-1499-1(2015)
NT-XYZ-1503-1
NT-RET-546-1(2014)
```
I need to select everything after first '-' from left and before '(' from the right. However, some records do not have '(', in which case, the second condition would not apply.
Here is what I need -
``... | You could get it done in a CASE statement, although I'd definitely take any advice from Aaron;
```
CREATE TABLE #TestData (ID nvarchar(50))
INSERT INTO #TestData (ID)
VALUES
('NT-QR-1499-1(2015)')
,('NT-XYZ-1503-1')
,('NT-RET-546-1(2014)')
SELECT
ID
,CASE
WHEN CHARINDEX('(',ID) = 0
THEN RIGHT(ID, LEN(ID... | SELECT CASE
WHEN CHARINDEX('(',ID) > 0
THEN
SUBSTRING(ID,CHARINDEX('-',ID)+1,(CHARINDEX('(',ID)-CHARINDEX('-',ID)-1))
ELSE
SUBSTRING(ID,CHARINDEX('-',ID)+1)
END AS New\_Column\_Name
FROM Table\_Name
First it will check whether "(" present or not .
If present then it will fetch the data from next position of "-" to bef... | How to use substring conditionally before and after two different symbols in SQL SERVER | [
"",
"sql",
"sql-server",
""
] |
I have 2 tables with the same columns (id, country\_code), example :
```
Table A
--------
id country_code
1 fr
2 fr
3 fr
Table B
--------
id country_code
1 ua
2 fr
3 uk
```
I would like to get all fields in B where the country\_code is different of the one in A for each same id,
Example expect... | You need to use Collate keyword to change collation:
```
select b.id,b.country_code
from b join a
on b.id = a.id and b.country_code <> a.country_code collate utf8_unicode_ci;
```
For more information about collation: [What does character set and collation mean exactly?](https://stackoverflow.com/questions/341273/what... | You can use `join`:
```
select b.*
from b join
a
on b.id = a.id and b.country_code <> a.country_code;
``` | SQL : error with an inner join, probably sthg simple | [
"",
"mysql",
"sql",
"database",
""
] |
I've been playing around with MySQL and sqlalchemy to gather and store data. Over the the weekend I was collecting tweets at about 20,000 tweets/hour and placing them in a table `raw_tweets` indexed by their tweet id. I am expecting ~1,000,000 rows, but when I run
```
SELECT COUNT(*) from raw_tweets;
```
the query ju... | Most probably it doesn't hang but needs very much time to execute.
If the table engine is `InnoDB`, `SELECT COUNT(*)` must read all the rows from the table (in order to count them) and, if the database is under heavy use then the operation takes a lot of time.
This is documented in the [Limits on InnoDB Tables](http:... | you could run the following in another database connection (if you have sufficient rights to do so):
```
SHOW FULL PROCESSLIST;
```
which might show all the queries/processes that are currently running on your database. In that list you might see if there are some locks set on a table
```
mysql> show full processlis... | MySQL query hangs on `SELECT COUNT(*)` | [
"",
"mysql",
"sql",
""
] |
I have a SQL Server 2012 table that holds session per user and I need to find out monthly total of minutes for activity and if there are no results for the month then to show "0". Table below:
```
User SessionStart SessionEnd
1 2014-03-01 08:00:00.000 2014-03-01 08:10:00.000
1 2014-03-15 09:... | You can generate all the rows with a `cross join` and then use `left join` to bring in your summaries. Assuming that some row exists for each month, you can get this information from the session table itself:
```
SELECT u.User, yyyymm.mm, yyyymm.yy
COALESCE(SUM(DATEDIFF(minute, s.SessionStart, s.SessionEnd)), 0... | You're on the right track with your `months` table. Could you post your example that's not working using the left outer join? If you start with `months` and left outer join to your `SessionTable` you should be fine.
Something like...
```
SELECT User
,MONTH(m.month)
,YEAR(m.year)
,SUM(DATEDIFF(minute... | Showing month value when no data exists SQL Server | [
"",
"sql",
"sql-server",
"datetime",
""
] |
I have the following SQL statement:
```
select
DOCUMENT.DOCUMENT_ID,
(case
when DOCUMENT.CLASSIFICATION_CODE is not null
then DOCUMENT.CLASSIFICATION_CODE
else TEMPLATE.CLASSIFICATION_CODE end) CLASSIFICATION_CODE,
CLASSIFICATION.NAME CLASSIFICATION_NAME
from
DOCUMENT,
TEMPL... | You can use [NVL](http://www.oradev.com/nvl.html) or the more standard [COALESCE](https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm) for that:
```
COALESCE(DOCUMENT.CLASSIFICATION_CODE, TEMPLATE.CLASSIFICATION_CODE)
= CLASSIFICATION.CLASSIFICATION_CODE(+)
```
In ANSI syntax:
```
select
... | While you can use `coalesce` or `nvl`, as other answers have suggested, I'd prefer to join to the `classification` table twice. Yes, the engine has to perform an extra join, but avoiding the functions allows the engine to use an index.
```
SELECT document.document_id,
COALESCE (d.classification_code, t.classifi... | Oracle SQL conditional join | [
"",
"sql",
"oracle",
"join",
""
] |
I need to update a single column over a thousand rows in the database. Normally when I need to do this, I'll do the following:
```
UPDATE [table] SET DATA="FOO" WHERE ID=23;
UPDATE [table] SET DATA="ASD" WHERE ID=47;
UPDATE [table] SET DATA="FGH" WHERE ID=83;
UPDATE [table] SET DATA="JKL" WHERE ID=88;
UPDATE [table] S... | You can actually do it using **insert into ...on duplicate key update**
```
insert into [table](ID,DATA)
values(23,'FOO'),(47,'ASD'),(54,'DSF')..,
on duplicate key update DATA=values(DATA)
``` | You could use the [`MERGE`](https://msdn.microsoft.com/en-us/library/bb510625%28v=sql.100%29.aspx) statement which is in the [SQL:2003](https://en.wikipedia.org/wiki/Merge_%28SQL%29) standard and available in Transact-SQL since SQL Server 2008:
```
MERGE mytable
USING (VALUES (23, 'FOD'),
(47, 'ASD'),
... | Update a single column on multiple rows with one SQL query | [
"",
"sql",
""
] |
I have written a query
**delete from Table1 where Tableid in(select Tableid from Table1 group by Tableid having count(\*) >1)**
but this query removes all the data having count greater than 1.
Can someone help me with a single line query that deletes the duplicate data and resetting the count to 1.
I have table `Tabl... | I think this is what you are looking for
```
DECLARE @Table TABLE
(
Name VARCHAR(20),
Value INT
);
;WITH T AS (
SELECT CONCAT('a',1) AS Name, 1 AS Value
UNION ALL
SELECT CONCAT('a',T.Value + 1) AS Name, T.Value + 1 FROM T
WHERE T.Value < 5
)
INSERT INTO @Table
SELECT T.Name ,
T.V... | To delete all the duplicate data: Group the column that may have the same data.
```
DELETE FROM table
WHERE id IN (SELECT id FROM table GROUP BY column HAVING COUNT(column) > 1)
```
To delete the duplicate and keep one of it: Get at least (1) data from the duplicate and grouped column.
```
DELETE t1 FROM table t1, ... | I want a single query that deletes duplicate entry from my database | [
"",
"mysql",
"sql",
"count",
"sql-delete",
"having",
""
] |
I have a table with the next structure:
```
Data structure:
| CONTRACT | CONNECTION | STATE |
| 1 | AAA | Y |
| 2 | AAA | Y |
| 3 | BBB | N |
| 4 | BBB | N |
| 5 | BBB | N |
| 6 | BBB | N |
| 7 | AAA ... | You can use `SUM` and `HAVING`:
`ONLINE DEMO`
```
SELECT *
FROM tbl t
WHERE
CONNECTION IN(
SELECT CONNECTION
FROM tbl
GROUP BY CONNECTION
HAVING
SUM(CASE WHEN STATE = 'N' THEN 1 ELSE 0 END) > 0
AND SUM(CASE WHEN STATE <> 'N' THEN 1 ELSE 0 END) = 0
)
```
... | Try this:
```
SELECT CONTRACT, CONNECTION, STATE
FROM (
SELECT CONTRACT, CONNECTION, STATE,
COUNT(CASE WHEN STATE <> 'N' THEN 1 END) OVER (PARTITION BY CONNECTION) AS cnt
FROM mytable) t
WHERE t.cnt = 0
``` | Select all rows, with specific characteristics, with same subdata by grouping them through a same row value in oracle | [
"",
"sql",
"oracle",
"group-by",
"subquery",
""
] |
Table 'volcado': id, reserva, cantidad
With the following query:
```
SELECT (CASE
WHEN sum(cantidad) > 0 THEN 1
WHEN sum(cantidad) <= 0 THEN 0
END) AS suma
FROM volcado
GROUP BY reserva
```
The result is:
```
╔══════╗
║ suma ║
╠══════╣
║ 1 ║
║ 1 ║
║ 0 ║
║ 1 ║
║ 0 ║
╚══════╝
... | Try this way
```
SELECT SUM(a.suma) from
(SELECT (CASE
WHEN sum(cantidad) > 0 THEN 1
WHEN sum(cantidad) <= 0 THEN 0
END) AS suma FROM volcado GROUP BY reserva)a
``` | This should work, use the subquery as a table instead of as a column.
```
SELECT SUM(suma) from
(SELECT (CASE
WHEN sum(cantidad) > 0 THEN 1
WHEN sum(cantidad) <= 0 THEN 0
END) AS suma FROM volcado GROUP BY reserva)
``` | SUM() the results of GROUP BY column | [
"",
"mysql",
"sql",
""
] |
For some reason, I get the mentioned error message while using two internal tables, declared at the beginning of the script.
I can insert data into the tables, but when I try to join them on a field, present in both tables it wount let me.
I am working in SQL2012
```
SELECT *
FROM @ITAB01
JOIN @ITAB02
on @ITAB01.coun... | You need to give a name to the table variable.
NOT LIKE THIS:
```
declare @t1 table
(
p1 int
)
declare @t2 table
(
p2 int
)
select *
from @t1,
@t2
where @t1.p1 = @t2.p2
```
BUT LIKE THIS:
```
declare @t1 table
(
p1 int
)
declare @t2 table
(
p2 int
)
select *
from @t1 t1,
@t2 t2
where t1.p1 = t2.... | If you want to refer to the tables elsewhere in the query (outside of the `FROM` clause), introduce aliases:
```
SELECT *
FROM @ITAB01 t1
JOIN @ITAB02 t2
on t1.country=t2.country
```
Aliases are also useful because you can shorten long names. They're also required once you want to use the same table more than once i... | Must declare the scalar variable using internal tables | [
"",
"sql",
"sql-server-2012",
""
] |
I was reading articles about rollback transaction and can't find something like I need. Assume I have a user table. User can update his/her records but I want to rollback if entered value is null. I know there are lots of simple ways to do this like checking with c# if it is null and things like that but point in here ... | Rollback is used with a transaction, a rollback restores the state to what it was when begin tran was executed.
```
BEGIN TRAN 'tran1'
INSERT INTO Whatever table...
IF(... check for null)
BEGIN
ROLLBACK TRAN 'tran1'
RETURN 0
END
COMMIT TRAN 'tran1'
``` | There are three ways. First, if your checks are just on one column, use the `check` constraint on the column definition:
```
create table test (
age int check (age > 40),
...
);
```
Fore more complex constraints, you will need `triggers`. The kind of triggers available depends on the technology (oracl... | Rollback if null | [
"",
"sql",
"rollback",
""
] |
I'm new in database design and as far as I could research, using `null` values as representation of no present data is not a good Idea, the proble that I'm having now is that I don't know how to represent no present data instead of `null`.
For example I have a user table and a `FavoritColor` table, the user has a colu... | `NULL` is a perfectly fine value to use. If you're worried about defaults, make sure to use an `OUTER JOIN` and (for SQL Server, anyway) you can do something like:
`SELECT user_table.name, COALESCE(preferences.color_preference, 'DEFAULT_VALUE') FROM user_table LEFT OUTER JOIN preferences ON user_table.id = preferences... | `NULL` is usually meant to represent "unknown", which is why `'Ellen' <> NULL` doesn't result in `TRUE`, but in `NULL`. It is *not known* whether the value still unknown to us is 'Ellen' or not. An example would be a middle name; as long as the field is empty we don't know whether Mary's middle name is Ellen or not.
O... | What to use instead of Null if no data is present in SQL? | [
"",
"mysql",
"sql",
"null",
""
] |
I'm working on a query where I need to look at patient vitals (specifically blood pressure) that were entered when a patient visited a clinic. I'm pulling results for the entire year of 2015, and of course there are certain patients who visited multiple times, and I need to only see the vitals that were entered at the ... | One simple method uses `ROW_NUMBER()` to find the more recent record for each test:
```
SELECT pd.PatientID as [Patient ID], pd.PatientName as Name, pd.DateOfBirth as DOB,
v.Test as Test, v.Results as Results, v.TestDate as Date
FROM PatientDemographic pd JOIN
(SELECT v.*,
ROW_NUMBER() OVER (P... | You can also use Common Table Expression to achieve this.
```
IF OBJECT_ID('tempdb..#RecentPatientVitals') IS NOT NULL
DROP TABLE #RecentPatientVitals;
GO
CREATE TABLE #RecentPatientVitals
(
Patient_ID INT
, Name VARCHAR(100)
, DOB DATE
, Test VARCHAR(... | Find the most recent date in a result set | [
"",
"sql",
"sql-server",
"group-by",
"max",
"where-clause",
""
] |
I have simple table:
```
| Val1 | Val2 |
--------------------------
| 10 | 20 |
--------------------------
| 20 | 30 |
--------------------------
```
How to select data from one row in this and get result as table where data in first column will be column name from original ta... | This SQL Script will create a temporary table, insert some values and unpivot the result.
```
CREATE TABLE #B
( VAL1 INT, VAL2 INT)
INSERT INTO #B VALUES(10,20),(20,30)
SELECT * FROM #B
SELECT U.NAME, U.VALUE
FROM (SELECT * FROM #B WHERE VAL1 = 10) AS SEL
UNPIVOT
(
VALUE
FOR NAME IN (VAL1, VAL2)
) U;
DROP T... | Consider this scenario :
Table 1:
```
DEPARTMENT EMPID ENAME SALARY
A/C 1 TEST1 2000
SALES 2 TEST2 3000
```
Table 2:
```
ColumnName 1 2
DEPARTMENT A/C SALES
EMPID 1 2
ENAME TEST1 TEST2
SALARY 2000 3000
```
If we are required to transform result set in Table1 format to Table2 ... | How to select data from one row in sql as table? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I wish to order the results of the below query by a substring of the first 8 characters of the 'version' number. I understand SUBSTRING(), so don't bother me with that. My problem is trying to actually place the ORDER BY in regards to the UNION.
UPDATE: I need the data returned in order of Version, but still also orde... | You need to do another `JOIN` to the `db` table to get the `Version` for each `[KEY]` sort by that:
```
SELECT
e.[GUID], e.[KEY], e.[VALUE]
FROM db e
INNER JOIN db g
ON e.[GUID] = g.[GUID]
AND g.[Key] = 'Session.Type'
AND g.[Value] IN ('EndMatchTypeA', 'EndMatchTypeB')
INNER JOIN (
SE... | You can wrap the entire query and then `SELECT` from it using `ORDER BY`:
```
SELECT t.[GUID], t.[KEY], t.[VALUE]
FROM
(
SELECT e.[GUID], e.[KEY], e.[VALUE]
FROM db e INNER JOIN
(SELECT[GUID] FROM db
WHERE[Key] = 'Session.Type' and[Value] = 'EndMatchTypA') g
ON e.[GUID] = g.[GUID]
... | SQL: Order By, Substring, Union | [
"",
"sql",
"sql-order-by",
"union",
""
] |
I'm trying to insert the row below into Oracle database, but I get error
`[22008][1830] ORA-01830: date format picture ends before converting entire input string`
```
insert into tbl (coldate, start, end)
values (
TO_DATE('2005-03-04 02:04:30', 'YYYY-MM-DD HH24:MI:SS'),
TO_TIMESTAMP('2005-03-23 09:06:51.055000', 'YYY... | The error message tells you what you should do: your format mask is too "short" for the value you provide. You need to include the fractional seconds in the format mask for `to_timestamp()`
```
TO_TIMESTAMP('2005-03-23 09:06:51.055000', 'YYYY-MM-DD HH24:MI:SS.FF6')
```
For more details on the format model used in `to... | You are missing the fractional second specification in your format string:
```
insert into tbl (coldate, start, end)
values (
TO_DATE('2005-03-04 02:04:30', 'YYYY-MM-DD HH24:MI:SS'),
TO_TIMESTAMP('2005-03-23 09:06:51.055000', 'YYYY-MM-DD HH24:MI:SS.FF'),
-- Here ------------------------------------------------------... | Inserting timestamp in Oracle | [
"",
"sql",
"oracle",
"datetime",
"timestamp",
""
] |
I have to search a table ("NamesAges") for the names and ages of a set of names. The problem is that the table has thousands of names, the set of names that I am searching with has hundreds and not all the names in the set are in the table. How can I get an explicit NULL entry for the missing names.
Specifically:
```... | One way to do it:
```
SELECT a.Name, b.Age, case when b.Name IS NULL THEN 'Missing' ELSE 'OK' End Status
FROM (
SELECT 'Allan' Name
UNION SELECT 'Bonita'
UNION SELECT 'Chandra'
UNION SELECT 'Daniel'
) a
LEFT JOIN [NamesAges] b ON b.Name = a.Name
``` | Assuming the set of names is in another table, you could probably use a left join:
```
select s.name, n.age
from set_of_names s
left join names_and_ages n on s.name = n.name
```
This will give you all the names in the set of names, along with the age from the other table if it finds a name match (and null ot... | SQL List with empty items | [
"",
"sql",
""
] |
I have a table of names and I want to generate another column "Group" that increases by 1 every 5 records. Below is an example of the desired output.
```
Name Group
Joe 1
Frank 1
Susan 1
Tom 1
Kim 1
Mike 2
John 2
Henry 2
Rick 2
Quinn 2
``` | Creating a CTE with row number will help
```
;WITH cte AS
(
SELECT
Name,
ROW_NUMBER() OVER (ORDER BY Name) AS RowNum
FROM YourTable
)
SELECT
Name,
(RowNum - 1) / 5 + 1 AS [Group]
FROM cte
``` | You could try something like this
```
select a.name,
case when (a.myrow%5=0) then 5 else a.myrow%5 end as group
from
(select name,row_number() over (order by name) as myrow from YourTable)a
``` | SQL Update Segment of 5 Records | [
"",
"sql",
"sql-update",
"row-number",
""
] |
I have the following query in HIVE which throwing "FAILED: SemanticException [Error 10017]: Line 4:28 Both left and right aliases encountered in JOIN 'status\_cd'" Error.
Whole query seems to be correct, I executed similar query in MYSQL also which is working fine. Only in Hive it throwing error.
Is there any limitat... | Hive currently support only EQUIJOIN. Thus you can't use `ON tableA.col1 > tableB.col2`, but you can only do `ON tableA.col1 = tableB.col2`.
Then, to achive your goal, you have to rewrite the query, using a case statement to handle the SEMIJOIN... | Hive supports only equi join . Any condition other than the equi join can be put in the where clause. | Hive Error: FAILED: SemanticException [Error 10017]: Line 4:28 Both left and right aliases encountered in JOIN 'status_cd' | [
"",
"mysql",
"sql",
"hadoop",
"hive",
""
] |
I have one table named `tbservicecallallocation` and below is data for that table.
[](https://i.stack.imgur.com/wStg8.png)
From above data i want that of technician with their `MAX AllocationTime`.
Below image shows what result i want..
[![enter imag... | Have a sub-query to return each technician's max AllocationTime. Join with that result:
```
select t1.*
from tbservicecallallocation t1
join (select TechnicianIDF, max(AllocationTime) as MAxAllocationTime
from tbservicecallallocation
group by TechnicianIDF) t2
on t1.TechnicianIDF = t2.TechnicianIDF
an... | Try this:
```
SELECT *
FROM tbservicecallallocation t1
WHERE NOT EXISTS(
SELECT 'NEXT'
FROM tbservicecallallocation t2
WHERE t1.TechnicianIDF = t2.TechnicianIDF
AND t2.AllocationTime > t1.AllocationTime
)
``` | How to use MySql MAX() in a WHERE clause | [
"",
"mysql",
"sql",
"select",
""
] |
I have a table similar to the one shown below.
```
-----------------------------
JOB ID | parameter | result |
-----------------------------
1 | xyz | 10 |
1 | abc | 15 |
2 | xyz | 12 |
2 | abc | 8 |
2 | mno | 20 |
----------------------------... | you want to simulate a pivot table since mysql doesn't have pivots.
```
select
param,
max(case when id = 1 then res else null end) as 'result 1',
max(case when id = 2 then res else null end) as 'result 2'
from table
group by param
```
[SQL FIDDLE TO PLAY WITH](http://sqlfiddle.com/#!9/7c2c6d/6) | In Postgres, you can use something like:
```
select parameter, (array_agg(result))[1], (array_agg(result))[2] from my_table group by parameter;
```
The idea is: aggregate all the results for a given parameter into an array of results, and then fetch individual elements from those arrays.
I think that you can achieve... | SQL Query to compare two values which are in the same column but returned by two different set of queries | [
"",
"mysql",
"sql",
""
] |
I'm trying to determine the minimum effective date of an employee that has a record in their most recent department (see data below). I'm looking to have 8/25/2014 as the result but would like some assistance from you experts out there on how to pull it off. In the same data, this employee was in department 70260 for a... | You need to find the first group of rows:
```
SELECT EMPLID, MIN(first_dates)
FROM
(
SELECT EMPLID, EFFDT, DEPTID,
CASE -- check if all previous rows return the same value
WHEN MIN(DEPTID) OVER (PARTITION BY EMPLID ORDER BY EFFDT DESC ROWS UNBOUNDED PRECEDING)
= MAX(DEPTID) OVER (PAR... | You could do something like this
```
select * from
(select empid,effdt,deptid,
row_number() over ( partition by deptid order by effdt desc) as mostRecent
from yourtable) a
where a.mostRecent=1
``` | How to find a specific date using Oracle SQL for employee in most current department? | [
"",
"sql",
"oracle",
"oracle11g",
"greatest-n-per-group",
""
] |
I am getting this error when executing a `stored procedure` that I have created
> Msg 241, Level 16, State 1, Procedure UDP\_INITIAL\_CUSTOMER\_DIM\_POPULATION, Line 28
> Conversion failed when converting date and/or time from character string.
The code for the procedure is:
```
CREATE PROCEDURE UDP_INITIAL_CUSTOM... | The error is caused by the default value for the `expiry_date`. Running
```
SELECT CAST('999-12-31'AS DATE)
```
will produce an error:
> Conversion failed when converting date and/or time from character
> string.
What you want is
```
[expiry_date] DATE NULL DEFAULT '9999-12-31'
``` | I'm doing string to date conversion in SQL 2017 and it properly handles strings in m/d/yyyy format with single and double digit days or months and two or four digit years. For example, the following strings converted cleanly:
```
2/6/2012
1/20/2020
12/21/2017
6/14/21
```
In my case I found the problem to be a record ... | SQL Server Msg 241, Level 16, State 1, Conversion failed when converting date and/or time from character string | [
"",
"sql",
"sql-server",
"type-conversion",
""
] |
I have 3 tables that all need to interact. They are for a bike inventory. They are bike shop, shop inventory, and bike model. I want to find the cheapest bike in each shop inventory. The code below gives me the correct result I expect, but I also want to show the bike name.
```
SELECT
BS.BIKESHOPNAME, MIN(BM.PRIC... | I think that this should solve your problem:
```
SELECT DISTINCT
BS.BIKESHOPNAME,
FIRST_VALUE(BM.NAME) OVER (PARTITION BY BS.BIKESHOPNAME ORDER BY BM.PRICE ASC),
FIRST_VALUE(BM.PRICE) OVER (PARTITION BY BS.BIKESHOPNAME ORDER BY BM.PRICE ASC)
FROM BIKESHOP BS, BIKEMODEL BM, SHOPINVENTORY SI
WHERE SI.BIKESHOPID = BS.BIK... | Give this a try maybe? This is an example of how you can use **join** as well :)
```
SELECT BS.BIKESHOPNAME, MIN(BM.PRICE), BM.NAME
FROM
BIKESHOP AS BS
INNER JOIN
SHOPINVENTORY AS SI
ON SI.BIKESHOPID = BS.BIKESHOPID
INNER JOIN
BIKEMODEL AS BM
ON BM.BIKEID = SI.BIKEID
GROUP BY BS.BIKESHOPNAME, BM.NAME;
``` | Adding an extra SQL select statement is returning too many results | [
"",
"sql",
"select",
""
] |
I am trying to select all records in TABLEC and its equivalent value in TABLEA or TABLEB using right join. I am using MYSQL 5.5.47.
--Table data as follows
```
TABLEA TABLEB TABLEC
ID FNAME ID MNAME ID LNAME
0 ANOOP 0 N 0 SINGH
1 BIMA 2 SITA 3 RAJ
4 CIMI ... | ```
DROP TABLE IF EXISTS table_a;
DROP TABLE IF EXISTS table_b;
DROP TABLE IF EXISTS table_c;
CREATE TABLE table_a
(id INT NOT NULL PRIMARY KEY
,fname VARCHAR(12) NULL
);
INSERT INTO table_a VALUES
(0,'ANOOP'),
(1,'BIMA'),
(4,'CIMI'),
(6,'RAVI');
CREATE TABLE table_b
(id INT NOT NULL PRIMARY KEY
,mname VARCHAR(12) N... | You are trying to select all records in TABLEC and its equivalent value in TABLEA or TABLEB using right join. So Table A and B is joined to Table c records. So we need to use Left join(you will get all records of Table C and common records of Table A and B). More info please ref this [link](https://en.wikipedia.org/wik... | Two right joins | [
"",
"mysql",
"sql",
""
] |
I want to delete row and I get this error:
> the row values updated or deleted either do not make the row unique or
> they alter multiple rows
[](https://i.stack.imgur.com/c1TVX.png) | There are duplicate rows in your table. When this is the case you cannot edit table using UI. first delete rows with matching data using SQL then try and edit. Delete rows with matching data one by one until you are left with one row. Use the following query for deleting matching rows where column IdSeminar has value 1... | This might be a bit late but it could help someone. I ran into the same issue today but Akshey's code didn't work for me. My database table didn't contain an ID column, so I added one in and set it's 'Identity Specification' to 'Yes'. I reloaded the table with this new column in it and then was able to delete whichever... | the row values updated or deleted either do not make the row unique or they alter multiple rows | [
"",
"sql",
"sql-server",
""
] |
I have the following tables:
```
table1
========
rpid | fname | lname | tu | fu | tu_id | start_time
table2
========
tu_id | tu | fu | start_time
```
I want to populate table1's tu, fu and tu\_id using the matching records in table2. I match them based on a time stamp.
```
UPDATE table1
INNER JOI... | ```
UPDATE table1 SET tu_id= table2.tu_id, fu = table2.fu, tu=table2.tu
from table2
where
date_trunc('hour', table1.start_time) = date_trunc('hour', table2.start_time) and table1.rpid=table2.tu
;
``` | You cannot update multiple columns with only one select before postgres 9.5 (the last stable version)
So the syntax will be something like :
Before 9.5:
```
UPDATE table1
SET tu_id = (SELECT table2.tu_id
FROM table1
INNER JOIN table2
ON date_trunc('hour', table1.start_time) = date_trunc('hour', ... | how to insert bulk data based on bulk select | [
"",
"sql",
"postgresql",
"sql-update",
""
] |
In my database there are 3 column which is Name, Age, Gender.
In the program, I only want to use 1 search button. When the button is clicked, the program determine which 3 of the textbox has input and search for the right data.
How do you work with the query? For example if Name and Gender has text, the query :
"`Sel... | ## Original answer
(scroll down to see update)
Can you try the following:
* build a list only including values of the textboxes that have an input
* set a string of the join the items of that list together with the " AND " string
* append that string to your standard SELECT statement
The code looks like this:
```
... | ```
Select * from table
Where (Name = @name OR @name is Null)
AND (Gender = @gender OR @gender is Null)
...
```
it should be one query | How to implement a more efficient search feature? | [
"",
"mysql",
"sql",
"database",
"vb.net",
""
] |
I am trying to measure the growth over time of some sales data. I've grouped current and previous sales together based on the last n months, yielding the following (abbreviated) table:
```
+-------------------------------+---------------+-------------+
| CUSTOMER_NAME | TIMEFRAME | GROSS_SALES |
+-... | You can use `GROUP BY` to get one row per customer, then `SUM(CASE)` to pick out the current and previous values.
This has the advantage of only scanning the table once, rather than needing a join.
```
SELECT
CUSTOMER_NAME,
SUM(CASE WHEN TIMEFRAME = 'CURRENT' THEN GROSS_SALES END)
/
SUM(CASE WHEN TIMEFRA... | Use the table twice with different names...
```
select CUSTOMER_NAME, t1.TIMEFRAME/t2.TIMEFRAME
from TABLE_NAME as t1, TABLE_NAME as t2
where t1.CUSTOMER_NAME = t2.CUSTOMER_NAME
and t1.TIMEFRAME = 'PREVIOUS'
and t2.TIMEFRAME = 'CURRENT'
``` | Dividing column values based on other column values | [
"",
"mysql",
"sql",
""
] |
This query is working good, but the issue is I need to get the room number which is in another table called `rooms`. The query below fetched data from `reservations` table which only has `room_id`:
```
$select_table = "SELECT id, name, phone, email, address, country, adults, childs, purpose, booking_type, remarks, che... | `Join` the rooms table!
```
SELECT r.id, r.name, r.phone, r.email, r.address, r.country, r.adults, r.childs, r.purpose,
r.booking_type, r.remarks, r.checkin, r.checkout, r.room_id, r.status, r.paid, r.date,
rooms.number
FROM reservations r
JOIN rooms ON r.room_id = rooms.id
WHERE DATE_FORMAT(r.date, '%... | Change the query to include the room number by joining the two tables:
```
$query = "SELECT id, name, phone, email, address, country, adults, childs, purpose, booking_type, remarks, checkin, checkout, room_id, status, paid, date , ro.number AS number FROM reservations AS r JOIN rooms AS ro ON r.room_id=ro.id WHERE ... | Fetch value from another table inside this query | [
"",
"mysql",
"sql",
""
] |
I am a newbie to SQL. I got stuck in this question.
I have 2 SQL tables: users with (name,userid), blacklistID with (userid). I want to create a sql query that will only allow non-blacklisted users to login.
Any suggestions are highly welcomed. thanks !! | You can join the `users` and `blacklist` tables together, and then check to make sure that a given user did not match the blacklist:
```
SELECT u.name, u.userid
FROM users u LEFT JOIN blacklist b
ON u.userid = b.userid
WHERE u.name = 'username' AND b.userid IS NULL
```
If the above query returns a record for a gi... | You can use a `LEFT OUTER JOIN` to return your condition in the form of a variable using:
```
SELECT
u.userID,
isOnBlackList=CASE WHEN b.userID IS NULL THEN 1 ELSE 0 END
FROM
users u
LEFT OUTER JOIN blacklistID b ON b.userID=u.userID
WHERE
u.userID=@UserID
```
Or, If you wish to return an empty set ... | Create an SQL query which allows only specific users to login | [
"",
"sql",
"mysqli",
""
] |
Here's the situation:
So, in my database, a person is "responsible" for job X and "linked" to job Y. What I want is a query that returns: name of person, his ID and he number of jobs it's linked/responsible. So far I got this:
```
select id_job, count(id_job) number_jobs
from
(
select responsible.id
from responsible... | Try this way
```
select prs.id, prs.name, count(*) from Person prs
join(select process_no, id
from Responsible res
Union all
select process_no, id
from Linked lin ) a on a.id=prs.id
group by prs.id, prs.name
``` | ```
select id, name, count(process_no) FROM (
select pr.id, pr.name, res.process_no from Person pr
LEFT JOIN Responsible res on pr.id = res.id
UNION
select pr.id, pr.name, lin.process_no from Person pr
LEFT JOIN Linked lin on pr.id = lin.id) src
group by id, name
order by id
```
Query ain't tes... | Count how many times a value appears in tables SQL | [
"",
"sql",
""
] |
I have some search filters on my project. You can search Users by roles. If you search for `:admin` it will only return Users with role: `[:admin]`. But it WONT add the users to the search results with role: `[:admin, :mentor]`.
**Does anyone know how to make an SQL query that will find me all Users that have a role a... | You are probably passing only one role in `values`:
```
records.where(roles_mask: User.mask_for(value))
```
Make sure that `value` includes both:
```
records.where(roles_mask: User.mask_for([:admin, :mentor]))
``` | I found a way to do this
```
custom_filter :role, lambda { |records, value|
records.where("roles_mask & ? != 0", User.mask_for(value))
}
```
This will return all `Users` that have a role `admin`. Even if the User has 2 roles or even 3 roles like `[:admin, :mentor]` it will inlcude his user in the result. | Role Model Gem: How to get all Users with role: [:admin, :mentor] | [
"",
"sql",
"ruby-on-rails",
"ruby",
""
] |
```
CREATE OR REPLACE FUNCTION sumNumbers(p VARCHAR2) RETURN NUMBER IS
...
SELECT sumNumbers('3 + 6 + 13 + 0 + 1') FROM dual;
```
So the output should be: `23` | You can use a 'trick' with XML and XPath evaluation to do this without manually tokenising the string:
```
select * from xmltable('3 + 6 + 13 + 0 + 1' columns result number path '.');
RESULT
----------
23
```
Or:
```
select to_number(xmlquery('3 + 6 + 13 + 0 + 1' returning content).getStringVal()) as re... | You can extract the numbers with a hierarchical query and a regular expression and sum the results. Something like this:
```
WITH t AS (
SELECT '3 + 6 + 13 + 0 + 1' numbers FROM DUAL
)
SELECT SUM(TRIM(REGEXP_SUBSTR(numbers,'( ?[[:digit:]]+ ?)',1,LEVEL)))
FROM t
CONNECT BY LENGTH(SUBSTR(numbers,DECODE(REGEXP_INSTR(... | PL/SQL split a string by " + " and sum the numbers in it? | [
"",
"sql",
"oracle",
"plsql",
""
] |
I'm looking for a SQL solution for the following problem.
I want a list of employees who are more then 14 days sick in a row.
I've a sql table with the following:
```
First_name, Last_Name, INDIRECT_ID, SHIFT_DATE
John, Doe, Sick, 2016-01-01
John, Doe, Sick, 2016-01-02
John, Doe, working, 2016-01-03
John, Doe, Sick, ... | Try this,
First create all the 14 days intervals in between the From Date and To Date.
Then check the count of the 'Sick' is 14 in each interval for every employee.
```
DECLARE @ST_DATE DATE='2016-01-01'
,@ED_DATE DATE='2016-04-01'
;WITH CTE_DATE AS (
SELECT @ST_DATE AS ST_DATE,DATEADD(DAY,13,@ST_DA... | ```
declare @t table(First_name varchar(50), Last_Name varchar(50), INDIRECT_ID varchar(50), SHIFT_DATE date)
insert into @t values
('John', 'Doe', 'Sick', '2016-01-01')
,('John', 'Doe', 'Sick', '2016-01-02')
,('John','Doe','working','2016-01-03')
,('John', 'Doe', 'Sick', '2016-04-04')
,('John', 'Doe', 'Sick', '2016-0... | SQL getting status of a period | [
"",
"sql",
"sql-server",
""
] |
I have a table with some data. It could look for example like this:
```
7 Gelb
8 Schwarz
9 Weiß my color
10 Grau
16 Gelb I
17 Gelb II
18 Gelb III
19 Gelb IV
27 Schwarz I
28 Schwarz II
29 Schwarz III
30 Schwarz IV
31 Schwarz V
32 Schwarz VI
39 Weiß my color III
40 Weiß my ... | **update**
```
select * from dbo.test
Where value not Like '%[MDILXV]_' Collate SQL_Latin1_General_CP1_CS_AS
```
Step 1 :
```
select * from dbo.test
id value
1 Gelb
2 Gelb I
3 Weiß my color III
4 Weiß my color
```
When i give
```
select * from dbo.test
Where value not Like '%[I... | Here is my solution:
First, generate a list of Roman Numerals up to a specified limit. Then, extract the last *word* from your table and check if it exists in the list of Roman Numerals:
`ONLINE DEMO`
```
;WITH E1(N) AS(
SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N)
),
E2(N) AS(SELECT 1 FROM... | Extract values which do not end by specific words | [
"",
"sql",
"sql-server",
""
] |
I have a table which has duplicate values in one column, title, so the title column has multiple rows with the same values.
I want to delete all duplicates except one where the title is the same.
What sort of query can I perform to accomplish this?
```
Title Subject Description Create... | You can do a self-join `DELETE`:
```
DELETE t1
FROM mytable t1
JOIN (SELECT Title, MAX(Created_at) AS max_date
FROM mytable
GROUP BY Title) t2
ON t1.Title = t2.Title AND t1.Created_at < t2.max_date
```
[**Demo here**](http://sqlfiddle.com/#!9/e0c649/1) | Do a backup first, for obvious reasons, but this should work:
```
delete from your_table where id not in (select id from your_table group by title)
```
Where `id` is the column that stores the primary key for `your_table` | How can I delete all rows with duplicates in one column using MySQL? | [
"",
"mysql",
"sql",
""
] |
I need to write SQL to extract repeat location codes and separate out the sub-location detail. However, the data I am working with does not follow a set pattern.
Here's a sample of what the location codes look like (the real table has over 5,000 locations):
`JR-DY-TIN
DY-RHOLD
DY-PREQ-TIN
GLVCSH
GLFLR
GLBOX1
GLBOX2
G... | ```
DECLARE @LocationRef TABLE (Location NVARCHAR(20), Ref INT)
INSERT INTO @LocationRef VALUES
('JR-DY-TIN',0)
,('DY-RHOLD',0)
,('DY-PREQ-TIN',0)
,('GLVCSH',0)
,('GLFLR',0)
,('GLBOX1',6)
,('GLBOX2',6)
,('GLBOX3',6)
,('GLBOXA',6)
,('GLBOXB',6)
,('GLBOXC',6)
,('GLBOXD',6... | It seems like you want to use something like a `parseInt` feature, which is not available in `SQL Server 2008`. You can attempt to use `cast`, but that won't work with your datatype - `varchar`.
I'd suggest using a case statement to parse the complex logic you need. ie:
```
select
LocationCode,
case when left(Lo... | Parsing inconsistent data with SQL | [
"",
"sql",
"sql-server",
"t-sql",
"text-parsing",
""
] |
I have a log table like this:
```
line Date status Type
1 26.04.2016 08:58 IN 4
2 26.04.2016 08:59 OUT 80
3 26.04.2016 09:05 REZ 7
4 26.04.2016 09:06 IN 7
5 26.04.2016 09:22 EDIT 81
6 26.04.2016 09:23 EDIT 80
7 26.04.2016 09:24 OUT 80
8 26.04.2016 09:... | Ok, I can get line 6:
```
select min(date) from MYTABLE where date > (select max(date) from MYTABLE where type <> @lasttype)
```
Any more effective code?
Many thanks for your answers... | Try running this query
```
select max(a.Date) from
(
Select top 4 * from table order by Date desc
)a;
``` | SQL: Find min date of a last type change | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
So I don't know how to subtract two `time(hh:mm:ss)` in sql server.
This is my statement:
```
where
( CONVERT(TIME(7), [EndWork], 102)) - ( CONVERT(TIME(7), [StartWork], 102)) <
CONVERT(TIME(7), ' 8:30:00', 102)
``` | ```
DECLARE @END_DATE TIME = '' ,
@START_DATE TIME = ''
SELECT CONVERT(TIME,DATEADD(MS,DATEDIFF(SS, @START_DATE, @END_DATE )*1000,0),114)
``` | Using the [DATEDIFF](https://msdn.microsoft.com/en-us/library/ms189794.aspx) function you will get the difference of two dates/time in Year/Month/Day/Hour/Min/Sec as you required.
Eg:- `DATEDIFF ( MINUTE , startdate , enddate )` --will return the diff in minutes | how to subtract two time in sql server? | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
how to Add 1 month to the date value(1st row) and use it as the input to the next row to add the month till it reaches the maximum month id.
```
declare @tmp table (date date,month_id int);
insert into @tmp values('2014-11-30',1),('2014-11-30',2),('2014-11-30',3),('2014-11-30',4),('2014-11-30',5),('2014-11-30',6),('20... | Recursive CTE
```
declare @tmp table (date date,month_id int);
insert into @tmp values('2014-11-30',1),('2014-11-30',2),('2014-11-30',3),('2014-11-30',4),('2014-11-30',5),('2014-11-30',6),('2015-01-01',1),('2015-01-01',2),('2015-01-01',3),('2015-01-01',4);
;with cte as
(
select date, month_id, DATEADD(MONTH, 1, d... | You can try this
The `DATEADD()` function adds or subtracts a specified time interval from a date.
```
Declare @tmp table (date date,month_id int);
Insert into @tmp values('2014-11-30',1),('2014-11-30',2),('2014-11-30',3),('2014-11-30',4),('2014-11-30',5),('2014-11-30',6),('2015-01-01',1),('2015-01-01',2),('2... | Add 1 month to the date value | [
"",
"sql",
"sql-server",
""
] |
I have a query that pulls sales information for employees.
An example of the query would be:
```
Select Name, Customer_count, item1, item2, item3
from Invoices
```
Output:
```
Name Customer_Count item1 item2 item3
Rob 10 1 2 0
Bill 10 3 0 2
Jim... | You can use the `UNION ALL` clause and do the union of the two queries, and then use the result in the `FROM` sentence. For ordering the rows the way you want, you can simply add the primary key column (or columns) to each `SELECT` sentence and add a column that will contain the visible name. This `Visible_name` column... | This will get you pretty close.
```
select name, customer_count, item1, item2, item3
from
(
select
rownum = row_number() over (order by name),
name, customer_count, item1, item2, item3
from Invoices
union
Select rownum = row_number() over (order by name),
'', Customer_count,
Cast... | Multiple Queries using name as a link | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
i have the below table. (no primary key in this table)
```
ID | IC | Name | UGCOS | MCOS
---------------------------------------------------------
1AA | A123456B | Edmund | Australia | Denmark
1AA | A123456B | Edmund | Australia | France
2CS | C435664C | Grace ... | I'll create a second answer, as this approach is something completely different from my first:
This dynamic query will first find the max count of a distinct ID and then build a dynamic pivot
```
CREATE TABLE #tmpTbl (ID VARCHAR(100),IC VARCHAR(100),Name VARCHAR(100),UGCOS VARCHAR(100),MCOS VARCHAR(100))
INSERT INT... | This is a suggestion with a concatenated result:
```
CREATE TABLE #tmpTbl (ID VARCHAR(100),IC VARCHAR(100),Name VARCHAR(100),UGCOS VARCHAR(100),MCOS VARCHAR(100))
INSERT INTO #tmpTbl VALUES
('1AA','A123456B','Edmund','Australia','Denmark')
,('1AA','A123456B','Edmund','Australia','France')
,('2CS','C435664C',... | Use Dyamic Pivot query for this? | [
"",
"sql",
"sql-server",
"pivot",
"pivot-table",
""
] |
I need a method for managing sequences in a table. I have a table that needs to be managed by a sequence. I must be able to insert a row between two other rows.
if I have a numbered sequence from 1 to 10000, and I want to insert a row between 100 and 101. Or I want to move 99 to between 1 and 2.
Can this be managed in... | SQL Server tables **do not have any implicit order!**
The only way to enforce a sequence is a sortable column (or a combination of columns) with unique values.
One way to achieve this was to number your row after an existing sort key:
* add a column SortKey BIGINT (after filling it with values you should set it to `... | One way to accomplish this would be to have your sequence be non-contiguous. That is, specify an increment on the sequence to leave gaps enough to put your interleaving rows. If course this isn't perfect as you may exhaust your intra-row gaps, but it's a start. | MSSQL controlling sequence | [
"",
"sql",
"sql-server",
""
] |
I have a following table structure
```
id | sessionId | event | created_on
---|-----------|-------|--------------------
1 | 1 | view | 2016-01-01 12:24:01
2 | 1 | buy | 2016-01-01 12:25:05
3 | 2 | view | 2016-01-01 12:25:09
4 | 1 | view | 2016-01-01 12:27:10
......
```
I'm try... | A simple solution could be:
Take the minimum created\_at per sessionID where event is view and join it with the minimum created at per sessionID where event is buy. Use inner join to have only records with both...
> select A.sessionID,A.firstView,B.firstBuy, datedif(*depend on rdbms*) from
>
> (select sessionID,min(cr... | Rather common sql syntax which hopefully google-bigquery supports
```
select sessionId,
min(case event when 'view' then created_on end) as firstView,
min(case event when 'buy' then created_on end) as firstBuy
from t
where event in ('view', 'buy')
group by sessionId
having max(event) != min(event)
``` | Calculate time between two actions within session | [
"",
"sql",
"google-bigquery",
""
] |
I want to group by all the hours between 0 and 40 into one total sum.
41 - 50 into one total sum and 50+ into another sum.
```
select hours,
sum(hours)
from employee
where hours between 0 and 40
group by hours;
```
The above query groups by the hours, so i have the results split by hours, like if I have 1, ... | You can use a conditional aggregation, grouping by a value that builds intervals of hours.
By your example, you can have not integer values, so you should use explicit relational operators to have, for example, 40.1 in 40-50 group:
```
select sum(hours),
case
when hours <= 40 then '0-40'
whe... | ```
select sum(case when hours between 0 and 40 then hours else 0 end) hours_1,
sum(case when hours between 41 and 50 then hours else 0 end) hours_41,
sum(case when hours > 50 then hours else 0 end) hours_51
from employee
``` | Sum the total hours and group by hours | [
"",
"sql",
"oracle",
""
] |
When just looking up Oracle's INSERT syntax, I noticed you can insert into a query, e.g.
```
insert into (select * from dept) (deptno, dname) values (99, 'new department');
```
Can anybody shed some light on what this is meant for? What can I achieve with inserting into a query that I can't with inserting into the ta... | The subquery defines the columns of the table into which the rows are to be inserted. As [oracle's doc (12c)](https://docs.oracle.com/database/121/SQLRF/statements_9014.htm#SQLRF55057) says:
> Specify the name of the [...] column or columns returned by a
> subquery, into which rows are to be inserted. If you specify a... | Inserting into a subquery allows restricting results using [`WITH CHECK OPTION`](http://docs.oracle.com/database/121/SQLRF/statements_10002.htm#i2126149).
For example, let's say you want to allow any department name *except* for "new department". This example using a different value works fine:
```
SQL> insert into
... | Insert into a query | [
"",
"sql",
"oracle",
"insert",
""
] |
I'm trying to select data from a row and then using that value input another predefined data value into a variable. I've got this, not sure if it's the correct syntax for SQL though.
```
DECLARE @ID INT
DECLARE @server VARCHAR(15)
DECLARE response_cursor CURSOR
FOR SELECT col1, col3, col4 FROM [dbo].[tbl] WHERE [... | Theres a few issues here:
```
DECLARE @ID INT
DECLARE @server VARCHAR(15)
DECLARE response_cursor CURSOR
FOR SELECT col1, col3, col4 FROM [dbo].[tbl] WHERE [status] <> 'Decommission'
```
**For your first if**
```
IF col3 ='ABCD'
BEGIN SET @server = 'Server1'; END
```
**There is no ELSE/IF IN SQL that I am ... | You can use `CASE` statement for a cleaner code.
```
SELECT @server = (
CASE col3
WHEN '123' THEN 'ABC'
WHEN '456' THEN 'DEF'
WHEN '789' THEN 'GHI'
ELSE ''
END)
``` | Conditional Select Statement with if else | [
"",
"sql",
"sql-server-2012",
""
] |
I have two column in sql
```
year month
2016 4
2014 5
```
What I want to do now is to combine these two columns together and get the period
Output
```
year month result
2016 4 201604
2014 5 201405
```
Are there ways to do this? | If the column data types are integer, do
```
select year * 100 + month from tablename
``` | First, you need to `CAST` them to `VARCHAR` to allow concatenation. Then use `RIGHT` for `month` to pad the value with `0`:
```
WITH Tbl AS(
SELECT 2016 AS [year], 4 AS [month] UNION ALL
SELECT 2014, 5
)
SELECT *,
CAST([year] AS VARCHAR(4)) + RIGHT('0' + CAST([month] AS VARCHAR(2)), 2)
FROM Tbl
``` | How to combine two columns in sql | [
"",
"sql",
"sql-server",
""
] |
How do I write a query which will return the next date.
Here is example, I want query to populate the Next\_Date column
Thanks
```
Employee_ID Date Point Next_Date
53 07/31/2015 1 12/02/2015
53 12/02/2015 1 01/12/2016
53 01/12/2016 1 ... | Lead should work, depending on which DB you are using.
```
select
employee_id,
date,
point,
lead(date) over (partition by employee_id order by date) as next_date
from your_table
``` | You need a column to specify the order since a table has no inherent order. It seems not to be ordered by the `Date`-column, otherwise your first two records would have the wrong `Next_Date` since they are in the past.
So i assume that you have a primary key to determine the order.
Then you can use this query(`TOP`pr... | SQL Query to Show next date | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.