Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is it possible to refer a views column as a select statement for another view?
How about joining two views together in another view?
How can I refer to a view column. I have used GROUP\_CONCAT(column1) in the initial view but then couldnt refer to it later on. | > Yes it is possible. For reference go through [MySql Docs](http://dev.mysql.com/doc/refman/5.0/en/create-view.html)
but note that nesting views can cause serious performance penalties. | Yes, it is possible.
Without more detail, that's about as descriptive as I can be.
[BTW, I think this is something you could have found easily by searching.] | Can a view select statement contain another view? | [
"",
"mysql",
"sql",
""
] |
In Oracle we have the limitation of only 1000 items supported in the IN clause of SQL. I would like to know if there are any other such limitations in Oracle. | Various limits are documented here for 11.2: <http://docs.oracle.com/cd/B28359_01/server.111/b28320/limits003.htm>
Some edition-based limitations: <http://www.oracle.com/us/products/database/enterprise-edition/comparisons/index.html> | Limits for Oracle 10g:
<http://docs.oracle.com/cd/B19306_01/server.102/b14237/limits.htm>
Logical limits:
<http://docs.oracle.com/cd/B19306_01/server.102/b14237/limits003.htm>
Physical limits:
<http://docs.oracle.com/cd/B19306_01/server.102/b14237/limits002.htm> | ORACLE SQL,PL/SQL limitations | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have been facing a strange scenario when comparing dates in postgresql(version 9.2.4 in windows).
I have a column in my table say `update_date` with type `timestamp without timezone`.
Client can search over this field with only date (e.g: `2013-05-03`) or date with time (e.g.: `2013-05-03 12:20:00`).
This colum... | @Nicolai is correct about casting and why the condition is false for any data. i guess you prefer the first form because you want to avoid date manipulation on the input string, correct? you don't need to be afraid:
```
SELECT *
FROM table
WHERE update_date >= '2013-05-03'::date
AND update_date < ('2013-05-03'::date +... | When you compare `update_date >= '2013-05-03'` postgres casts values to the same type to compare values. So your '2013-05-03' was casted to '2013-05-03 00:00:00'.
So for update\_date = '2013-05-03 14:45:00' your expression will be that:
```
'2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '... | How to compare dates in datetime fields in Postgresql? | [
"",
"sql",
"database",
"postgresql",
"date",
""
] |
I have 2 tables , Users and Friends Table, Users have uID, Friends have UID as well, I want to check the UIDs present in Users table but not present in Friends Table,
I am using this query
```
SELECT b.userId
FROM users b
where b.userId NOT IN(
select userId
from user_friend
)
```
But it is returning me all th... | Try this
```
SELECT b.userId
FROM users b
WHERE NOT EXISTS (
SELECT *
FROM user_friend
WHERE b.userId = user_friend.userId
);
``` | Try this one:
```
SELECT b.userId
FROM users b
where b.userId NOT IN(
select user_friend.userId
from user_friend
)
``` | NOT IN not working SQL | [
"",
"mysql",
"sql",
"oracle",
"select",
"notin",
""
] |
Basic SQL question -- and I'm new at this, so please bear with me...
I'm trying to join two fields in this manner:
'Buyers' table:
```
Name Date
Greg Jan 01
John Jan 01
Greg Jan 02
```
'Purchases' table:
```
Name Date Product Qty
Greg Jan 01 Apple 2
Greg Jan 01 Banana 3
Joh... | Looks like you're trying to `pivot` your results. You can achieve this using `sum` with `case`:
```
select b.name,
b.date,
sum(case when product='Apple' then qty end) Apples,
sum(case when product='Banana' then qty end) Bananas
from buyers b
join purchases p on b.name = p.name and b.date = p.date
gro... | if Joined table names 'buyer\_purchases',then the sql looks like :
`select buyer_purchases.*,Purchases.* from buyer_purchases,Purchases where buyer_purchases.Name=Purchases.Name and buyer_purchases.Date=Purchases.Date;` | Simple Joining SQL on two fields | [
"",
"mysql",
"sql",
""
] |
I have a database representing retail items. Some items have multiple scancode, but are in essence the same item, ie. their name, cost, and retail will ALWAYS be the same. To model this, [the database has the following structure](http://sqlfiddle.com/#!2/3daa6/2):
```
Inventory_Table
INV_PK | INV_ScanCode | INV_Name ... | You're looking for a `union`:
```
SELECT it.INV_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail
FROM Inventory_Table AS it
UNION ALL
SELECT at.ALT_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail
FROM Inventory_Table AS it
INNER JOIN Alternate_Table AS at
ON at.INV_FK = INV_PK
```
`UNION ALL` is the fast... | ```
SELECT it.INV_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail
FROM Inventory_Table AS it
union all
SELECT at.ALT_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail
FROM Alternate_Table AS at
inner join Inventory_Table AS it on at.INV_FK = it.INV_PK
```
[SQL Fiddle](http://sqlfiddle.com/#!2/3daa6/6) | SQL JOIN to get a list of intventory items and alternate items | [
"",
"sql",
"join",
"foreign-keys",
"sybase",
""
] |
I have this table

and I want the 10 distinct rows with the highest score ordered descending.
So I tried
```
SELECT * FROM `highscores` GROUP BY userID ORDER BY score DESC LIMIT 10 ;
```
which is not correct because it returns:
![enter image des... | The right query is:
```
SELECT userName, userLastname, userID, MAX( score )
FROM `highscores`
GROUP BY userID
ORDER BY MAX( score ) DESC
LIMIT 10
```
Thanks to EddieJamsession's comment. | ```
SELECT a.*
FROM highscore a
INNER JOIN
(
SELECT userID, MAX(score) score
FROM highscore
GROUP BY userID
) b ON a.userID = b.userID
AND a.score = b.score
ORDER BY score DESC
LIMIT 10
```
*this does not handle ties, though.* | Distinct values of an SQL Table | [
"",
"mysql",
"sql",
"greatest-n-per-group",
""
] |
I have the following table in my database
```
" CREATE TABLE Q_GROUP ( Id INTEGER PRIMARY KEY ); "
```
This is only needed to ensure different Items are in the same group. Each time, when adding new items, I need to create a unique group. The items are then connected to this group. The usual syntax for adding items a... | Use `null` as placeholder
```
insert into Q_GROUP (Id)
values (null);
```
## [SQLFiddle demo](http://sqlfiddle.com/#!7/c8fda/1) | try like this,
```
insert into Q_GROUP values(1);
``` | SQ Lite insert just a single identifier | [
"",
"sql",
"database",
"sqlite",
"syntax-error",
"identifier",
""
] |
I have the following table:
```
Table1 Table2
CardNo ID Record Date ID Name Dept
1 101 8.00 11/7/2013 101 Danny Green
2 101 13.00 11/7/2013 102 Tanya Red
3 101 15.00 11/7/2013 103 Susan ... | Use:
```
select t2.Name, t2.Dept, min(t1.Record)
from table1 t1
join table2 t2 on t2.ID = t1.ID
group by t2.ID, t2.Name, t2.Dept
```
or
```
select t2.Name, t2.Dept, a.record
from table2 t2
join
(
select t1.ID, min(t1.Record) [record]
from table1 t1
group by t1.ID
)a
on a.ID = t2.ID
```
For filtering add... | Please try:
```
Select
b.Name,
b.Dept,
MIN(Record) Record
from
Table1 a join Table2 b on a.ID=b.ID
GROUP BY b.Name,
b.Dept
``` | Select the minimum value for each row join by another table | [
"",
"sql",
"join",
"group-by",
"multiple-tables",
"minimum",
""
] |
I want to merge the values of three different columns name **ProcessFalseRedirect,ProcessTrueRedirect,GeneralRedirectToPP** into a single column named as **PPID**.
The query i'm using is this,
```
select ProcessFalseRedirect,ProcessTrueRedirect,GeneralRedirectToPP from IVR_PPMaster
```
which gives me the following r... | The `UNION` can help you.
```
select ProcessFalseRedirect PPID from IVR_PPMaster
union
select ProcessTrueRedirect from IVR_PPMaster
union
select GeneralRedirectToPP from IVR_PPMaster
```
To get data in ascending order use this:
```
select PPID from
(
select ProcessFalseRedirect PPID from IVR_PPMaster
union
sel... | try this:
```
(SELECT ProcessFalseRedirect PPID FROM IVR_PPMaster WHERE ProcessFalseRedirect IS NOT NULL
UNION ALL
SELECT ProcessTrueRedirect FROM IVR_PPMaster WHERE ProcessTrueRedirect IS NOT NULL
UNION ALL
SELECT GeneralRedirectToPP FROM IVR_PPMaster WHERE GeneralRedirectToPP IS NOT NULL)
ORDER BY ProcessFalseRedire... | SQL Query to merge different column data in to one | [
"",
".net",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I am trying to create a table in Oracle SQL Developer but I am getting error ORA-00902.
Here is my schema for the table creation
```
CREATE TABLE APPOINTMENT(
Appointment NUMBER(8) NOT NULL,
PatientID NUMBER(8) NOT NULL,
DateOfVisit DATE NOT NULL,
PhysioName VARCHAR2(50) NOT NU... | Oracle does not support the `boolean` data type at schema level, though it is supported in PL/SQL blocks. By schema level, I mean you cannot create table columns with type as `boolean`, nor nested table types of records with one of the columns as `boolean`. You have that freedom in PL/SQL though, where you can create a... | Last I heard there were no `boolean` type in oracle. Use `number(1)` instead! | Boolean giving invalid datatype - Oracle | [
"",
"sql",
"oracle",
""
] |
I have a table in SQL SERVER "usage" that consists of 4 columns
```
userID, appid, licenseid, dateUsed
```
Now I need to query the table so that I can find how many users used an app under a license within a time frame. Bearing in mind that even if user 1 used the app on say january 1st and 2nd they would only count ... | Just tested this and provides your desired result:
```
SELECT appid, licenseid, COUNT(DISTINCT userID)
FROM usage
WHERE dateUsed BETWEEN @from AND @dateTo
GROUP BY appid, licenseid
``` | Something like this should work:
```
SELECT appid, licenseid, COUNT(DISTINCT userid) as DistictUsers
FROM yourTable
WHERE dateUsed BETWEEN @from AND @dateTo
GROUP BY appid, licenseid
``` | SQL count of distinct records against multiple criteria | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I use SQL Server 2008 R2 and SQL Server Business Intelligence Development Studio.
I create one project of `Business Intelligence Project`
I create a `Data Source` Of `Adventure Work 2008 DW` and then i create one `Data Source View`
and then i create one `Cube`.
I can `build` and `rebuild` my project but when i want... | I Fix this error with verify this way :
At First open `Data Source`

Then `Edit` connection string


And then ... | This error is regarding **"NT AUTHORITY\SYSTEM"**, so just go to relational database and expand Security folder.
[](https://i.stack.imgur.com/sPxzA.png)
Double click on **"NT AUTHORITY\SYSTEM"**, it will open **"Login Properties"** wizard, go to **"U... | OLE DB or ODBC error: Login failed for user 'NT AUTHORITY\NETWORK SERVICE | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
"ssas",
"olap",
""
] |
Error is
> Unknown column 'num' in 'where' clause
```
SELECT COUNT(*) AS num, books_bookid
FROM bookgenre_has_books
WHERE num > 10
GROUP BY books_bookid
```
What am I doing wrong? Thanks. | `WHERE` clause cant see aliases,use `HAVING`.
It is not allowable to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed
<http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html> | Try this, you should use the HAVING clause
```
SELECT COUNT(*) AS num, books_bookid
FROM bookgenre_has_books
GROUP BY books_bookid
HAVING COUNT(*) > 10
```
The SQL HAVING clause is used in combination with the SQL GROUP BY clause. It can be used in an SQL SELECT statement to filter the records that a SQL GROUP BY ret... | Unknown column error in this COUNT MySQL statement? | [
"",
"mysql",
"sql",
""
] |
I have two tables with a common id,
table1 has a task numbers column and table2 has documents column
each task can have multiple documents. I'm trying to find all task numbers that don't have a specific document
Fake data:
```
SELECT * FROM table1
id tasknumber
1 3210-012
2 3210-022
3 3210-032
SELECT * FROM t... | ```
SELECT t1.tasknumber
FROM table1 t1
LEFT JOIN table2 t2 ON t2.id = t1.id AND t2.document = 'SB'
WHERE t2.id IS NULL;
```
There are basically four techniques:
* [Select rows which are not present in other table](https://stackoverflow.com/questions/19363481/select-rows-which-are-not-present-in-other-table/1936... | ```
select t1.tasknumber from table1 t1
where not exists
(select 1 from table2 t2 where t1.id = t2.id and t2.document = 'SB')
``` | SQL View to find missing values, should be simple | [
"",
"sql",
"sql-server",
"sql-server-2000",
""
] |
Im looking for a query to gave me the last day result.
the query can be run in any time of day so it shouldnt be hour dependent
and the result must be from starting point of last day and start of today.
i find this , is this give the exact result ?
```
WHERE Date between
select dateadd(d, -2, CAST(GETDATE() AS DATE))
... | try something like this:
```
select * from mytable where mydate >= DATEADD(day, -1, convert(date, GETDATE()))
and mydate < convert(date, GETDATE())
``` | if i understood your problem correctly..Add below condition to your select query
```
WHERE Date >=(select dateadd(d, -1, CAST(GETDATE() AS DATE))) AND Date < GETDATE()
``` | sql query to get exactly the last day result | [
"",
"sql",
"sql-server-2008",
""
] |
I have a table like this:
```
date(timestamp) Error(integer) someOtherColumns
```
I have a query to select all the rows for specific date:
```
SELECT * from table
WHERE date::date = '2010-01-17'
```
Now I need to count all rows which Error is equal to 0(from that day) and divide it by count of all rows(from that ... | what about this (if `error` could be only 1 and 0):
```
select
date,
sum(Error)::numeric / count(Error) as "Percentage of failure"
from Table1
group by date
```
or, if `error` could be any integer:
```
select
date,
sum(case when Error > 0 then 1 end)::numeric / count(Error) as "Percentage of failure"
fro... | try this
```
select cast(data1.count1 as float)/ cast(data2.count2 as float)
from (
select count(*) as count1 from table date::date = '2010-01-17' and Error = 0) data1,
(select count(*) as count1 from table date::date = '2010-01-17') data2
``` | Divide two counts from one select | [
"",
"sql",
"postgresql",
"select",
"percentage",
""
] |
```
SELECT SUM(orders.quantity) AS num, fName, surname
FROM author
INNER JOIN book ON author.aID = book.authorID;
```
I keep getting the error message: "you tried to execute a query that does not include the specified expression "fName" as part of an aggregate function. What do I do? | The error is because `fName` is included in the `SELECT` list, but is not included in a `GROUP BY` clause and is not part of an aggregate function (`Count()`, `Min()`, `Max()`, `Sum()`, etc.)
You can fix that problem by including `fName` in a `GROUP BY`. But then you will face the same issue with `surname`. So put bot... | I had a similar problem in a MS-Access query, and I solved it by changing my equivalent `fName` to an "Expression" (as opposed to "Group By" or "Sum"). So long as all of my fields were "Expression", the Access query builder did not require any `Group By` clause at the end.. It can't return a complex part of the parse tree of something else, like an `ORDER BY` clause of a `SELECT` statement.
It looks like you just need:
```
ORDER BY
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,
CASE... | Another simple example from [here..](http://codechef4u.com/post/2015/04/07/order-by-clause-with-case-expressions-case-statement)
```
SELECT * FROM dbo.Employee
ORDER BY
CASE WHEN Gender='Male' THEN EmployeeName END Desc,
CASE WHEN Gender='Female' THEN Country END ASC
``` | CASE WHEN statement for ORDER BY clause | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I have a requirement to show a report in the following format from the two different tables as shown below, the below report should count the order numbers by branch.
```
===================================================================
Branch OrdersCountInTable1 OrdersCountInTable2
===================... | One *more or less generic* way to do it
```
SELECT COALESCE(t1.branch, t2.branch) branch,
COALESCE(t1.ordercount, 0) OrdersCountInTable1,
COALESCE(t2.ordercount, 0) OrdersCountInTable2
FROM
(
SELECT branch, COUNT(orderno) ordercount
FROM Table1
GROUP BY branch
) t1 FULL JOIN
(
SELECT branc... | Do like this using SUM aggregate function and UNION ALL operator
```
SELECT Branch,
SUM( CASE tag WHEN 'table1' THEN 1 ELSE 0 END) as OrdersCountInTable1,
SUM( CASE tag WHEN 'table2' THEN 1 ELSE 0 END) as OrdersCountInTable2
FROM
(
SELECT Branch,'table1' as tag
FROM Table1
UNION ALL
SELECT Branch,'tab... | Group By from two tables | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
""
] |
I am using the below SQL Query to get the data from a table for the last 7 days.
```
SELECT *
FROM emp
WHERE date >= (SELECT CONVERT (VARCHAR(10), Getdate() - 6, 101))
AND date <= (SELECT CONVERT (VARCHAR(10), Getdate(), 101))
ORDER BY date
```
The data in the table is also holding the last year data.
... | Instead of converting a `date` to a `varchar` and comparing a `varchar` against a `varchar`. Convert the `varchar` to a `datetime` and then compare that way.
```
SELECT
*
FROM
emp
WHERE
convert(datetime, date, 101) BETWEEN (Getdate() - 6) AND Getdate()
ORDER BY
date
``` | Why convert to varchar when processing dates? Try this instead:
```
DECLARE @Now DATETIME = GETDATE();
DECLARE @7DaysAgo DATETIME = DATEADD(day,-7,@Now);
SELECT *
FROM emp
WHERE date BETWEEN @7DaysAgo AND @Now
ORDER BY date
``` | SQL Output to get only last 7 days output while using convert on date | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have two table as follows:
```
- tblEmployee
employeeID | Name
10 | sothorn
20 | lyhong
30 | sodaly
40 | chantra
50 | sangha
60 | bruno
- tblSale
ID | employeeID | employeeSaleID
... | Simply select all rows of the `tblSale` table, and join `tblEmployee` table twice:
```
SELECT s.ID, e1.Name, e2.Name
FROM tblSale s
INNER JOIN tblEmployee e1
ON e1.employeeID = s.employeeID
INNER JOIN tblEmployee e2
ON e2.employeeID = s.employeeSaleID
``` | Here is a sample query on your data.
<http://sqlfiddle.com/#!2/b74ca/5/0> | How to do one select two query with join table | [
"",
"mysql",
"sql",
""
] |
I need to extract everything after the last '=' (<http://www.domain.com?query=blablabla> - > blablabla) but this query returns the entire strings. Where did I go wrong in here:
```
SELECT RIGHT(supplier_reference, CHAR_LENGTH(supplier_reference) - SUBSTRING('=', supplier_reference))
FROM ps_product
``` | ```
select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;
```
Please use [this](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_substring-index) for further reference. | Try this (it should work if there are multiple '=' characters in the string):
```
SELECT RIGHT(supplier_reference, (CHARINDEX('=',REVERSE(supplier_reference),0))-1) FROM ps_product
``` | SQL SELECT everything after a certain character | [
"",
"mysql",
"sql",
"substring",
"string-length",
""
] |
I have a table "`Customers`".
It has a column name "`CreatedDate`", means it is a joining date of customer.
I want to calculate how many customer are between 1-5 years, 6-10 years, 11-15 years from current date to ceateddate, like below
```
Years No of Customer
0-5 200
6-10 500
11-15 ... | something like this:
```
with cte as (
select ((datediff(yy, CreatedDate, getdate()) - 1) / 5) * 5 + 1 as d
from Customers
)
select
cast(d as nvarchar(max)) + '-' + cast(d + 4 as nvarchar(max)),
count(*)
from cte
group by d
```
**`sql fiddle demo`** | Try this
```
SELECT '0-5' as [Years],COUNT(Customer) as [No of Customers] FROM dbo.Customers WHERE DATEDIFF(YY,CreatedDate,GETDATE()) <=5
UNION
SELECT '6-10' as [Years],COUNT(Customer) as [No of Customers] FROM dbo.Customers WHERE DATEDIFF(YY,CreatedDate,GETDATE()) >=5 AND DATEDIFF(YY,CreatedDate,GETDATE()) <=10
UN... | Sql query to get number of customers according to joining date | [
"",
"sql",
"sql-server",
""
] |
I want to select data from one table (T1, in DB1) in one server (Data.Old.S1) into data in another table (T2, in DB2) in another server (Data.Latest.S2). How can I do this ?
Please note the way the servers are named. The query should take care of that too. That is,
SQL server should not be confused about fully qualifi... | create a [linked server](http://msdn.microsoft.com/en-us/library/aa560998.aspx). then use an [openquery](http://technet.microsoft.com/en-us/library/ms188427.aspx) sql statement. | Use Sql Server Management Studio's Import feature.
1. right click on database in the object explorer and select import
2. select your source database
3. select your target database
4. choose the option to 'specify custom query' and just select your data from T1, in DB1
5. choose your destination table in the destinati... | Select into from one sql server into another? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
There are two tables `JOB` and `WORKER`.
JOB table
* JOBID
WORKER table
* WORKERID
* JOBID (FK from JOB table)
* VACATION ('Y' or 'N')
With these two tables, I want to find a list of jobs that no workers are now assigned.
I made the following query, but it seems inefficient and verbose because of aggregate functio... | Select \*
From job
Where jobid not in( select distinct jobid from worker)
Thats it. | Have a look here, hope it helps
```
SELECT JOBID
FROM JOB
WHERE JOBID NOT IN (
SELECT j.JOBID
FROM JOB j
JOIN WORKER w ON j.JOBID = w.JOBID
WHERE w.VACATION = 'N'
GROUP BY j.JOBID
)
```
Sqlfiddle example: [**EXAMPLE**](http://sqlfiddle.com/#!2/81aa3/4) | Select items that do not meet conditions | [
"",
"sql",
"t-sql",
""
] |
I need to get a list of Customers who have never had an Order Exported
I am passing in a list of CustomerNumbers, grab them join on Orders then I am grouping - I feel like I am close but not sure how to get just Customers where none of the Orders.Exported is set to 1.
Here is what I have so far:
```
SELECT Customers... | You could use `Having Min(IsNull(Orders.Exported,0))` *with* a `Left Join` and *remove grouping by* `Orders.Exported` to filter out customers who has exported orders before.
Logically your count will always be 0 and so you don't need to count.
```
SELECT Customers.CustomerID, Min(IsNull(Orders.Exported,0)) Exported, ... | ```
WHERE Customers.CustomerNumber IN (SELECT * FROM dbo.Split(REPLACE(@CustomerNumbers,'\',''),','))
AND Customers.ManufacturerID=@ManufacturerID
AND Customers.Source = 'ipad'
AND Orders.Exported is NuLL
``` | find Customers where none of the Orders have been Exported | [
"",
"sql",
"sql-server-2008",
""
] |
I have a table with some numerical values (diameters)
18
21
27
34
42
48
60
76
89
114
etc...
How Can I select the max nearest value if I put for example in a text.box a number.
25 to select 27, 100 to select 114, 48 to select 48.
I put the following code but it is not acting correct ...It is selecting the closest near... | Lets say you were using SQL Server, you could try something like
```
strSQL = "SELECT TOP 1 * " & "FROM [materials] WHERE [dia] >= " & Me.TextBox1.Text & " ORDER BY dia ASC"
```
If it was MySQL You would have to use [LIMIT](http://dev.mysql.com/doc/refman/5.5/en/select.html)
> The LIMIT clause can be used to constra... | ```
strSQL = "SELECT TOP 1 * FROM materials " & _
"WHERE dia >= " & Me.TextBox1.Text & " " & _
"ORDER BY dia"
``` | max nearest values sql | [
"",
"sql",
"vba",
""
] |
I have created two indexes on different materialized views with the same name in TimesTen and now cannot drop neither of them. If try to I get the following error message:
```
2222: Index name is not unique
```
Could you please advise me how could I get rid of one (or at least both) of these indexes?
Thank you! | Oracle doesn't permit the creation of index with the same name in the same schema. Are your indexes in seperate schemas? if Yes, then please specify your schema.index\_name while deletion.To check the schemas of index , you can query all\_indexes.
select \* from all\_indexes where index\_name = 'put your index name he... | To drop indexes for Materialized Views [or tables] of the same name in two different schemas, you need to either:
1. Log into the first schema and drop the MV index
Log into the second schema and drop the MV index
2. As the instance administrator [the OS user who you installed TimesTen as]
and qualify the index ... | 2222: Index name is not unique (TimesTen) | [
"",
"sql",
"database",
"oracle",
"indexing",
"timesten",
""
] |
i have a table that have the following columns and sample data.
(this data is output of a query so i have to use that query in FROM () statement)
```
Type| Time | Count
--------------------------------
1 |2013-05-09 12:00:00 | 71
2 |2013-05-09 12:00:00 | 48
3 |2013-05-09 12:00:00 | 10
3 |2013-05... | You need SUM(Count), not SUM(1):
```
SELECT
SUM(IF (AlarmType = '1',Count,0)) as AlarmType1,
SUM(IF (AlarmType = '2',Count,0)) as AlarmType2,
SUM(IF (AlarmType = '3',Count,0)) as AlarmType3,
AlarmHour
FROM 'Table1'
GROUP BY Time
``` | Your `table1` is your subquery right? Well it has to have its alias so it will be something like that
```
SELECT
SUM(IF (AlarmType = '1',1,0)) as AlarmType1,
SUM(IF (AlarmType = '2',1,0)) as AlarmType2,
SUM(IF (AlarmType = '3',1,0)) as AlarmType3,
AlarmHour
FROM (subquery giving table1) as subTable
GROUP BY subtabl... | Multiple Count based on value MYSQL | [
"",
"mysql",
"sql",
""
] |
I have a simple application in which users submit data into a table.
There are currently 3 fields the user can pass values to at the moment. I'm trying to find a solution where the number of description columns can vary, depending on the description list created by the user.
So far I have considered:
1. having the u... | Definitely option #2. Normalizaing is always the best option in a scenario like this. You are correct that it is more work, but you are overcoming the inevitable issue when you will need more than 15 descriptions. | The second solution is preferable in terms of flexibility. If tomorrow you need to add more description fields with the first solution you will need to modify the table and the code to manage it.
The second solution can require a bit more work now but then it will handle 2 like 200 descriptions.
The first approach is... | Database design, variable number of columns | [
"",
"mysql",
"sql",
"database-design",
""
] |
I need to select one of the table column value together with some constant variable. For example,
SQL Table :
```
Key KeyName
-------------
1 Normal
2 Basic
3 Super
```
Constant values are R1, R2, R3, R4.
The output result as single column:
```
Normal R1
Normal R2
Normal R3
Normal R4
Basic R1
Basic R2
... | Try this:
```
SELECT
T.KeyName,
TT.ConstValues
FROM Tbl T
CROSS JOIN
(VALUES ('R1'), ('R2'), ('R3'), ('R4')) TT(ConstValues)
```
**[SQL FIDDLE DEMO](http://sqlfiddle.com/#!6/d8e19/1)** | You need to represent the constant values as a result-set, then you can get the cartesian product by selecting from both of them. For example:
```
WITH ConstantValues AS
(
SELECT 'R1' AS ConstantValue
UNION ALL
SELECT 'R2'
UNION ALL
SELECT 'R3'
UNION ALL
SELECT 'R4'
)
SELECT t.KeyName, c.Const... | Select query with constant variable | [
"",
"sql",
"sql-server",
""
] |
I have `Book` and `Author` tables. `Book` have many `Author`s (I know that it should be many-to-many it's just for the sake of this example).
How do I select all books that have been written by authors: X **and** by Y in one sql query?
**EDIT**
Number of authors can be variable - 3, 5 or more authors.
I can't figur... | Try this:
```
SELECT
B.Name
FROM Books B
JOIN Authors A
ON B.AuthorID = A.ID
WHERE A.Name IN ('X', 'Y')
GROUP BY B.Name
HAVING COUNT(DISTINCT A.ID) = 2
``` | You can just double join the authors table.
```
SELECT Book.* from Book
JOIN Author author1
ON author1.book_id = Book.id AND author1.author_name = 'Some Name'
JOIN Author author2
ON author2.book_id = Book.id AND author1.author_name = 'Some Other Name'
GROUP BY Book.id
```
The JOINs ensure th... | Select books having specified authors | [
"",
"sql",
""
] |
```
select packageid,status+' Date : '+UpdatedOn from [Shipment_Package]
```
The below error is appeared when executing the above code in sql server. The type of `UpdatedOn` is `DateTime` and status is a `varchar`. We wanted to concatenate the status, Date and UpdatedOn.
error:
> Conversion failed when converting da... | You need to convert `UpdatedOn` to `varchar` something like this:
```
select packageid, status + ' Date : ' + CAST(UpdatedOn AS VARCHAR(10))
from [Shipment_Package];
```
You might also need to use [`CONVERT`](http://msdn.microsoft.com/en-us/library/ms187928.aspx) if you want to format the datetime in a specific forma... | To achive what you need, you would need to CAST the Date?
Example would be;
Your current, incorrect code:
```
select packageid,status+' Date : '+UpdatedOn from [Shipment_Package]
```
Suggested solution:
```
select packageid,status + ' Date : ' + CAST(UpdatedOn AS VARCHAR(20))
from [Shipment_Package]
```
[MSDN art... | SQL Server: How to concatenate string constant with date? | [
"",
"sql",
"sql-server",
"sql-server-2008r2-express",
""
] |
I have a table in a database that has 9 columns containing the same sort of data, these values are **allowed to be null**. I need to select each of the non-null values into a single column of values that don't care about the identity of the row from which they originated.
So, for a table that looks like this:
```
+--... | You can use the UNPIVOT function to get the final result:
```
select value
from yourtable
unpivot
(
value
for col in (I1, I2, I3)
) un
order by id, col;
```
Since you are using SQL Server 2008+, then you can also use CROSS APPLY with the VALUES clause to unpivot the columns:
```
select value
from yourtable
cross... | ```
SELECT value FROM (
SELECT ID, 1 AS col, I1 AS [value] FROM t
UNION ALL SELECT ID, 2, I2 FROM t
UNION ALL SELECT ID, 3, I3 FROM t
) AS t WHERE value IS NOT NULL ORDER BY ID, col;
``` | Select values from multiple columns into single column | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
"unpivot",
""
] |
I'm currently working on a query which takes all the relevant data AND stock levels within a query, rather than looping over the stock levels separately. So far I have managed to obtain those stock levels by doing this:
```
<cfquery datasource="datasource" name="get">
Select *,
(
Select IsNull(Sum(stoc... | To reference an alias, use a derived table:
```
select * from
(Select *,
(
Select IsNull(Sum(stocklevel), 0)
From itemstock
Where item_id = itemstock_itemid
) As stock_count
From items
Where item_id = <cfqueryparam value="#URL.item_id#">
) derived_table
where stock_count > 0
```
Note that my query param ... | You cannot reference 'get.' inside the query. I think if you just reference stock\_count you should be fine? | SQL reference to alias name in the WHERE clause | [
"",
"mysql",
"sql",
"coldfusion",
"coldfusion-10",
""
] |
I am working on magento platform.I face a problem regarding values insertion to specific field: My query run perfect but one specific column not working for any query.I try my best but didn't find why .When i change the column type from int to varchar type it works.This is my table structure.
```
CREATE TABLE `followu... | the whole query is ok
```
CREATE TABLE `followupemails_emaillogs` (
`id` int NOT NULL AUTO_INCREMENT,
`schedule_time` datetime DEFAULT NULL,
`sent_time` datetime DEFAULT NULL,
`email_status` varchar(100) DEFAULT NULL,
`client_name` varchar(250) DEFAULT NULL,
`client_email` varchar(250) DEFAULT NULL,
`follo... | Try like this
To Create,
```
CREATE TABLE followupemails_emaillogs (
id int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
schedule_time datetime DEFAULT NULL,
sent_time datetime DEFAULT NULL,
email_status varchar(100) DEFAULT NULL,
client_name varchar(250) DEFAULT NULL,
client_email varchar(250) DEFAULT NULL,
... | Field not inserting or updating , int type in sql | [
"",
"mysql",
"sql",
"magento",
""
] |
I'm sure this is simple SQL, but I have a table which contains multiple records for each of X (currently 3) levels. I basically want to copy this to csv files, one for each level.
I've got the SQL which selects and I can copy that out. I can also do a select to get the list of unique levels in the file. What I can't w... | I don't know why you have all the text/endtext. You can just build your SQL-Select as one long statement... just use a semi-colon at the end of each line to indicate that the statement continues on the following line (unlike in C# that ; indicates end of statement)...
Anyhow, this simplified should do what you have
`... | Try something like:
```
FOR curlevel = 1 TO numlevels
outfile = 'file' + ALLTRIM(STR(curlevel)) + '.csv'
TEXT TO contents
blah blah
ENDTEXT
= STRTOFILE(contents, outfile)
ENDFOR
```
You'll have to adjust things, but that's a technique to use. | Splitting a foxpro table | [
"",
"sql",
"foxpro",
""
] |
I am having an issue with using inner selects where the output isn't quite right. Any help would be greatly appreciated.
Here is my [SQLFiddle](http://sqlfiddle.com/#!2/19f3d/1) example.
Here is the query I am using.
```
SELECT
t.event as event_date,
count((
SELECT
count(s.id)
FROM mytable s
WHE... | Can simplify a bit and exclude the sub-selects using conditional aggregation:
```
SELECT
t.event as event_date,
SUM(t.type = 2) AS type_count,
SUM(t.type != 3)AS non_type_count
FROM mytable t
WHERE t.event >= '2013-10-01' AND t.event <= '2013-10-08'
GROUP BY t.event
```
Demo: [SQL Fiddle](http://sqlfiddl... | Try this way:
```
SELECT
t.event as event_date,
SUM( case when type = 2 then 1 else 0 end )
AS type_count,
SUM( case when type != 3 then 1 else 0 end )
as non_type_count
FROM mytable t
WHERE t.event >= '2013-10-01' AND t.event <= '2013-10-08'
GROUP BY t.event
```
demo: --> <http://sqlfiddle... | Query counts using inner selects | [
"",
"mysql",
"sql",
""
] |
I want to create a user and only allow them to use select statements on the `cameracircle` database. So I have the following code:
```
CREATE USER 'hoeym'@'localhost' IDENTIFIED BY 'password';
CREATE DATABASE cameracircle;
GRANT SELECT ON cameracircle TO 'hoeym'@'localhost';
```
But the phpmyadmin doesn't like that. ... | Solved it with
```
GRANT SELECT ON cameracircle.* TO 'hoeym'@'localhost';
``` | Before you issue a GRANT statement, check that the
> derby.database.sqlAuthorization
property is set to true. The derby.database.sqlAuthorization property enables the SQL Authorization mode. | SQL Grant SELECT | [
"",
"mysql",
"sql",
"phpmyadmin",
"easyphp",
""
] |
I'm a bit stumped how I might go about this.
I have a very basic query, that currently returns sales for each product, by year and month.
It is grouping by year/month, and summing up the quantity.
This returns one row for each product/year/month combo where there was a sale.
If there was no sale for a month, then the... | Thank your for your suggestions.
I managed to get this working using another method.
```
Declare @DateFrom datetime, @DateTo Datetime
Set @DateFrom = '2012-01-01'
set @DateTo = '2013-12-31'
select
YearMonthTbl.YearMonth,
orders.vad_variant_code,
orders.qty
From
(SELECT Convert(CHAR(4),DATEADD(MONTH, x.number, @D... | You can generate this by using CTE.
You will find information on this article :
<http://blog.lysender.com/2010/11/sql-server-generating-date-range-with-cte/>
Especially this piece of code :
```
WITH CTE AS
(
SELECT @start_date AS cte_start_date
UNION ALL
SELECT DATEADD(MONTH, 1, cte_start_date)
FROM C... | Return All Months & Years Between Date Range - SQL | [
"",
"sql",
"sql-server",
"date",
""
] |
I need to calculate the local time from yyyymmddhhmmss and return it as yyyymmddhhmmss. I have tried the below, it is working but I am not able to get rid of the month name.
```
Declare @VarCharDate varchar(max)
Declare @VarCharDate1 varchar(max)
Declare @VarCharDate2 varchar(max)
--Declare
set @VarCharDate = '2... | Try this -
```
Declare @VarCharDate varchar(max)
Declare @VarCharDate1 varchar(max)
Declare @VarCharDate2 varchar(max)
--Declare
set @VarCharDate = '20131020215735' --- YYYYMMDDHHMMSS
--Convert
set @VarCharDate1 =(select SUBSTRING(@VarCharDate,0,5) + '/' + SUBSTRING(@VarCharDate,5,2) + '/' + SUBSTRING(@VarChar... | ```
Declare @VarCharDate varchar(max)
Declare @VarCharDate1 varchar(max)
Declare @VarCharDate2 datetime
--Declare
set @VarCharDate = '20131020215735' --- YYYYMMDDHHMMSS
--Convert
set @VarCharDate1 =(select SUBSTRING(@VarCharDate,0,5) + '/' + SUBSTRING(@VarCharDate,5,2) + '/' + SUBSTRING(@VarCharDate,7,2) +... | Convert datetime to yyyymmddhhmmss in sql server | [
"",
"sql",
"sql-server",
"datetime",
"gmt",
""
] |
Given
```
CREATE TABLE Parent (
Id INT IDENTITY(1,1) NOT NULL
Name VARCHAR(255)
SomeProp VARCHAR(255)
)
CREATE TABLE Child (
Id INT IDENTITY(1,1) NOT NULL
ParentId INT NOT NULL
ChildA VARCHAR(255)
ChildZ VARCHAR(255)
)
```
I wish to write a stored procedure that accepts... | Your naïve approach looks OK, except that you don't have a UNIQUE constraint on `Parent.Name`, which means you could have duplicate parent names, but would only return children matching the first Id you find. Also there is a syntax error on your first SELECT, which should be:
```
SELECT @id = Id FROM Parent WHERE Name... | You could use a join like this and never select the id.
```
SELECT *
FROM Child c
JOIN Parent p on c.ParentId = P.Id
WHERE p.Name = @name
``` | Return Parent and Child from Stored Procedure | [
"",
"sql",
"sql-server",
""
] |
Need a query that lists all the dates of the past 12 months
say my current date is 10-21-2013. need to use sysdate to get the data
The result should look like
```
10/21/2013
...
10/01/2013
09/30/2013
...
09/01/2013
...
01/31/2013
...
01/01/2013
...
11/30/2012
...
11/01/2012
```
Please help me with this..
Thanks in ... | Allowing for leap years and all, by using add\_months to work out the date 12 months ago and thus how many rows to generate ...
```
select trunc(sysdate) - rownum + 1 the_date
from dual
connect by level <= (trunc(sysdate) - add_months(trunc(sysdate),-12))
``` | You could do something like this:
```
select to_date('21-oct-2012','dd-mon-yyyy') + rownum -1
from all_objects
where rownum <=
to_date('21-oct-2013','dd-mon-yyyy') - to_date('21-oct-2012','dd-mon-yyyy')+1
```
of course, you could use parameters for the start and end date to make it more usable.
-or- using sysda... | dates of past 12 months in oracle | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I have a web portal that should display only time if the date is today's date otherwise it should display date .
```
dossier_date_created | Expected result
----------------------------------------------------
2013-10-22 16:18:46.610 | 2013-10-22
2013-10-23 11:26:56.390 | 11:26
```
I tried someth... | You can just use `CAST` or `CONVERT` to get your values to `DATE` or `TIME` datatypes. But, since you can't combine two data types in same column you have to cast them both to something identical - like `NVARCHAR` afterwards:
```
SELECT CASE WHEN CAST(dossier_date_created AS DATE) = CAST(GETDATE() AS DATE)
... | This works fine for me:
```
select
case
when (CONVERT(date,PaymentDate) = CONVERT(DATE,getdate()))
then convert(VARCHAR(15), PaymentDate, 108)
else convert(varchar, PaymentDate, 101)
end as timedate
from Payments
```
Hope it will help you.. :) | only date and only time in same column - sql server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have the following table:
```
CREATE TABLE posts...
id INT(11),
time DATETIME,
...
```
And I want to know the highest ID in general, and I also want to know the latest post disregarding posts from the last hour so I can subtract them to get the number of posts from the past hour.
I could do two queries:
```
SELEC... | Try this::
```
Select
(SELECT MAX(id) AS max from posts),
(SELECT
MAX(id) AS old_max
FROM posts WHERE time <
DATE_SUB(NOW(), INTERVAL 1 HOUR));
``` | How about this;
```
SELECT (
SELECT MAX(id) AS old_max FROM posts WHERE time <
DATE_SUB(NOW(), INTERVAL 1 HOUR)),
(SELECT MAX(id) AS max FROM posts)
``` | JOIN the same statement without WHERE clause | [
"",
"mysql",
"sql",
""
] |
I want to move data from Column Col11 of DB1.Table1 into Col555 of DB2.Table7, based on a certain condition. How do I do it ? Is there a statement like -
```
select Col11 from DB1.Table1
into Col555 of Db2.Table7
where Col11 = 'Important'
``` | You don't need `COPY` or `INSERT` but `UPDATE`(using JOIN):
```
UPDATE [DB2].[Table7]
SET [Table7].[Col555] = [Table1].[Col11]
FROM [Table1] JOIN [Table7] ON -- add the base for the join here...
WHERE [Table1].[Coll] = 'Important'
```
See this post for more details: [SQL update query using joins](https://stackoverflo... | ```
INSERT INTO [DB2].[Table7] (Col555)
SELECT [Table1].[Col11]
FROM [DB1].[Table1]
WHERE [Table1].[Coll] = 'Important'
```
--May need .[dbo] or schema name between database and table names. | Copy data from one column into another column | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I see multiple topics on this issue, where you have tested with a database, and now want to reset the ids.
There are a lot of ways to do this with codes, but isn't there a way to do this manually in sql server 2008? So to just go to your table(/content) and reset the id's + clear the values.
Atm, I can only go into m... | Basically - you need to run the [DBCC checkident](http://technet.microsoft.com/en-us/library/ms176057.aspx) to get the database engine to reseed.
```
DBCC CHECKIDENT ('<your table>', RESEED, <new seed>);
``` | On SQL server, if you are deleting all data and resetting an identity column, I would use Truncate
<http://technet.microsoft.com/en-us/library/ms177570.aspx> | Reset IDENTITY columns Manually | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Suppose I write a query that finds the names of all artists which have members who were not born in the 1960s and another query to find the names of all artists which do not have any members born in the 1960s.
So we are speaking of these three tables:
## Artists
```
ArtistID, ArtistName, Region, EntryDate
```
## Me... | The question seems not to be looking for code. The question is:
> But what would be true of any artist that appeared in the results of the first query but not in the results of the second?
So, the first query gets all artists with SOME members not born in 1960. The second query gets all artists WITH NO member born in... | Each can be done with an IN or NOT IN condition:
```
-- Artists with NO members born in the 60s
SELECT * FROM Artists
WHERE ArtistID NOT IN (
SELECT ArtistID
FROM XrefArtistsMembers x
INNER JOIN Members m ON x.MemberId = m.MemberID
WHERE year(birthday) BETWEEN 1960 AND 1969)
-- Artists with ANY memb... | SQL difficult JOIN tables | [
"",
"sql",
""
] |
Given this table structure:
```
Table A
ID AGE EDUCATION
1 23 3
2 25 6
3 22 5
Table B
ID AGE EDUCATION
1 26 4
2 24 6
3 21 3
```
I want to find all matches between the two tables where the age is within 2 and the education is within 2. However, I do not want... | As @Joel Coehoorn said earlier, there has to be a mechanism that selects which pairs of (a,b) with the same (b) are filtered out from the output. SQL is not great on allowing you to select ONE row when multiple match, so a pivot query needs to be created, where you filter out the records you don't want. In this case, f... | In SQL-Server, you can use the `CROSS APPLY` syntax:
```
SELECT
a.id, a.age, a.education,
b.id AS b_id, b.age AS b_age, b.education AS b_education
FROM tableB AS b
CROSS APPLY
( SELECT TOP (1) a.*
FROM tableA AS a
WHERE ABS(a.age - b.age) <= 2
AND ABS(a.education - b.education) <= 2
... | Is it possible to left join two tables and have the right table supply each row no more than once? | [
"",
"sql",
"left-join",
""
] |
I have access database called road.mdb.
Inside road.mdb, I have a linked SQL table and
the table name is student.
I can insert records using query design in MSAccess
But I cannot update nor Delete
when run delete query below, the error is: could not delete from specified table
```
delete from student where studen... | I SOLVED this by adding primary key to the SQL table and re linked the table to ACCESS
Thanks everyone... | In the case that you can't manipulated the table on SqlServer, you can get around the problem by telling Access which/s column/s are meant to be the primary key. This is done on the last step of creating a Linked table, the window title is "Select Unique Record Identifier". | cannot delete and update records on access linked table | [
"",
"sql",
"ms-access",
""
] |
When I use an if statement to get a result like this:
```
SELECT
IF(huxwz_user_orders.year = YEAR(CURDATE()) + 1, huxwz_user_orders.plannedweek + 52, huxwz_user_orders.plannedweek) as PlannedWeekG
```
When I used PlannedWeekG in my query like this: `WHERE PlannedWeekG > 0`
It's giving me an error "Unknown column 'P... | You need to use 'HAVING' in place of 'WHERE' to look at the derived result. Since PlannedWeekG is not a column in the DB, 'HAVING' is the magic to making this work ;) | You can use the `Having` clause in mysql:
```
SELECT
IF(huxwz_user_orders.year = YEAR(CURDATE()) + 1, huxwz_user_orders.plannedweek + 52, huxwz_user_orders.plannedweek) as PlannedWeekG
HAVING PlannedWeekG > 0
``` | Columns defined through if statement | [
"",
"mysql",
"sql",
""
] |
In mysql - table like this:
```
ID Name Value
1 Color Blue
1 Weight 50
1 Type Fruit
2 Color Red
2 Weight 40
3 Color Yellow
```
I want to get a count of distinct ID's that have a name/characteristic of 'Type' and a distinct count of ID's that don't. The first one (those that do) is e... | This is similar to [SQL Query User has one record in the table but not another one](https://stackoverflow.com/questions/18896462/sql-query-user-has-one-record-in-the-table-but-not-another-one/18896706#18896706)
You can select where the id is not in a subquery looking for ids that have type
```
select count(id) from t... | ```
SELECT id FROM test GROUP BY id HAVING
CONCAT(",",CONCAT(GROUP_CONCAT(name), ","))
NOT LIKE '%,Type,%'
```
will give you all ids without `Type`: <http://sqlfiddle.com/#!2/30837/1>
(Concat with `,` ensures, that you are not matching `XType` by accident.)
while
```
SELECT COUNT(id) AS count, GROUP_CONCAT(id) AS ... | Get count of ID for name-value pair when name doesn't exist | [
"",
"mysql",
"sql",
"t-sql",
""
] |
I am trying to create a stored that will some values, one of the value is column name and a value.
I've tried the following code
```
create PROC SelectDynamic
@DateFrom DATETIME,
@DateTo DATETIME,
@ColumName NVARCHAR(50),
@ColumID INT
AS
DECLARE @Sql NVARCHAR(MAX)
SET @Sql=
'
SELECT
*
FROM
Ticket t
WHER... | You have to escape the quotation marks when building a dynamic query.
Thus, your @SQL variable should be something like this
```
SET @Sql= 'SELECT * FROM Ticket t WHERE t.TicketDate BETWEEN ''' + CAST(@DateFrom AS NVARCHAR) + ''' AND ''' + CAST(@DateTo AS NVARCHAR) + ''' AND ' + @ColumName + '=' + CAST(@ColumID AS N... | ```
Try this
declare @DateFrom DATETIME=getdate(),
@DateTo DATETIME=getdate(),
@ColumName NVARCHAR(50)='A',
@ColumID INT=1
DECLARE @Sql NVARCHAR(MAX)
SET @Sql=
'
SELECT
*
FROM
Ticket t
WHERE t.TicketDate BETWEEN '''+ convert(varchar,@DateFrom,110) +''' AND ''' + convert(varchar,@Dat... | create Dynamic where in sql SP | [
"",
"sql",
"sql-server",
"stored-procedures",
"dynamic",
"where-clause",
""
] |
I have two tables, a USER table which contains all current users. The next table is called tasks and has a lot of information, one of the columns is PointPerson which is the same as one of the columns in the user table. This column has entries for people who are not users anymore. This is what I want to get from a SELE... | Try this:
```
SELECT DISTINCT TSK.PointPerson FROM [Task] AS TSK
WHERE TSK.PointPerson NOT IN (
SELECT DisplayName FROM [User]
)
```
Or a different approach:
```
SELECT DISTINCT TSK.PointPerson FROM [Task] AS TSK
LEFT JOIN [User] AS U ON U.DisplayName = TSK.PointPerson
WHERE U.DisplayName IS NULL
``` | You may try like this:-
```
SELECT DISTINCT TSK.PointPerson
FROM [Task]
WHERE NOT EXISTS
(SELECT DisplayName
FROM User
WHERE Task.name = User.name)
```
or using a LEFT JOIN like this:-
```
SELECT DISTINCT TSK.PointPerson
FROM Task t1
LEFT JOIN User t2 ON t2.name = t1.name
WHERE t2.name IS NULL
``` | SELECT all elements that don't exist in another table | [
"",
"sql",
"sql-server",
""
] |
There are two tables.
Visits (Parent)
VisitDocs (Child)
I need to show all the visits which has at least docType 3 and doesn't have DocType 1 and 2. There are different DocTypes 1 to 15.
Example:

Result should be 101 because visit 101 doesn't hav... | Answer above seems very close, just duplicated a similar structure and tested. My revised select below (just removed the 'AS' keyword and changed the last 'NOT IN' to 'IN' and it seems to work for me.
```
SELECT v.visitID
FROM Visits v
WHERE EXISTS(SELECT *
FROM VisitDocs d
WHERE d.VisitID = v.VisitID
AND d.... | Try this. I am sure you can do this via a couple JOINs (or at least part of it) but you did not request what your return columns should be
```
SELECT v.visitID
FROM Visits AS v
WHERE EXISTS(SELECT *
FROM VisitDocs AS d
WHERE d.VisitID = v.VisitID
AND d.docType = 3)
AND NOT EXISTS(SELECT *
... | How to check if a column A IN (3,4,5) and A NOT IN (1,2) | [
"",
"mysql",
"sql",
""
] |
I'm trying to create a query that only returns rows with objects that have three or more orders in a week's timeframe and are only orders submitted after 9/1/13.
```
SELECT OrderID, DateSubmitted, ObjectID = i.ObjectID
FROM dbo.Object i
JOIN dbo.Order j
ON i.ObjectID = j.ObjectID
WHERE DateSubmitted >= '9/1/2013'
```
... | based on your last comments the query you looking for is very simple. use the DatePart function and find out WEEK of that object's order-date. check the below query. also unless you data base is configured already by default Sunday(int 7) is the First Day set in the SQL server. so you for this query purpose you need to... | Try:
```
SELECT ObjectID
FROM dbo.Object i
JOIN dbo.Order j ON J.ObjectID = i.ObjectID
WHERE DateSubmitted >= '9/1/2013'
GROUP BY ObjectID
HAVING COUNT(1) >=3
``` | Assistance with creating SQL query | [
"",
"sql",
"sql-server",
""
] |
Is it possible to create a column within a MySQL structure that automatically sums two other columns?
So if I have a table called TABLE:
`Column A, Column B, and Column C.`
I would want `Column C` to automatically sum `Column A` and `Column B`.
Is that possible?
If A changes, C changes.
If it possible than how.an... | With a trigger:
```
DELIMITER $$
CREATE TRIGGER myTableAutoSum
BEFORE INSERT ON `myTable` FOR EACH ROW
BEGIN
SET NEW.ColumnC = NEW.ColumnA + NEW.ColumnB;
END;
$$
DELIMITER ;
```
Then this query:
```
INSERT INTO myTable (ColumnA, ColumnB) values(1, 1), (2, 3), (1, 4);
```
Will result in rows:
```
ColumnA Colum... | You can achieve this with a VIEW:
```
CREATE TABLE table1 (a INT, b INT);
CREATE
OR replace VIEW V_TABLE AS
SELECT a, b, a + b AS c
FROM table1;
```
`sqlfiddle` | Calculate two columns they automatic put into total column | [
"",
"mysql",
"sql",
""
] |
Here is some SQL to set up with a very simple table.
```
CREATE TABLE CC_TEST2
("CURRENCYID" NUMBER NOT NULL ENABLE,
"NAME" NVARCHAR2(255)) ;
insert into CC_TEST2 (select 1,'Testing issue'from dual);
commit;
```
Then this recreates the issue
```
SELECT (step.Name ||
'Commentary of 1234567890 1234567890... | If "NAME" NVARCHAR2(255) is changed to "NAME" VARCHAR2(255) (i.e by using varchar2) you won't get any issue. You can test the same at
<http://sqlfiddle.com/#!4/cefd8/2> | There seems to be some strangeness with NVARCHAR2 and string concatenation.
See <http://sqlfiddle.com/#!4/936c4/2>
My understanding based on running the various statements in the SQL Fiddle is that the string constant on the right hand side of the concatenation operator || is also treated as an NVARCHAR2, and can be ... | Why am I getting ORA-01401: inserted value too large for column - when I'm not inserting? | [
"",
"sql",
"oracle",
""
] |
Schema is below:
Ships(name, yearLaunched, country, numGuns, gunSize, displacement)
Battles(ship, battleName, result)
where name and ship are equal. By this I mean if 'Missouri' was one of the tuple
results for name, 'Missouri' would also appear as a tuple result for ship.
(i.e. name = 'Missouri' , ship = 'Missouri... | The problem in your query is that the subquery has no column named `name`.
Anyway, to find the largest amount of guns, just use `SELECT MAX(gunSize) FROM Ships`.
To get all ships with that number of guns, you need nothing more than a simple comparison with that value:
```
SELECT name
FROM Ships
WHERE gunSize = (SELEC... | It does not exist because you are trying to alias a subquery in the 'Where' clause, instead of aliasing specific column from a table. In order to identify the ship with the most guns you could try something like:
```
with cte as (select *
,ROW_NUMBER() over (order by s.gunsize desc) seq
from ships s )
... | SQL Query: Largest number of guns | [
"",
"sql",
"sqlite",
"max",
""
] |
I have a value in a table that was changed unexpectedly. The column in question is `CreatedDate`, which is set when my item is created, but it's being changed by a stored procedure.
Could I write some type of `SELECT` statement to get all the procedure names that reference this column from my table? | One option is to create a script file.
Right click on the database ***-> Tasks -> Generate Scripts***
Then you can select all the stored procedures and generate the script with all the sps. So you can find the reference from there.
Or
```
-- Search in All Objects
SELECT OBJECT_NAME(OBJECT_ID),
definition
FROM sys.s... | If you want to get stored procedures using specific column only, you can use try this query:
```
SELECT DISTINCT Name
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%CreatedDate%';
```
If you want to get stored procedures using specific column of table, you can use below query :
```
SELECT DISTINCT Nam... | Find all stored procedures that reference a specific column in some table | [
"",
"sql",
"sql-server",
"select",
"find",
""
] |
I am trying to do a SQL query and to build the where condition dynamically depending if the parameters are null or no. I have something like this:
```
SELECT tblOrder.ProdOrder, tblOrder.Customer FROM tblOrder
CASE WHEN @OrderId IS NOT NULL
THEN
WHERE tblOrder.OrderId = @OrderId
ELSE
END
CASE WHEN @OrderCustomer IS ... | This should do what you want:
```
SELECT tblOrder.ProdOrder, tblOrder.Customer
FROM tblOrder
WHERE ( @OrderId IS NULL OR tblOrder.OrderId = @OrderId )
AND ( @OrderCustomer IS NULL OR tblOrder.OrderCustomer = @OrderCustomer )
OPRION (RECOMPILE)
```
But as commented you should include the OPTION RECOMPILE hint, o... | You can't dynamically write the `WHERE` clause, but you can use compound statements to achieve the desired effect.
Since in SQL `NULL` is **never** equal to any value, you can actually achieve a pretty elegant query:
```
SELECT tblOrder.ProdOrder, tblOrder.Customer
FROM tblOrder
WHERE
-- Can only be true if @Ord... | SQL query where parameters null not null | [
"",
"sql",
"sql-server-2008",
"t-sql",
"sql-server-2008-r2",
"case",
""
] |
I am creating a database which stores arbitrary date/time ranges in PostgreSQL 9.2.4. I want to place a constraint on this database which forces the date/time ranges to be non-overlapping, and non-adjacent (since two adjacent ranges can be expressed as a single continuous range).
To do this, I am using an `EXCLUDE` co... | [Range types](https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-CONSTRUCT) consist of lower and upper bound, and each can be included or excluded.
The canonical form (and default for range types) is to *include* the lower and *exclude* the upper bound.
### Inclusive bounds `'[]'`
You could include ... | You can rewrite the exclude with the range type introduced in 9.2. Better yet, you could replace the two fields with a range. See "Constraints on Ranges" here, with an example that basically amounts to your use case:
<http://www.postgresql.org/docs/current/static/rangetypes.html> | Preventing adjacent/overlapping entries with EXCLUDE in PostgreSQL | [
"",
"sql",
"postgresql",
"datetime",
"range-types",
"exclusion-constraint",
""
] |
I'm looking to show on 1 line my clients name and all of their check dates for the month of January in 2014. Some clients may have 5 check dates in the month while other may only have 1 or 3. Is there a way to make this happen? Using this SQL query:
```
SELECT CC.co, checkDate FROM CCalendar CC
INNER JOIN CInfo CI... | OK, What you need to use here is a combination of both [PIVOT](http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx) and [ROW\_NUMBER](http://technet.microsoft.com/en-us/library/ms186734.aspx).
Your statment should be close to this:
```
SELECT co, [1] as checkDate1, [2] checkDate2, [3] checkDate3, ... | You're what you're looking for is a function similar to MySql's `group_concat` function, only in SQL Server instead.
This is probably a bad idea to do this in your query... instead, you should handle this in your UI / front-end, and build up your comma separated `checkDate` column there instead.
However, if you're st... | is there a way to show this SQL query on 1 line? | [
"",
"sql",
"sql-server",
""
] |
Edit:
Sorry I did not clarify in beginning. CompanyType is smallint, not null and TotalLicenses is int, null
Basically I only want to check that `TotalLicenses > 0 if C.CompanyType != 4`
I looked at a few reference guides and tutorials, but I couldn't find one that confirmed that I am using CASE WHEN how I intend to... | It is not that much different from the way you described it:
```
update WebCatalog.Published.DemoTracking
set Purchased = 1
from WebCatalog.Published.Company C
inner join WebCatalog.Published.RCompany RC
on C.RCompany = RC.Link
inner join WebCatalog.Published.DemoTracking DT
on ... | I think you want:
```
and ( C.CompanyType <> 4 AND C.TotalLicenses > 0
OR C.CompanyType = 4 AND C.TotalLicenses >= 0
)
```
which can be simplified (under the assumption that these two columns are not nullable) to:
```
and ( C.TotalLicenses > 0
OR C.CompanyType = 4 AND C.TotalLicenses = 0
)
```
which... | Am I using CASE WHEN Correctly? | [
"",
"sql",
"case",
"case-when",
""
] |
Yes, you can find similar questions numerous times, but:
the most elegant solutions posted here, work for SQL Server, but not for Sybase (in my case Sybase Anywhere 11). I have even found some Sybase-related questions marked as duplicates for SQL Server questions, which doesn't help.
One example for solutions I liked,... | Ok, now that I know the `ROWID()` function, solutions for tables with primary key (PK) can be easily adopted. This one first selects all rows to keep and then deletes the remaining ones:
```
DELETE FROM #TestTable
FROM #TestTable
LEFT OUTER JOIN (
SELECT MIN(ROWID(#TestTable)) rowid
FROM #TestTable
GROUP BY Colu... | If all fields are identical, you can just do this:
```
select distinct *
into #temp_table
from table_with_duplicates
delete table_with_duplicates
insert into table_with_duplicates select * from #temp_table
```
If all fields are not identical, for example, if you have an id that is different, then you'll need to ... | How to delete duplicate rows in sybase, when you have no unique key? | [
"",
"sql",
"sybase",
"duplicates",
"sqlanywhere",
""
] |
In SQL 2008 Im trying to combine the data from 4 columns into a single column. I have searched and tried several different things but none have worked. My latest attempt has been :
```
SELECT [2012 Notes] + [2012 STEPS TAKEN TO REMEDY ISSUES] + [2013 NOTES] + [2013 STEPS TAKEN TO REMEDY ISSUES] AS 'ConcatNotes'
FROM E... | That should work - you probably have some NULLS.
try
```
SELECT ISNULL([2012 Notes],'') + ISNULL([2012 STEPS TAKEN TO REMEDY ISSUES],'') + ISNULL([2013 NOTES],'') + ISNULL([2013 STEPS TAKEN TO REMEDY ISSUES],'') AS 'ConcatNotes'
FROM ECRSurvey
```
or to update
```
UPDATE ECRSurvey Set UserNotes = ISNULL([2012 Notes... | If any of those columns contain NULLs, the result will be NULL. You'll want to coalesce or isnull checks on the fields. | How can I combine 4 columns of data into a single column? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I want to upload data from a local SQL Server 2008 database to web server database within particular time.
I.e. suppose my database runs on local host and some inserts, updates and deletes are performed on local database. Now I want to upload that data to the web server.
How it will happen?
Both database are structu... | You should use sql server Copy database functionality.
Connect to Database server >> Right Click on any one database >> click on TASk >> Select Copy Database.. Option..
This Sql Copy Database wizard will copy your whole database from one server to another server. you can copy this to you webserver also.
Hope this wi... | You can either do it manually (for example, using a program like <http://www.red-gate.com/products/sql-development/sql-data-compare/>) or you can make scripts/applications that do it for you.
Then you can either run those script manually or set up various automated jobs to do it, in various types of software (deploy m... | Upload local SQL Server 2008 database to web server within particular time | [
"",
"asp.net",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have the following tables:
`account`
```
+------------+--------------+
| account_id | account_name |
+------------+--------------+
| 452 | a |
| 785 | b |
| 985 | c |
+------------+--------------+
```
and
`task`
```
+---------+------------+------------+
| tas... | You can either use analytics:
```
SELECT account_name, task_id
FROM (SELECT a.account_name,
t.task_id,
row_number()
over(PARTITION BY a.account_id ORDER BY t.task_date) task_num
FROM account a
INNER JOIN task t ON a.account_id = t.account_id
... | Another approach, a bit shorter:
```
select max(a.accountname) as account_name
, max(t.taskid) keep(dense_rank first
order by t.taskdate) as task_id
from account1 a
join task t
on (a.accountid = t.accountid)
group by a.accountid
```
result:
```
ACCOUNT_NAME TASK_ID
-------... | Show the oldest or newest records without showing the date | [
"",
"sql",
"oracle",
""
] |
Quite a lot of database scripts are of the form:
```
IF NOT EXISTS(SELECT * FROM Countries WHERE Name = 'France')
INSERT INTO(Countries)
```
However, I've also seen people do:
```
IF NOT EXISTS(SELECT CountryID FROM Countries WHERE Name = 'France')
INSERT INTO(Countries)
```
And even:
```
IF NOT EXISTS(SELECT 1 FR... | I think it was back in the 6.5 - 7 period of SQL Server that they made the query optimizer smart enough to know that:
```
IF NOT EXISTS(SELECT * FROM Countries WHERE Name = 'France')
```
Does not actually need to return any row data. The advice to use `SELECT 1` pre-dates that, yet continues on as a myth.
Arguably, ... | No,
sql server is smart enough to make this optimization for you. | When using "IF NOT EXISTS(SELECT..." in Sql Server, does it matter which columns you choose? | [
"",
"sql",
"sql-server",
""
] |
SQlite, Android, true story. I have a table, which I use as a cache:
```
CREATE TABLE cache(key TEXT, ts TIMESTAMP, size INTEGER, data BLOB);
CREATE UNIQUE INDEX by_key ON cache(key);
CREATE INDEX by_ts ON cache(ts);
```
During app lifetime I fill the cache and at some point I want to clear it out and drop `N` record... | You are working on a database with "big" data - ie, each blob using multiple pages.
At some point near optimal performance you will reach a limit you can't improve.
Checking all your choices, I see different behaviors, not just different algorithms.
[1] This one shouldn't be terrible slow as long as you use a transa... | Apparently, what is slow is not finding the records to be deleted, but the actual deletion itself.
Check if [PRAGMA secure\_delete](http://www.sqlite.org/pragma.html#pragma_secure_delete) is set by default in your Android's SQLite.
You should just disable it, just to be sure.
You do not need to run `VACUUM`; SQLite a... | SQLite: efficient way to drop lots of rows | [
"",
"android",
"sql",
"sqlite",
""
] |
I've got 3 Tables:
```
tblCustomer
CustomerID CustomerName
1 Customer 1
2 Customer 2
tblOrder
OrderID CustomerID OrderTypeID LoanNumber
1 1 1 98513542
2 1 1 71283527
3 1 1 10268541
4 1 1 ... | You need to use grouping and aggregation:
```
SELECT tblCustomer.CustomerID, tblCustomer.customerName, tblOrderType.OrderTypeName,
count (tblOrder.OrderID) asOrderCOunt
FROM tblCustomer
INNER JOIN tblOrder
ON tblCustomer.CustomerID = tblOrder.CustomerID
INNER JOIN tblOrderType
ON tblOrderType.OrderTypeID = tblOrde... | The error message does tell you the issue. Whenever you use an aggregation operator (`COUNT`, `SUM`, `AVG`, etc.), you have to tell the database how these should be aggregated together. You do this with a [`GROUP BY`](http://technet.microsoft.com/en-us/library/ms177673.aspx) statement (the link there is for SQL Server,... | How to get the count and display only one row | [
"",
"sql",
""
] |
I have got a sample table like this.
```
ID Name
1 Jane
2 John
3 Kevin
4 George
5 Jane
```
The result I would like to get from the query would be a table of two values:
```
ID Name
1 Jane
5 Jane
```
I know this could ... | I usually recommend using `Joins` rather than `exist,in or not in` in the codes.
```
Select A.ID,B.Name from Tablename A
inner join Tablename B
on A.Name = B.Name
where a.id <> b.id
```
and
I don't usually recommend this, ID's should normally be joined rather than the name.
here is the [DEMO](http://sq... | One way of doing this is by using `EXISTS()`.
```
SELECT *
FROM tablename a
WHERE EXISTS
(
SELECT 1
FROM tableName b
WHERE a.Name = b.name
GROUP BY Name
HAVING COUNT(*) > 1
)
```
* [SQLFiddle Demo](http://sqlfiddle.com/#!2/28e7... | Compare rows in SQL | [
"",
"sql",
"compare",
""
] |
I have two tables in a SQL Server 2008 R2 database. I want to create a View where it has all the columns from Table1 and receives an additional column called "Photo\_Exist" appended to it and it is assigned "1" or "True" if ID in Table1 exists in Table2.
**Table1**:
ID, Col1, Col2, ..., Coln
**Table2**:
Linked\_ID
*... | Try this
```
SELECT *,
CASE WHEN EXISTS (SELECT * FROM Table2 AS T2 WHERE T2.Linked_ID=T1.ID)
THEN 1
ELSE 0
END AS Photo_Exist
FROM Table1 AS T1
``` | Create a view using this query. This should help
```
select table1.*, case when table2.linked_id is null then 0 else 1 end as Photo_exist
from table1 left outer join table2 on table1.id =table2.linked_id
``` | Set value to a column on the row where its ID exists in another table | [
"",
"sql",
"sql-server",
"database",
"view",
"sql-server-2008-r2",
""
] |
> Exercise 39: Define the ships that "survived for future battles";
> being damaged in one battle, they took part in another.
Database Schema: <http://www.sql-ex.ru/help/select13.php#db_3>
My approach:
```
SELECT distinct o.ship from Outcomes o
WHERE o.RESULT = 'damaged'
AND exists (select 1 FROM Outcomes o2 WHERE ... | Solved! needed to add Distinct
```
select distinct kk.ship from
(Select ship,date from outcomes oo,battles bb where oo.battle=bb.name) tt
inner join
(Select ship,date as damagedate from outcomes oo,battles bb where result='damaged' AND oo.battle=bb.name) kk
ON tt.ship=kk.ship AND tt.date>kk.damagedate
``` | ```
with a as (select * from outcomes o join battles b on o.battle=b.name)select distinct a1.ship from a a1, a a2 where a1.ship=a2.ship and a1.result='damaged'and a1.date<a2.date
``` | sql-ex exercise 39 failed on second server error? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I'm running into some issues with long query times on very basic queries. This is my first time working with a bigger table (12.5 mil rows) and I'm just trying to figure out what might be bottlenecking or what I can do to improve performance. All data is in 1 table.
**Server Specs:**
Windows Server 2008 R2 Standard
I... | Yes there are 2 glaring issues. In the first query you have no criteria -- hence you are asking for the entire sales table to be read, grouped and summarized. The grouping is going to create a temporary table as well. Hence you will make a table scan and that will be limited to what the hardware can provide in terms of... | Query 1:
```
SELECT Store, sum(Total)
FROM sales
GROUP BY Store ;
```
Add an index on `(Store, Total)`:
```
ALTER TABLE sales
ADD INDEX store_total_IX -- pick a name for the index
(store, total) ;
```
---
Query 2:
```
SELECT Date, Register, Customers, Items, Total
FROM sales
WHERE Date(Date) = D... | Database Performance Problems | [
"",
"mysql",
"sql",
"performance",
""
] |
So I have two tables, players and matches with structures like so:
```
Table "public.players"
Column | Type | Modifiers
--------+---------+------------------------------------------------------
id | integer | not null default nextval('players_id... | if you want to select matches won by `<player1>` or `<player2>`, you can use this query:
```
with cte_winners as (
select
id, case when winner then player1 else player2 end as player
from public.matches
)
select *
from cte_winners
where player in (<player1>, <player2>)
```
**update**
to get desired o... | ```
SELECT id, name, wins, losses, rating
,count(CASE WHEN winner THEN m.player1 = p.id ELSE m.player2 = p.id END
OR NULL) AS wins_v_opp
,count(CASE WHEN winner THEN m.player2 = p.id ELSE m.player1 = p.id END
OR NULL) AS loses_v_opp
FROM (
SELECT *, COALESCE(lag(p.id) OVER(), ... | Summarize totals given multiple conditions | [
"",
"sql",
"postgresql",
"plpgsql",
""
] |
My tables:
feeds\_time:
```
user_id | time
1 | 123123
2 | 1231111
3 | 1233223
...
```
users\_follow
```
user_id | follow_id
1 | 2
1 | 3
2 | 3
```
And table posts - but this is not important in this problem.
Actually my query looks like:
```
SELECT `id`, `name`, `user_id`, `tim... | You can try this
Use join
```
SELECT A.`id`, A.`name`, A.`user_id`, A.`time`, A.'posts' as `what`
FROM `posts` A
JOIN feeds_time B ON A.user_id = B.user_id
WHERE A.`user_id` IN (SELECT `follow_id`
FROM users_follow WHERE user_id = posts.user_id)
AND A.time > B.time
``` | Try this:
```
SELECT * FROM (SELECT `id`, `name`, `user_id`, `time`, 'posts' as `what`
FROM `posts`
WHERE `user_id` IN (SELECT `follow_id` FROM users_follow
WHERE user_id = posts.user_id)) a, feeds_time
where a.`time` > feeds_time.time and a.`user_id` = feeds_time.`user_id`
``` | SELECT from 3 tables and "IN" | [
"",
"mysql",
"sql",
""
] |
If I write a hive sql like
```
ALTER TABLE tbl_name ADD PARTITION (dt=20131023) LOCATION 'hdfs://path/to/tbl_name/dt=20131023;
```
How can I query this location about partition later? Because I found there is some data in location but I can't query them, hive sql like
```
SELECT data FROM tbl_name where dt=20131023;... | ```
show table extended like 'tbl_name' partition (dt='20131023');
```
> [Show Tables/Partitions Extended](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-ShowTables/PartitionsExtended)
>
> `SHOW TABLE EXTENDED` will list information for all tables matching the given regular expre... | Do a describe on the partition instead of the full table.
This will show the linked location if it's an external table.
```
describe formatted tbl_name partition (dt='20131023')
``` | How to know location about partition in hive? | [
"",
"sql",
"hadoop",
"hive",
""
] |
I have data this is linked from SQL Server into an excel document. The column format on the SQL Server is `datetime2`.
When I get the data via an ODBC connection it comes across as a string?
I tried using
```
CAST(column AS DATE )
```
but that didn't work.
I tried reformatting via
```
CONVERT(VARCHAR(10), column,... | It appears that Excel and Access as well don't like the SQL Server datetime2 format.
I have converted the data into datetime format and that seems to be working now. | You can simply convert date in the Excel to the following format:
> "YYYY-MM-DD HH:mm:ss"
This is the [default ODBC canonical format](http://msdn.microsoft.com/en-us/library/ms187928.aspx). In this case the implicit conversion will be made and the correct results will be achieved.
Another way is to try to perform co... | MS SQL Server Dates Excel | [
"",
"sql",
"sql-server",
"excel",
"datetime",
"odbc",
""
] |
I am a C# developer, I am not really good with SQL. I have a simple questions here. I need to move more than 50 millions records from a database to other database. I tried to use the import function in ms SQL, however it got stuck because the log was full (I got an error message The transaction log for database 'mydata... | If you are moving the entire database, use backup and restore, it will be the quickest and easiest.
<http://technet.microsoft.com/en-us/library/ms187048.aspx>
If you are just moving a single table read about and use the BCP command line tools for this many records:
> The bcp utility bulk copies data between an insta... | The fastest and probably most reliable way is to bulk copy the data out via SQL Server's [bcp.exe utility](http://technet.microsoft.com/en-us/library/ms162802.aspx). If the schema on the destination database is *exactly* identical to that on the source database, including nullability of columns, export it in "native fo... | SQL, moving million records from a database to other database | [
"",
"sql",
"sql-server",
""
] |
I am working on a project that accepts 3 different parameters, the date is required and the First and Last name are optional. We setup the query below, but even if I change the parameters on the report (SSRS) it still looks at @LetterCreated as being '1/1/1950', any ideas on how I can get this to just accept the parame... | I'm guessing here but what you may want is
* IF parameter `@LetterCreated` is null then it should not be used as a filter at all
* IF the data in `RedFlagData.LETTERCREATETIME` is Null then it should be matched to a filter date of `'07/05/81'` FWR
Assuming that you have the 'allow nulls' check on the `RDL/RDLC` set f... | You are setting the `@lettercreated` date in the procedure. Variables defined within the procedure are not visible outside it.
You should declare the parameters as parameters, and set the default in the declaration
```
ALTER PROC yourproc
(
@LetterCreated DATETIME = '1950-1-1',
@FirstName VARCHAR(20) = '',
@LastName ... | Passing Parameters to a stored Procedure | [
"",
"sql",
"sql-server",
"sql-server-2008",
"stored-procedures",
"reporting-services",
""
] |
I have a database and a lot of tables inside it. I wrote some information into the each table and column's decription part. And now using query i want to see all table and columns descriptions.
Note: DATABASE -> ms sql server
Can you please help me ? | Check this query:
```
SELECT
t.name AS TableName
, td.value AS TableDescription
, c.name AS ColumnName
, cd.value AS ColumnDescription
FROM sys.tables t
INNER JOIN sys.columns c ON t.object_id = c.object_id
LEFT JOIN sys.extended_properties td
ON td.major_id = t.object_id
AND td.minor_id = 0
A... | You can see that using [INFORMATION\_SCHEMA](http://technet.microsoft.com/en-us/library/ms186778.aspx)
To get columns for each table you can do:
```
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
```
To get table information you can do:
```
SELECT * FROM INFORMATION_SCHEMA.TABLES
``` | Getting the decriptions of the tables and columns via a sql statement | [
"",
"sql",
"sql-server",
""
] |
I can `INSERT` a row into SQL like this:
```
INSERT INTO MyTable VALUES (0, 'This is some text...');
```
However, what if I wanted *This is some text...* to be the contents of `C:\SomeFile.txt`. Is there a method in Oracle that makes this possible?
I dug through the Docs a bit and found the `LOAD FILE` method, howev... | You should never be reading files from the DATABASE SERVER's file system to insert into the db.
Why do you want to do this? You really should read the file in your application code, then insert the string or binary data through standard SQL.
If you really must do this you will need to use the oracle [UTL\_FILE](http:... | To do this I think you would have to use PL/SQL. This is technically an "advanced SQL".
search up a bit about PL/SQL. You can copy your SQL directly into PL/SQL and use the same database. | Inserting a single row in SQL, but loading the contents from a file | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I have a Listing model which has a category column and size column. For each category I have an array of sizes. I want to return only the Listings in each category that correspond to the size arrays. (I also have an array of designers as a condition with params[:designer].)
Params hash:
```
params[:category] => ['top... | I ended up using Arel which is pretty good. Arel lets you build up whatever query you want and then call it on Model.where(). It's kind of complicated but was the only solution I found that worked.
```
t = Listing.arel_table
query = t[:category].eq('rooney')
params[:category].each do |category|
if params[category]
... | You could pass an array to `where`:
```
@listings = Listing.where(category: params[:category], s...
``` | Reduce loop of activerecord queries into one query | [
"",
"sql",
"ruby-on-rails",
"activerecord",
""
] |
I have a following query:
```
UPDATE TOP (@MaxRecords) Messages
SET status = 'P'
OUTPUT inserted.*
FROM Messages
where Status = 'N'
and InsertDate >= GETDATE()
```
In the Messages table there is priority column and I want to select high priority messages first. So I need an ORDER BY. But I do not need to hav... | you can use common table expression for this:
```
;with cte as (
select top (@MaxRecords)
status
from Messages
where Status = 'N' and InsertDate >= getdate()
order by ...
)
update cte set
status = 'P'
output inserted.*
```
This one uses the fact that in SQL Server it's possible to update cte, ... | You can try sub query like
```
UPDATE Messages
SET status = 'P'
WHERE MessageId IN (SELECT TOP (@MaxRecords) MessageId FROM Messages where Status = 'N' and InsertDate >= GETDATE() ORDER BY Priority)
output inserted.*
``` | SQL UPDATE TOP with ORDER BY? | [
"",
"sql",
"sql-server",
""
] |
What's wrong with SQL code below:
```
INSERT INTO tbl_HAMP_Actions ( Loan_ID, Action_ID, Event_User, Event_Time, Event_Station, Reason_ID )
VALUES(3238, 3, 'CONTROL', Now(), 'CONTROL', (SELECT tbl_Reasons.Reason_ID
FROM tbl_Reasons
WHERE tbl_Reasons.Reason = 'Incorrect Information'));
``` | I don't think you can use subqueries as values in Access.
Try this instead:
```
INSERT INTO tbl_HAMP_Actions ( Loan_ID, Action_ID, Event_User, Event_Time, Event_Station, Reason_ID )
SELECT 3238, 3, 'CONTROL', Now(), 'CONTROL', Reason_ID
FROM tbl_Reasons
WHERE tbl_Reasons.Reason = 'Incorrect Information'
``` | ```
(SELECT tbl_Reasons.Reason_ID
FROM tbl_Reasons
WHERE tbl_Reasons.Reason = 'Incorrect Information')
```
could this part of the code return more than one row? If so then this will fail. | SQL Access Error - Syntax error in query expression | [
"",
"sql",
"ms-access",
"append",
""
] |
I have the following table in postgres:
```
create table1 (col1 character varying, col2 character varying);
```
My table has the following data:
```
col1 col2
Questions Tags Users
Value1 Value2 Val
```
I want find the length of col1 and col2 and when the length of values of column 1 and co... | Couldn't you just update them to contain only strings of length 6 at max?
I am no postrgres pro, so this is probably not the best method, but should do the job anyways:
```
UPDATE table1 SET col1 = SUBSTRING(col1, 1, 6) WHERE LEN(col1) > 6
UPDATE table1 SET col2 = SUBSTRING(col2, 1, 6) WHERE LEN(col2) > 6
``` | I'd suggest that you actually follow the advice from Postgres, rather than changing your data. Clearly, that column with a 2k character long string shouldn't be indexed -- or not with a btree index anyway.
If the idea behind the index is searching, use full text search instead:
<http://www.postgresql.org/docs/current... | sql query to truncate columns which are above specified length | [
"",
"sql",
"postgresql",
""
] |
I have a table in SQL Server with bundle of records. I want to convert the ID column which is Primary Key to an identity Column without loss of data. I thought of the following two approaches:
1. Create a new table with identity & drop the existing table.
2. Create a new column with identity & drop the existing column... | As you are using SQL Server 2012, another possible alternative could be to create a sequence object that has a starting value of the highest ID +1 already in your table, then create a default constraint for your column using GET NEXT VALUE FOR and reference your sequence object you just created. | This solution violates your point 2, but there is no other way and I think your aim is to keep the old values, because nothing else makes sense...
You could do the following:
1. make it possible to insert into identity columns in your table:
```
set identity_insert YourTable ON
```
2. add a new ID column to... | Convert an existing Column to Identity | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
I am a SQL beginner and I need to figure out this query: I have three tables joined together from which I am counting certain value, like this:
```
SELECT SEATS_MAX-COUNT(BOOKING_ID)
FROM FLIGHTS
INNER JOIN PLANES ON FLIGHTS.PLANE_ID=PLANES.PLANE_ID
LEFT JOIN BOOKINGS ON FLIGHTS.FLIGHT_ID=BOOKINGS.FLIGHT_ID
GR... | In the group by you need to have all the column not aggregated.
So you query has to become:
```
SELECT FLIGHTS.*,
SEATS_MAX-COUNT(BOOKING_ID)
FROM FLIGHTS
INNER JOIN PLANES
ON FLIGHTS.PLANE_ID = PLANES.PLANE_ID
LEFT JOIN BOOKINGS
ON FLIGHTS.FLIGHT_ID = BOOKING... | This should work:
```
SELECT flights.*, seats_max-booked_seats
FROM flights, (SELECT COUNT(*) booked_seats, flight_id
FROM bookings GROUP BY flight_id) book
WHERE flights.flight_id = book.flight_id
``` | SQL select all from one table of joint tables | [
"",
"sql",
"oracle",
"select",
""
] |
Is there a way to update all columns in table from
```
2010-12-31 23:59:59.000
```
to
```
2010-12-31 00:00:00.000
```
Something like this??
```
UPDATE t1
SET [Posting Date] = [Posting Date] with ms = 00:00:00.000
WHERE ms = other than 00:00:00.000
GO
``` | ```
UPDATE t1
SET [Posting Date] = cast([Posting Date] as date)
WHERE cast([Posting Date] as time) > '00:00'
``` | ```
UPDATE t1
SET [Posting Date] = CAST([Posting Date] as DATE)
``` | SQL datetime update time to 00:00:00 from all other time values | [
"",
"sql",
"sql-server-2008",
"t-sql",
"datetime",
"milliseconds",
""
] |
I want to match my user to a different user in his/her community every day. Currently, I use code like this:
```
@matched_user = User.near(@user).order("RANDOM()").first
```
But I want to have a different @matched\_user on a daily basis. I haven't been able to find anything in Stack or in the APIs that has given me i... | Whenever I find myself hankering for shared 'memory' or transient state, I think to myself "this is what (distributed) caches were invented for".
```
@matched_user = Rails.cache.fetch(@user.cache_key + '/daily_match', expires_in: 1.day) {
User.near(@user).order("RANDOM()").first
}
```
**NOTE**: While specifying a T... | How about using PostgreSQL's `SETSEED` function? I used the date to seed so that every day the seed will change, but within a day, the seed will be consistent.:
```
User.connection.execute "SELECT SETSEED(#{Date.today.strftime("%y%d%m").to_i/1000000.0})"
@matched_user = User.near(@user).order("RANDOM()").first
```
Yo... | Rails show different object every day | [
"",
"sql",
"ruby-on-rails",
"ruby",
"postgresql",
"activerecord",
""
] |
i have one interesting question, and could not resolve it. Please help!!!!
They are tables
```
t_employee
ID NUMBER,
DEPARTMENT_ID NUMBER,
CHIEF_ID NUMBER,
NAME VARCHAR2(100 BYTE),
SALARY NUMBER,
BIRTH_DATE DATE,
ADDRESS VARCHAR2(200 BYTE),
STATUS ... | Free form strings are seldom a good idea in databases, this query won't be able to use indexes which will most likely make it a slow performer;
```
WITH a AS ( SELECT TRIM(
REPLACE(
UPPER(
REGEXP_SUBSTR(ADDRESS, ',([^,]*),', 1, 1, 'i', 1)
... | Try the below:
```
SELECT regexp_substr(address, ',(.*?reg.*?),', 1, 1, null, 1) AS region, COUNT(*)
FROM t_employee
GROUP BY regexp_substr(address, ',(.*?reg.*?),', 1, 1, null, 1);
```
I would strongly advise however to refactor the schema and break the address into separate fields for street, city, region, etc. bef... | oracle sql select with employeees | [
"",
"sql",
"database",
"oracle",
"function",
""
] |
I have two tables:
```
CREATE TABLE "status" (
"id" integer NOT NULL PRIMARY KEY,
"created_at" datetime NOT NULL,
"updated_at" datetime NOT NULL);
CREATE TABLE "device" (
"id" integer NOT NULL PRIMARY KEY,
"created_at" datetime NOT NULL,
"updated_at" datetime NOT NULL,
"last_status_o... | ```
DELETE
status
FROM
status
LEFT JOIN device ON (status.id = last_status_object_id)
WHERE
device.id IS NULL
``` | ```
delete from status
where id not in (select last_status_object_id
from device);
```
Here we go, with demo in [sqlfiddle](http://sqlfiddle.com/#!9/19b06/2) | Delete all rows in one table that aren't referenced by another table | [
"",
"mysql",
"sql",
""
] |
I have following code in SQL Server,
```
declare @previouspulse int = 0
declare @previousox int = 0
declare @Pulse int = 0
declare @SpO2 int = 0
set @previouspulse = null
set @Pulse= 121
set @previousox = 56
set @SpO2 = null
IF @previouspulse <> @Pulse or @previousox <> @SpO2
select -1
else
select -2
```... | NULL values represent missing or unknown data.It is not possible to test for NULL values with comparison operators, such as =, <, or <> because comparison with unknown data results in an unknown data.
Use ISNULL operator to get correct results from comparison as:
```
declare @previouspulse int = 0
declare @previousox... | Here's the reason why,
```
@previouspulse <> @Pulse OR @previousox <> @SpO2
NULL OR NULL
NULL
```
since you have only two paths, it falls on `FALSE` block which results to `-2`. Whn comparing with `NULL` value use `IS NULL` or `IS NOT NULL`.
* [SQL Three-Valued ... | Issue related to not Equal to (<>) in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I would like to write an IN statement when setting the `RECEIPTIDS` variable, so that I can pass multiple values in that format into my query. I have tried the following:
```
DECLARE @RECEIPTIDS VARCHAR(2000)
SET @RECEIPTIDS = ('R00013','R00028')
```
However, I get the error:
> Incorrect syntax near ','. | You need extra single qoutes.
```
create table MyTable
(
ID varchar(50)
)
insert into MyTable values('R00013')
insert into MyTable values('R00028')
insert into MyTable values('R00015')
DECLARE @RECEIPTIDS VARCHAR(2000)
SET @RECEIPTIDS = ('''R00013'',''R00028''')
DECLARE @QU... | You need [table variable](http://blog.sqlauthority.com/2012/10/27/sql-server-storing-variable-values-in-temporary-array-or-temporary-list/) or [temp table](http://blogs.msdn.com/b/sqlserverstorageengine/archive/2008/03/30/sql-server-table-variable-vs-local-temporary-table.aspx).
```
DECLARE @RECEIPTIDS TABLE(val VARCH... | Declare multiple value variable in SQL | [
"",
"sql",
"sql-server-2008",
""
] |
`table1` has fields `id`, `a`, `b`.
`table2` has fields `id`, `a`.
I want to update `table1.a` with data from `table2.a` for the records with the same ID. `table1.c` should remain unchanged. Can I do that in one single query? | Just use `JOIN` with `UPDATE`:
```
UPDATE table1 LEFT JOIN table2 ON table1.id=table2.id SET table1.a=table2.a
```
-you may want to use `INNER JOIN` instead (if you want to update only records with id existing in both tables) | ```
update table1, table2 set table1.a=table2.a where table1.id=table2.id
``` | SQL update a list of key/values with one statement? | [
"",
"mysql",
"sql",
""
] |
```
ID name Dept Manager
101 Mukesh SW
102 Ram SW 101
103 sham SW 101
104 rahul SW 101
105 Rajat HQ
106 akhilesh HQ ... | Kindly find below query as you want. i created MyTest as table name which you need to replace.
```
SELECT
Case WHEN ISNULL(SecondTable.Id,0) = 0
THEN FirstTable.Dept
ELSE ''
END As Department,
Case WHEN ISNULL(SecondTable.Id,0) = 0
THEN Manager.Name
ELSE ''
END ... | What you are looking for is to retrieve the hierachical data, with sql 2008 you can use common table expression. check out this link [Recursive Queries Using Common Table Expressions](http://technet.microsoft.com/en-us/library/ms186243%28v=sql.100%29.aspx) the data output is flat (it will repeat SW and Mukesh for each ... | sql server desired output from tables | [
"",
"sql",
"sql-server-2008",
""
] |
How can i search for a particular date for eg: '2013-10-22' from teradata timestamp(6) field?
```
sel * from table A
where date = '2013-10-22';
```
I tried the above query which is throwing error. Please help! | You may try like this:-
```
sel * from table A
where date = date '2013-10-22';
```
Since in ANSI standard form (must be preceded by the keyword DATE)
Check out [this](http://www.teradataforum.com/l081007a.htm) | And more formally:
```
select *
from table A
where cast(timestamp_column as date) = date '2013-10-22';
```
I'm guessing that you were just showing an example, because I don't think you can have a column named `date`; it's a reserved word. The keyword "**date**" above is how you specific an ANSI date constant and is ... | query to return specific date from teradata timestamp(6) | [
"",
"sql",
"teradata",
""
] |
Is there something similar to `DATEFROMPARTS(year, month, day)` in SQL Server 2008? I want to create a date using the current year and month, but my own day of the month. This needs to be done in one line in order to be used in a computed column formula.
For Example (I'm not sure if it works because I do not have SQL ... | Using the `3` from your example, you could do this:
```
dateadd(dd, 3 -1, dateadd(mm, datediff(mm,0, current_timestamp), 0))
```
It works by finding the number of months since the epoch date, adding those months back to the epoch date, and then adding the desired number of days to that prior result. It sounds complic... | You could use something like this to make your own datetime:
```
DECLARE @year INT = 2012
DECLARE @month INT = 12
DECLARE @day INT = 25
SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @month) + '-' + CONVERT(VARCHAR, @day)
AS DATETIME)
``` | Creating date in SQL Server 2008 | [
"",
"sql",
"sql-server",
"sql-server-2008",
"date",
"calculated-columns",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.